feat: jwt token generation (todo: create jwt validation middleware)
This commit is contained in:
parent
d8caef7e5d
commit
b28b719b51
9 changed files with 86 additions and 29 deletions
|
@ -11,3 +11,6 @@ SQLITE_FILE=
|
||||||
|
|
||||||
# postgres DSN, look at https://gorm.io/docs/connecting_to_the_database.html#PostgreSQL
|
# postgres DSN, look at https://gorm.io/docs/connecting_to_the_database.html#PostgreSQL
|
||||||
POSTGRES_DSN=
|
POSTGRES_DSN=
|
||||||
|
|
||||||
|
# Random secret. Recommended length is 64 characters at minimum.
|
||||||
|
JWT_SECRET=
|
||||||
|
|
1
go.mod
1
go.mod
|
@ -18,6 +18,7 @@ require (
|
||||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||||
github.com/go-playground/validator/v10 v10.26.0 // indirect
|
github.com/go-playground/validator/v10 v10.26.0 // indirect
|
||||||
github.com/goccy/go-json v0.10.5 // indirect
|
github.com/goccy/go-json v0.10.5 // indirect
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.2.2 // indirect
|
||||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||||
github.com/jackc/pgx/v5 v5.7.4 // indirect
|
github.com/jackc/pgx/v5 v5.7.4 // indirect
|
||||||
|
|
2
go.sum
2
go.sum
|
@ -26,6 +26,8 @@ github.com/go-playground/validator/v10 v10.26.0 h1:SP05Nqhjcvz81uJaRfEV0YBSSSGMc
|
||||||
github.com/go-playground/validator/v10 v10.26.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo=
|
github.com/go-playground/validator/v10 v10.26.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo=
|
||||||
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
||||||
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8=
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
|
||||||
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
||||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||||
|
|
|
@ -2,8 +2,10 @@ package routes
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
|
"stereo.cat/backend/internal/auth"
|
||||||
"stereo.cat/backend/internal/types"
|
"stereo.cat/backend/internal/types"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -23,6 +25,12 @@ func RegisterAuthRoutes(cfg *types.StereoConfig, api *gin.RouterGroup) {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, user)
|
jwt, err := auth.GenerateJWT(cfg.JWTSecret, user, uint64(time.Now().Add(time.Second*time.Duration(t.ExpiresIn)).Unix()))
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
c.String(http.StatusOK, jwt)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
|
@ -8,8 +8,6 @@ import (
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
|
||||||
|
|
||||||
"stereo.cat/backend/internal/auth"
|
"stereo.cat/backend/internal/auth"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
37
internal/auth/jwt.go
Normal file
37
internal/auth/jwt.go
Normal file
|
@ -0,0 +1,37 @@
|
||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
func GenerateJWT(key string, user User, expiryTimestamp uint64) (string, error) {
|
||||||
|
claims := jwt.MapClaims{
|
||||||
|
"user": user,
|
||||||
|
"exp": expiryTimestamp,
|
||||||
|
}
|
||||||
|
|
||||||
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||||
|
return token.SignedString([]byte(key))
|
||||||
|
}
|
||||||
|
|
||||||
|
func ValidateJWT(jwtString, key string) (jwt.MapClaims, error) {
|
||||||
|
token, err := jwt.Parse(jwtString, func(token *jwt.Token) (any, error) {
|
||||||
|
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||||
|
return nil, fmt.Errorf("Invalid signing method!")
|
||||||
|
}
|
||||||
|
|
||||||
|
return []byte(key), nil
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
|
||||||
|
return claims, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, fmt.Errorf("Invalid token!")
|
||||||
|
}
|
|
@ -1,23 +1,21 @@
|
||||||
package auth
|
package auth
|
||||||
|
|
||||||
import (
|
import "time"
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
type TokenResponse struct {
|
type TokenResponse struct {
|
||||||
AccessToken string `json:"access_token"`
|
AccessToken string `json:"access_token"`
|
||||||
TokenType string `json:"token_type"`
|
TokenType string `json:"token_type"`
|
||||||
ExpiresIn uint64 `json:"expires_in"`
|
ExpiresIn int64 `json:"expires_in"`
|
||||||
RefreshToken string `json:"refresh_token"`
|
RefreshToken string `json:"refresh_token"`
|
||||||
Scope string `json:"scope"`
|
Scope string `json:"scope"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type User struct {
|
type User struct {
|
||||||
gorm.Model
|
ID string `json:"id" gorm:"primaryKey"`
|
||||||
ID string `json:"id" gorm:"primaryKey;autoIncrement:false"`
|
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
Blacklisted bool
|
Blacklisted bool
|
||||||
Email string `json:"email"`
|
Email string `json:"email"`
|
||||||
|
CreatedAt time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
type AvatarDecorationData struct {
|
type AvatarDecorationData struct {
|
||||||
|
|
|
@ -17,4 +17,5 @@ type StereoConfig struct {
|
||||||
Router *gin.Engine
|
Router *gin.Engine
|
||||||
Client client.Client
|
Client client.Client
|
||||||
Database *gorm.DB
|
Database *gorm.DB
|
||||||
|
JWTSecret string
|
||||||
}
|
}
|
||||||
|
|
17
main.go
17
main.go
|
@ -2,6 +2,7 @@ package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
|
@ -23,6 +24,13 @@ func getEnv(key, fallback string) string {
|
||||||
return fallback
|
return fallback
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func requireEnv(key string) string {
|
||||||
|
if value, ok := os.LookupEnv(key); ok {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
panic(errors.New(fmt.Sprintf("Environment variable %s is required but not specified. Exiting...", key)))
|
||||||
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
_ = godotenv.Load()
|
_ = godotenv.Load()
|
||||||
|
|
||||||
|
@ -42,10 +50,11 @@ func main() {
|
||||||
Router: gin.Default(),
|
Router: gin.Default(),
|
||||||
ImagePath: imagePath,
|
ImagePath: imagePath,
|
||||||
Client: client.New(
|
Client: client.New(
|
||||||
os.Getenv("REDIRECT_URI"),
|
requireEnv("REDIRECT_URI"),
|
||||||
os.Getenv("CLIENT_ID"),
|
requireEnv("CLIENT_ID"),
|
||||||
os.Getenv("CLIENT_SECRET"),
|
requireEnv("CLIENT_SECRET"),
|
||||||
),
|
),
|
||||||
|
JWTSecret: requireEnv("JWT_SECRET"),
|
||||||
}
|
}
|
||||||
|
|
||||||
switch databaseType {
|
switch databaseType {
|
||||||
|
@ -61,7 +70,7 @@ func main() {
|
||||||
break
|
break
|
||||||
|
|
||||||
case "postgres":
|
case "postgres":
|
||||||
db, err := gorm.Open(postgres.Open(os.Getenv("POSTGRES_DSN")), &gorm.Config{})
|
db, err := gorm.Open(postgres.Open(requireEnv("POSTGRES_DSN")), &gorm.Config{})
|
||||||
|
|
||||||
c.Database = db
|
c.Database = db
|
||||||
|
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue