Implement hard-coded login
This commit is contained in:
parent
a5f0ea074c
commit
73d7424eed
69
main.go
69
main.go
@ -1,9 +1,74 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"github.com/labstack/echo"
|
||||
"github.com/labstack/echo/engine/standard"
|
||||
"github.com/labstack/echo/middleware"
|
||||
)
|
||||
|
||||
const (
|
||||
expiration = 72
|
||||
secret = "uditapbzuditagscwxuqdflgzpbu´ßiaefnlmzeßtrubiadern"
|
||||
)
|
||||
|
||||
func main() {
|
||||
fmt.Println("Hello World")
|
||||
e := echo.New()
|
||||
|
||||
// Middleware
|
||||
e.Use(middleware.Logger())
|
||||
e.Use(middleware.Recover())
|
||||
|
||||
// Login route
|
||||
e.POST("/login", login)
|
||||
|
||||
// Unauthenticated routes
|
||||
e.GET("/", accessible)
|
||||
e.GET("/hello", func(c echo.Context) error {
|
||||
return c.String(http.StatusOK, "Hello, World!")
|
||||
})
|
||||
|
||||
// Restricted group
|
||||
r := e.Group("/restricted")
|
||||
r.Use(middleware.JWT([]byte(secret)))
|
||||
r.GET("", restricted)
|
||||
|
||||
e.Run(standard.New(":1323"))
|
||||
}
|
||||
|
||||
func accessible(c echo.Context) error {
|
||||
return c.String(http.StatusOK, "Accessible")
|
||||
}
|
||||
func restricted(c echo.Context) error {
|
||||
user := c.Get("user").(*jwt.Token)
|
||||
name := user.Claims["name"].(string)
|
||||
return c.String(http.StatusOK, "Welcome "+name+"!")
|
||||
}
|
||||
func login(c echo.Context) error {
|
||||
username := c.FormValue("username")
|
||||
password := c.FormValue("password")
|
||||
|
||||
if username == "jan" && password == "passwort" {
|
||||
// Create token
|
||||
token := jwt.New(jwt.SigningMethodHS256)
|
||||
|
||||
// Set claims
|
||||
token.Claims["name"] = "Jan Bader"
|
||||
token.Claims["admin"] = true
|
||||
token.Claims["exp"] = time.Now().Add(time.Hour * expiration).Unix()
|
||||
|
||||
// Generate encoded token and send it as response.
|
||||
t, err := token.SignedString([]byte(secret))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.JSON(http.StatusOK, map[string]string{
|
||||
"token": t,
|
||||
})
|
||||
}
|
||||
|
||||
return echo.ErrUnauthorized
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user