aboutsummaryrefslogtreecommitdiffhomepage
path: root/backend/auth/jwt.go
diff options
context:
space:
mode:
authornsfisis <nsfisis@gmail.com>2024-07-27 21:07:16 +0900
committernsfisis <nsfisis@gmail.com>2024-07-27 21:07:16 +0900
commit3ca36032c7aabbc7b8cee8f0f59d18d1264242ae (patch)
treede34134feb14d53f3a31e34ab8e2d8c9af9adc67 /backend/auth/jwt.go
parentb70fa3abf9c96871cc3e39090e9a00da4ad87b8b (diff)
downloadphperkaigi-2025-albatross-3ca36032c7aabbc7b8cee8f0f59d18d1264242ae.tar.gz
phperkaigi-2025-albatross-3ca36032c7aabbc7b8cee8f0f59d18d1264242ae.tar.zst
phperkaigi-2025-albatross-3ca36032c7aabbc7b8cee8f0f59d18d1264242ae.zip
backend: jwt
Diffstat (limited to 'backend/auth/jwt.go')
-rw-r--r--backend/auth/jwt.go54
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
+}