summaryrefslogtreecommitdiff
path: root/internal/api/auth/auth.go
diff options
context:
space:
mode:
Diffstat (limited to 'internal/api/auth/auth.go')
-rw-r--r--internal/api/auth/auth.go24
1 files changed, 21 insertions, 3 deletions
diff --git a/internal/api/auth/auth.go b/internal/api/auth/auth.go
index b382beb..966a09c 100644
--- a/internal/api/auth/auth.go
+++ b/internal/api/auth/auth.go
@@ -7,17 +7,26 @@ import (
"time"
"github.com/golang-jwt/jwt/v5"
+ "gorm.io/gorm"
)
+// Key used for JWT encryption/decryption
var jwtKey = []byte(os.Getenv("JWT_SECRET"))
+// Kind of JWT token
+var TokenType = "Bearer"
+
+// Extends JWT Claims with the UserID field
type Claims struct {
UserID int `json:"user_id"`
jwt.RegisteredClaims
}
+// Generate a JWT token from an userID.
func GenerateJWT(userID int) (string, error) {
- expirationTime := time.Now().Add(5 * time.Hour)
+ // Set expiration date for the token to 90 days
+ expirationTime := time.Now().Add(90 * 24 * time.Hour)
+
claims := &Claims{
UserID: userID,
RegisteredClaims: jwt.RegisteredClaims{
@@ -30,17 +39,21 @@ func GenerateJWT(userID int) (string, error) {
if err != nil {
return "", err
}
- return tokenString, nil
+ return TokenType + " " + tokenString, nil
}
+// Validate a JWT token for a kind of time
func ValidateJWT(tokenString string) (*Claims, error) {
claims := &Claims{}
- // A token has a form `Bearer ...`
tokenParts := strings.Split(tokenString, " ")
if len(tokenParts) != 2 {
return nil, errors.New("not valid JWT")
}
+ if tokenParts[0] != TokenType {
+ return nil, errors.New("not valid JWT type")
+ }
+
token, err := jwt.ParseWithClaims(tokenParts[1], claims, func(token *jwt.Token) (interface{}, error) {
return jwtKey, nil
})
@@ -55,3 +68,8 @@ func ValidateJWT(tokenString string) (*Claims, error) {
return claims, nil
}
+
+// Common omit password field for users
+func OmitPassword(db *gorm.DB) *gorm.DB {
+ return db.Omit("Password")
+}