feat: add API token authentication
This commit is contained in:
@@ -20,6 +20,7 @@ func (h *AuthHandler) Register(r *gin.Engine) {
|
||||
r.GET("/login", h.HandleLoginPage)
|
||||
r.POST("/login", h.HandleLogin)
|
||||
r.GET("/logout", h.HandleLogout)
|
||||
r.POST("/api/auth/login", h.HandleAPILogin)
|
||||
}
|
||||
|
||||
func (h *AuthHandler) HandleLoginPage(c *gin.Context) {
|
||||
@@ -59,3 +60,35 @@ func (h *AuthHandler) HandleLogout(c *gin.Context) {
|
||||
c.SetCookie("session_id", "", -1, "/", "", false, true)
|
||||
c.Redirect(http.StatusSeeOther, "/login")
|
||||
}
|
||||
|
||||
func (h *AuthHandler) HandleAPILogin(c *gin.Context) {
|
||||
var body struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&body); err != nil || body.Username == "" || body.Password == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
|
||||
return
|
||||
}
|
||||
|
||||
token, user, err := h.svc.LoginForAPIToken(c.Request.Context(), body.Username, body.Password, body.Name)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid username or password"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"token": token,
|
||||
"user": gin.H{
|
||||
"id": user.ID,
|
||||
"username": user.Username,
|
||||
"avatarUrl": func() string {
|
||||
if user.AvatarUrl == "" {
|
||||
return ""
|
||||
}
|
||||
return user.AvatarUrl
|
||||
}(),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -3,32 +3,59 @@ package middleware
|
||||
import (
|
||||
"mal/internal/domain"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func AuthMiddleware(svc domain.AuthService) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
path := c.Request.URL.Path
|
||||
|
||||
// Allow access to login, logout and static assets without authentication
|
||||
if c.Request.URL.Path == "/login" || c.Request.URL.Path == "/logout" ||
|
||||
len(c.Request.URL.Path) >= 7 && c.Request.URL.Path[:7] == "/static" ||
|
||||
len(c.Request.URL.Path) >= 5 && c.Request.URL.Path[:5] == "/dist" {
|
||||
if path == "/login" || path == "/logout" ||
|
||||
strings.HasPrefix(path, "/static") ||
|
||||
strings.HasPrefix(path, "/dist") ||
|
||||
path == "/api/auth/login" {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
sessionID, err := c.Cookie("session_id")
|
||||
if err != nil {
|
||||
c.Redirect(http.StatusSeeOther, "/login")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
var user *domain.User
|
||||
var err error
|
||||
|
||||
user, err := svc.ValidateSession(c.Request.Context(), sessionID)
|
||||
if err != nil {
|
||||
c.Redirect(http.StatusSeeOther, "/login")
|
||||
c.Abort()
|
||||
return
|
||||
// API routes can authenticate via Bearer token OR cookie session.
|
||||
if strings.HasPrefix(path, "/api/") {
|
||||
authHeader := strings.TrimSpace(c.GetHeader("Authorization"))
|
||||
if strings.HasPrefix(strings.ToLower(authHeader), "bearer ") {
|
||||
token := strings.TrimSpace(authHeader[7:])
|
||||
user, err = svc.ValidateAPIToken(c.Request.Context(), token)
|
||||
} else if sessionID, cookieErr := c.Cookie("session_id"); cookieErr == nil {
|
||||
user, err = svc.ValidateSession(c.Request.Context(), sessionID)
|
||||
} else {
|
||||
err = cookieErr
|
||||
}
|
||||
|
||||
if err != nil || user == nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
} else {
|
||||
// Non-API routes only use cookie sessions and redirect to /login.
|
||||
sessionID, cookieErr := c.Cookie("session_id")
|
||||
if cookieErr != nil {
|
||||
c.Redirect(http.StatusSeeOther, "/login")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
user, err = svc.ValidateSession(c.Request.Context(), sessionID)
|
||||
if err != nil || user == nil {
|
||||
c.Redirect(http.StatusSeeOther, "/login")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
c.Set("User", user)
|
||||
|
||||
@@ -7,6 +7,8 @@ import (
|
||||
"mal/internal/db"
|
||||
"mal/internal/domain"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type authRepository struct {
|
||||
@@ -65,3 +67,35 @@ func (r *authRepository) GetSession(ctx context.Context, sessionID string) (*dom
|
||||
func (r *authRepository) DeleteSession(ctx context.Context, sessionID string) error {
|
||||
return r.queries.DeleteSession(ctx, sessionID)
|
||||
}
|
||||
|
||||
func (r *authRepository) CreateAPIToken(ctx context.Context, userID, tokenHash, name string) (*domain.APIToken, error) {
|
||||
t, err := r.queries.CreateAPIToken(ctx, db.CreateAPITokenParams{
|
||||
ID: uuid.New().String(),
|
||||
UserID: userID,
|
||||
TokenHash: tokenHash,
|
||||
Name: name,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &t, nil
|
||||
}
|
||||
|
||||
func (r *authRepository) GetAPITokenByHash(ctx context.Context, tokenHash string) (*domain.APIToken, error) {
|
||||
t, err := r.queries.GetAPITokenByHash(ctx, tokenHash)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &t, nil
|
||||
}
|
||||
|
||||
func (r *authRepository) TouchAPITokenLastUsedAt(ctx context.Context, tokenID string) error {
|
||||
return r.queries.TouchAPITokenLastUsedAt(ctx, tokenID)
|
||||
}
|
||||
|
||||
func (r *authRepository) RevokeAllAPITokensForUser(ctx context.Context, userID string) error {
|
||||
return r.queries.RevokeAllAPITokensForUser(ctx, userID)
|
||||
}
|
||||
|
||||
@@ -2,8 +2,13 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"mal/internal/domain"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -35,6 +40,32 @@ func (s *authService) Login(ctx context.Context, username, password string) (*do
|
||||
return s.repo.CreateSession(ctx, user.ID, sessionID)
|
||||
}
|
||||
|
||||
func (s *authService) LoginForAPIToken(ctx context.Context, username, password, name string) (string, *domain.User, error) {
|
||||
user, err := s.repo.GetUserByUsername(ctx, username)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
if user == nil {
|
||||
return "", nil, errors.New("invalid credentials")
|
||||
}
|
||||
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password)); err != nil {
|
||||
return "", nil, errors.New("invalid credentials")
|
||||
}
|
||||
|
||||
trimmedName := strings.TrimSpace(name)
|
||||
if trimmedName == "" {
|
||||
trimmedName = "Firefox extension"
|
||||
}
|
||||
|
||||
rawToken, tokenHash := newOpaqueToken()
|
||||
if _, err := s.repo.CreateAPIToken(ctx, user.ID, tokenHash, trimmedName); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
return rawToken, user, nil
|
||||
}
|
||||
|
||||
func (s *authService) ValidateSession(ctx context.Context, sessionID string) (*domain.User, error) {
|
||||
session, err := s.repo.GetSession(ctx, sessionID)
|
||||
if err != nil {
|
||||
@@ -52,6 +83,44 @@ func (s *authService) ValidateSession(ctx context.Context, sessionID string) (*d
|
||||
return s.repo.GetUserByID(ctx, session.UserID)
|
||||
}
|
||||
|
||||
func (s *authService) ValidateAPIToken(ctx context.Context, token string) (*domain.User, error) {
|
||||
trimmed := strings.TrimSpace(token)
|
||||
if trimmed == "" {
|
||||
return nil, errors.New("token missing")
|
||||
}
|
||||
|
||||
sum := sha256.Sum256([]byte(trimmed))
|
||||
tokenHash := hex.EncodeToString(sum[:])
|
||||
|
||||
t, err := s.repo.GetAPITokenByHash(ctx, tokenHash)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if t == nil {
|
||||
return nil, errors.New("token not found")
|
||||
}
|
||||
|
||||
_ = s.repo.TouchAPITokenLastUsedAt(ctx, t.ID)
|
||||
return s.repo.GetUserByID(ctx, t.UserID)
|
||||
}
|
||||
|
||||
func (s *authService) Logout(ctx context.Context, sessionID string) error {
|
||||
return s.repo.DeleteSession(ctx, sessionID)
|
||||
}
|
||||
|
||||
func (s *authService) RevokeAllAPITokensForUser(ctx context.Context, userID string) error {
|
||||
if strings.TrimSpace(userID) == "" {
|
||||
return errors.New("user id missing")
|
||||
}
|
||||
return s.repo.RevokeAllAPITokensForUser(ctx, userID)
|
||||
}
|
||||
|
||||
func newOpaqueToken() (token string, tokenHash string) {
|
||||
buf := make([]byte, 32)
|
||||
_, _ = rand.Read(buf)
|
||||
token = base64.RawURLEncoding.EncodeToString(buf)
|
||||
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
tokenHash = hex.EncodeToString(sum[:])
|
||||
return token, tokenHash
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user