feat(auth): add session login, logout and bearer middleware
This commit is contained in:
+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
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user