feat(auth): add session login, logout and bearer middleware
This commit is contained in:
@@ -14,9 +14,10 @@ SELECT user_id FROM sessions
|
||||
WHERE token_hash = sqlc.arg(token_hash)
|
||||
AND expires_at > now();
|
||||
|
||||
-- name: DeleteSession :exec
|
||||
-- name: DeleteSession :execrows
|
||||
DELETE FROM sessions
|
||||
WHERE token_hash = sqlc.arg(token_hash);
|
||||
WHERE token_hash = sqlc.arg(token_hash)
|
||||
AND expires_at > now();
|
||||
|
||||
-- name: DeleteExpiredSessions :execrows
|
||||
DELETE FROM sessions
|
||||
|
||||
@@ -43,6 +43,7 @@ func Run() error {
|
||||
queries := db.New(pool)
|
||||
memory := store.New()
|
||||
|
||||
authService := service.NewAuthService(queries, cfg.Server.SessionTTL)
|
||||
userService := service.NewUserService(queries)
|
||||
chatService := service.NewChatService(memory)
|
||||
messageService := service.NewMessageService(memory)
|
||||
@@ -51,6 +52,7 @@ func Run() error {
|
||||
log,
|
||||
cfg.Server.MaxInflightRequests,
|
||||
pool,
|
||||
authService,
|
||||
userService,
|
||||
chatService,
|
||||
messageService,
|
||||
|
||||
@@ -15,6 +15,7 @@ func NewRouter(
|
||||
log *slog.Logger,
|
||||
maxInflightRequests int,
|
||||
db handler.Pinger,
|
||||
authService *service.AuthService,
|
||||
userService *service.UserService,
|
||||
chatService *service.ChatService,
|
||||
messageService *service.MessageService,
|
||||
@@ -22,6 +23,7 @@ func NewRouter(
|
||||
router := chi.NewRouter()
|
||||
|
||||
healthHandler := handler.NewHealthHandler(log, db)
|
||||
authHandler := handler.NewAuthHandler(authService)
|
||||
userHandler := handler.NewUserHandler(userService)
|
||||
chatHandler := handler.NewChatHandler(chatService)
|
||||
messageHandler := handler.NewMessageHandler(messageService)
|
||||
@@ -35,8 +37,11 @@ func NewRouter(
|
||||
|
||||
router.Post("/api/v1/users", userHandler.Create)
|
||||
|
||||
router.Post("/api/v1/auth/sessions", authHandler.CreateSession)
|
||||
router.Delete("/api/v1/auth/sessions/current", authHandler.RevokeSession)
|
||||
|
||||
router.Group(func(r chi.Router) {
|
||||
r.Use(middleware.Auth(userService))
|
||||
r.Use(middleware.Auth(authService))
|
||||
|
||||
r.Get("/api/v1/users/me", userHandler.Me)
|
||||
|
||||
|
||||
@@ -48,14 +48,18 @@ func (q *Queries) DeleteExpiredSessions(ctx context.Context) (int64, error) {
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const deleteSession = `-- name: DeleteSession :exec
|
||||
const deleteSession = `-- name: DeleteSession :execrows
|
||||
DELETE FROM sessions
|
||||
WHERE token_hash = $1
|
||||
AND expires_at > now()
|
||||
`
|
||||
|
||||
func (q *Queries) DeleteSession(ctx context.Context, tokenHash string) error {
|
||||
_, err := q.db.Exec(ctx, deleteSession, tokenHash)
|
||||
return err
|
||||
func (q *Queries) DeleteSession(ctx context.Context, tokenHash string) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, deleteSession, tokenHash)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const getSessionUserID = `-- name: GetSessionUserID :one
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package dto
|
||||
|
||||
import "time"
|
||||
|
||||
type SessionResponse struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
User UserResponse `json:"user"`
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"mtusi2026-messenger/internal/dto"
|
||||
"mtusi2026-messenger/internal/httpx"
|
||||
"mtusi2026-messenger/internal/middleware"
|
||||
"mtusi2026-messenger/internal/service"
|
||||
)
|
||||
|
||||
type AuthHandler struct {
|
||||
service *service.AuthService
|
||||
}
|
||||
|
||||
func NewAuthHandler(s *service.AuthService) *AuthHandler {
|
||||
return &AuthHandler{service: s}
|
||||
}
|
||||
|
||||
func (h *AuthHandler) CreateSession(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
username, plain, ok := r.BasicAuth()
|
||||
if !ok {
|
||||
httpx.WriteUnauthorized(w, httpx.BasicChallenge, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
session, err := h.service.Login(r.Context(), username, plain)
|
||||
if errors.Is(err, service.ErrInvalidCredentials) {
|
||||
httpx.WriteUnauthorized(w, httpx.BasicChallenge, requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
httpx.WriteInternal(w, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
httpx.WriteJSON(w, http.StatusCreated, dto.SessionResponse{
|
||||
Token: session.Token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: session.ExpiresAt,
|
||||
User: dto.UserResponse{
|
||||
ID: session.User.ID,
|
||||
Username: session.User.Username,
|
||||
DisplayName: session.User.DisplayName,
|
||||
CreatedAt: session.User.CreatedAt,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (h *AuthHandler) RevokeSession(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
token, ok := httpx.BearerToken(r)
|
||||
if !ok {
|
||||
httpx.WriteUnauthorized(w, httpx.BearerChallenge, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
err := h.service.Logout(r.Context(), token)
|
||||
if errors.Is(err, service.ErrUnauthorized) {
|
||||
httpx.WriteUnauthorized(w, httpx.BearerChallenge, requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
httpx.WriteInternal(w, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"mtusi2026-messenger/internal/dto"
|
||||
)
|
||||
|
||||
const (
|
||||
BasicChallenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
BearerChallenge = `Bearer realm="messenger"`
|
||||
)
|
||||
|
||||
func BearerToken(r *http.Request) (string, bool) {
|
||||
const prefix = "Bearer "
|
||||
|
||||
header := r.Header.Get("Authorization")
|
||||
if len(header) <= len(prefix) || !strings.EqualFold(header[:len(prefix)], prefix) {
|
||||
return "", false
|
||||
}
|
||||
|
||||
token := strings.TrimSpace(header[len(prefix):])
|
||||
|
||||
return token, token != ""
|
||||
}
|
||||
|
||||
func WriteUnauthorized(w http.ResponseWriter, challenge, requestID string) {
|
||||
w.Header().Set("WWW-Authenticate", challenge)
|
||||
WriteError(
|
||||
w,
|
||||
http.StatusUnauthorized,
|
||||
dto.ErrorCodeUnauthorized,
|
||||
"unauthorized",
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
+15
-30
@@ -2,54 +2,39 @@ package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026-messenger/internal/dto"
|
||||
"mtusi2026-messenger/internal/httpx"
|
||||
"mtusi2026-messenger/internal/service"
|
||||
)
|
||||
|
||||
type userIDContextKey struct{}
|
||||
|
||||
func Auth(userService *service.UserService) func(http.Handler) http.Handler {
|
||||
type authenticator interface {
|
||||
Authenticate(ctx context.Context, token string) (uuid.UUID, error)
|
||||
}
|
||||
|
||||
func Auth(auth authenticator) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := GetRequestID(r.Context())
|
||||
|
||||
raw := r.Header.Get("X-User-Id")
|
||||
if raw == "" {
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusUnauthorized,
|
||||
dto.ErrorCodeUnauthorized,
|
||||
"missing X-User-Id header",
|
||||
requestID,
|
||||
)
|
||||
token, ok := httpx.BearerToken(r)
|
||||
if !ok {
|
||||
httpx.WriteUnauthorized(w, httpx.BearerChallenge, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
userID, err := uuid.Parse(raw)
|
||||
userID, err := auth.Authenticate(r.Context(), token)
|
||||
if errors.Is(err, service.ErrUnauthorized) {
|
||||
httpx.WriteUnauthorized(w, httpx.BearerChallenge, requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusUnauthorized,
|
||||
dto.ErrorCodeUnauthorized,
|
||||
"invalid X-User-Id header",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := userService.GetByID(userID); err != nil {
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusUnauthorized,
|
||||
dto.ErrorCodeUnauthorized,
|
||||
"unknown user",
|
||||
requestID,
|
||||
)
|
||||
httpx.WriteInternal(w, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type Session struct {
|
||||
Token string
|
||||
ExpiresAt time.Time
|
||||
User User
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"mtusi2026-messenger/internal/credentials"
|
||||
"mtusi2026-messenger/internal/db"
|
||||
"mtusi2026-messenger/internal/model"
|
||||
"mtusi2026-messenger/internal/postgres"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidCredentials = errors.New("invalid credentials")
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
)
|
||||
|
||||
type authQueries interface {
|
||||
CreateSession(ctx context.Context, arg db.CreateSessionParams) error
|
||||
DeleteSession(ctx context.Context, tokenHash string) (int64, error)
|
||||
GetSessionUserID(ctx context.Context, tokenHash string) (uuid.UUID, error)
|
||||
GetUserByUsername(ctx context.Context, username string) (db.User, error)
|
||||
}
|
||||
|
||||
type AuthService struct {
|
||||
q authQueries
|
||||
sessionTTL time.Duration
|
||||
}
|
||||
|
||||
func NewAuthService(q authQueries, sessionTTL time.Duration) *AuthService {
|
||||
return &AuthService{
|
||||
q: q,
|
||||
sessionTTL: sessionTTL,
|
||||
}
|
||||
}
|
||||
|
||||
var dummyHash, _ = credentials.HashPassword("dummy-password-for-timing")
|
||||
|
||||
func (s *AuthService) Login(ctx context.Context, username, plain string) (model.Session, error) {
|
||||
user, err := s.q.GetUserByUsername(ctx, username)
|
||||
if postgres.IsNotFound(err) {
|
||||
_ = credentials.VerifyPassword(dummyHash, plain)
|
||||
return model.Session{}, ErrInvalidCredentials
|
||||
}
|
||||
if err != nil {
|
||||
return model.Session{}, err
|
||||
}
|
||||
|
||||
if err := credentials.VerifyPassword(user.PasswordHash, plain); err != nil {
|
||||
if errors.Is(err, credentials.ErrPasswordMismatch) {
|
||||
return model.Session{}, ErrInvalidCredentials
|
||||
}
|
||||
return model.Session{}, err
|
||||
}
|
||||
|
||||
token := credentials.NewToken()
|
||||
expiresAt := time.Now().UTC().Add(s.sessionTTL)
|
||||
|
||||
err = s.q.CreateSession(ctx, db.CreateSessionParams{
|
||||
TokenHash: credentials.HashToken(token),
|
||||
UserID: user.ID,
|
||||
ExpiresAt: expiresAt,
|
||||
})
|
||||
if err != nil {
|
||||
return model.Session{}, err
|
||||
}
|
||||
|
||||
return model.Session{
|
||||
Token: token,
|
||||
ExpiresAt: expiresAt,
|
||||
User: model.User{
|
||||
ID: user.ID,
|
||||
Username: user.Username,
|
||||
DisplayName: user.DisplayName,
|
||||
CreatedAt: user.CreatedAt.UTC(),
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *AuthService) Authenticate(ctx context.Context, token string) (uuid.UUID, error) {
|
||||
userID, err := s.q.GetSessionUserID(ctx, credentials.HashToken(token))
|
||||
if postgres.IsNotFound(err) {
|
||||
return uuid.Nil, ErrUnauthorized
|
||||
}
|
||||
if err != nil {
|
||||
return uuid.Nil, err
|
||||
}
|
||||
|
||||
return userID, nil
|
||||
}
|
||||
|
||||
func (s *AuthService) Logout(ctx context.Context, token string) error {
|
||||
n, err := s.q.DeleteSession(ctx, credentials.HashToken(token))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n == 0 {
|
||||
return ErrUnauthorized
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user