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