/
auth.go
52 lines (39 loc) · 989 Bytes
/
auth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package app
import (
"errors"
"net/http"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/jovandeginste/workout-tracker/pkg/database"
"github.com/labstack/echo/v4"
)
var ErrInvalidJWTToken = errors.New("invalid JWT token")
func (a *App) createToken(u *database.User, c echo.Context) error {
token := jwt.New(jwt.SigningMethodHS256)
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
return ErrInvalidJWTToken
}
exp := time.Now().Add(time.Hour * 24 * 10)
claims["name"] = u.Username
claims["exp"] = exp.Unix()
t, err := token.SignedString(a.jwtSecret())
if err != nil {
return err
}
a.setTokenCookie(t, exp, c)
return nil
}
func (a *App) setTokenCookie(t string, exp time.Time, c echo.Context) {
cookie := new(http.Cookie)
cookie.Path = "/"
cookie.HttpOnly = true
cookie.Name = "token"
cookie.Value = t
cookie.Expires = exp
c.SetCookie(cookie)
}
func (a *App) clearTokenCookie(c echo.Context) {
exp := time.Now()
a.setTokenCookie("", exp, c)
}