From b4c331daa02a242fa196e5a983a776ec976fde7d Mon Sep 17 00:00:00 2001 From: Sam Date: Mon, 17 Apr 2023 23:43:04 +0200 Subject: [PATCH] fix: fix tokens to expire after 3 months and always inherit admin perms from user --- backend/db/tokens.go | 4 ++-- backend/routes/auth/tokens.go | 7 ++++++- backend/server/auth/auth.go | 8 +++----- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/backend/db/tokens.go b/backend/db/tokens.go index 32376a8..367c492 100644 --- a/backend/db/tokens.go +++ b/backend/db/tokens.go @@ -61,7 +61,7 @@ func (db *DB) Tokens(ctx context.Context, userID xid.ID) (ts []Token, err error) } // 3 months, might be customizable later -const ExpiryTime = 3 * 30 * 24 * time.Hour +const TokenExpiryTime = 3 * 30 * 24 * time.Hour // SaveToken saves a token to the database. func (db *DB) SaveToken(ctx context.Context, userID xid.ID, tokenID xid.ID, apiOnly, readOnly bool) (t Token, err error) { @@ -69,7 +69,7 @@ func (db *DB) SaveToken(ctx context.Context, userID xid.ID, tokenID xid.ID, apiO SetMap(map[string]any{ "user_id": userID, "token_id": tokenID, - "expires": time.Now().Add(ExpiryTime), + "expires": time.Now().Add(TokenExpiryTime), "api_only": apiOnly, "read_only": readOnly, }). diff --git a/backend/routes/auth/tokens.go b/backend/routes/auth/tokens.go index 211126d..d08c767 100644 --- a/backend/routes/auth/tokens.go +++ b/backend/routes/auth/tokens.go @@ -96,9 +96,14 @@ func (s *Server) createToken(w http.ResponseWriter, r *http.Request) error { return server.APIError{Code: server.ErrMissingPermissions, Details: "This endpoint cannot be used by API tokens"} } + u, err := s.DB.User(ctx, claims.UserID) + if err != nil { + return errors.Wrap(err, "getting me user") + } + readOnly := r.FormValue("read_only") == "true" tokenID := xid.New() - tokenStr, err := s.Auth.CreateToken(claims.UserID, tokenID, false, true, !readOnly) + tokenStr, err := s.Auth.CreateToken(claims.UserID, tokenID, u.IsAdmin, true, !readOnly) if err != nil { return errors.Wrap(err, "creating token") } diff --git a/backend/server/auth/auth.go b/backend/server/auth/auth.go index e9d2bfb..4529155 100644 --- a/backend/server/auth/auth.go +++ b/backend/server/auth/auth.go @@ -6,6 +6,7 @@ import ( "os" "time" + "codeberg.org/u1f320/pronouns.cc/backend/db" "codeberg.org/u1f320/pronouns.cc/backend/log" "emperror.dev/errors" "github.com/golang-jwt/jwt/v4" @@ -46,14 +47,11 @@ func New() *Verifier { return &Verifier{key: key} } -// ExpireDays is after how many days the token will expire. -const ExpireDays = 30 - // CreateToken creates a token for the given user ID. -// It expires after 30 days. +// It expires after three months. func (v *Verifier) CreateToken(userID, tokenID xid.ID, isAdmin bool, isAPIToken bool, isWriteToken bool) (token string, err error) { now := time.Now() - expires := now.Add(ExpireDays * 24 * time.Hour) + expires := now.Add(db.TokenExpiryTime) t := jwt.NewWithClaims(jwt.SigningMethodHS256, Claims{ UserID: userID,