summaryrefslogtreecommitdiff
path: root/internal/api/auth
diff options
context:
space:
mode:
authorSanto Cariotti <santo@dcariotti.me>2025-04-17 22:08:43 +0200
committerSanto Cariotti <santo@dcariotti.me>2025-04-17 22:08:43 +0200
commit8255fbdd7d9d595e71545b7c6909114024527a34 (patch)
tree94773150af8b9d0a2b4e5b548923441cbc107b34 /internal/api/auth
parent9cd48c660231592f3f8d9a035d45b568d987616e (diff)
Logger with also stdout and move logic to network.Me() instead of network.Peer()
Diffstat (limited to 'internal/api/auth')
-rw-r--r--internal/api/auth/auth.go24
-rw-r--r--internal/api/auth/auth_test.go2
2 files changed, 21 insertions, 5 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")
+}
diff --git a/internal/api/auth/auth_test.go b/internal/api/auth/auth_test.go
index 66bcc27..50b6c9b 100644
--- a/internal/api/auth/auth_test.go
+++ b/internal/api/auth/auth_test.go
@@ -19,8 +19,6 @@ func TestGenerateAndValidateJWT(t *testing.T) {
assert.NoError(t, err)
assert.NotEmpty(t, tokenString)
- tokenString = "Bearer " + tokenString
-
claims, err := ValidateJWT(tokenString)
assert.NoError(t, err)
assert.NotNil(t, claims)