75 lines
1.6 KiB
Go
75 lines
1.6 KiB
Go
package main
|
|
|
|
import (
|
|
"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() {
|
|
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
|
|
}
|