fix: fix tokens to expire after 3 months and always inherit admin perms from user

This commit is contained in:
Sam 2023-04-17 23:43:04 +02:00
parent e8f502073d
commit b4c331daa0
Signed by: sam
GPG key ID: B4EF20DDE721CAA1
3 changed files with 11 additions and 8 deletions

View file

@ -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,
}).

View file

@ -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")
}

View file

@ -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,