diff options
| author | nsfisis <nsfisis@gmail.com> | 2024-07-28 00:57:07 +0900 |
|---|---|---|
| committer | nsfisis <nsfisis@gmail.com> | 2024-07-28 00:57:07 +0900 |
| commit | ab2a49654a7964bf9e6222b17676ca87588b88d8 (patch) | |
| tree | 4674b807c4e32efd9919e6ab90019e5b68a84d19 /backend/auth/jwt.go | |
| parent | b70fa3abf9c96871cc3e39090e9a00da4ad87b8b (diff) | |
| parent | 519008c4bae3db046004e4bc2aaa23a2e66311c7 (diff) | |
| download | phperkaigi-2025-albatross-ab2a49654a7964bf9e6222b17676ca87588b88d8.tar.gz phperkaigi-2025-albatross-ab2a49654a7964bf9e6222b17676ca87588b88d8.tar.zst phperkaigi-2025-albatross-ab2a49654a7964bf9e6222b17676ca87588b88d8.zip | |
Merge branch 'auth'
Diffstat (limited to 'backend/auth/jwt.go')
| -rw-r--r-- | backend/auth/jwt.go | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/backend/auth/jwt.go b/backend/auth/jwt.go new file mode 100644 index 0000000..aa35de6 --- /dev/null +++ b/backend/auth/jwt.go @@ -0,0 +1,54 @@ +package auth + +import ( + "time" + + "github.com/golang-jwt/jwt/v5" + echojwt "github.com/labstack/echo-jwt/v4" + "github.com/labstack/echo/v4" + + "github.com/nsfisis/iosdc-2024-albatross-backend/db" +) + +type JWTClaims struct { + UserID int `json:"user_id"` + Username string `json:"username"` + DisplayUsername string `json:"display_username"` + IconPath *string `json:"icon_path"` + IsAdmin bool `json:"is_admin"` + jwt.RegisteredClaims +} + +func NewJWT(user *db.User) (string, error) { + var iconPath *string + if user.IconPath.Valid { + iconPath = &user.IconPath.String + } + claims := &JWTClaims{ + UserID: int(user.UserID), + Username: user.Username, + DisplayUsername: user.DisplayUsername, + IconPath: iconPath, + IsAdmin: user.IsAdmin, + RegisteredClaims: jwt.RegisteredClaims{ + ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * 24)), + }, + } + token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) + return token.SignedString([]byte("TODO")) +} + +func NewJWTMiddleware() echo.MiddlewareFunc { + return echojwt.WithConfig(echojwt.Config{ + NewClaimsFunc: func(c echo.Context) jwt.Claims { + return new(JWTClaims) + }, + SigningKey: []byte("TODO"), + }) +} + +func GetJWTClaimsFromEchoContext(c echo.Context) *JWTClaims { + user := c.Get("user").(*jwt.Token) + claims := user.Claims.(*JWTClaims) + return claims +} |
