85 lines
1.8 KiB
Go
85 lines
1.8 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())
|
||
e.Use(middleware.Static("static"))
|
||
|
||
a := e.Group("/api")
|
||
a.POST("/login", login)
|
||
|
||
// Unauthenticated routes
|
||
a.GET("/check", accessible)
|
||
a.GET("/hello", func(c echo.Context) error {
|
||
return c.String(http.StatusOK, "Hello, World!")
|
||
})
|
||
|
||
// Restricted group
|
||
r := a.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
|
||
}
|
||
|
||
cookie := new(echo.Cookie)
|
||
cookie.SetName("authentication")
|
||
cookie.SetValue(t)
|
||
cookie.SetExpires(time.Now().Add(expiration * time.Hour))
|
||
c.SetCookie(cookie)
|
||
|
||
return c.JSON(http.StatusOK, map[string]string{
|
||
"token": t,
|
||
})
|
||
}
|
||
|
||
return echo.ErrUnauthorized
|
||
}
|