209 lines
6.9 KiB
Go
209 lines
6.9 KiB
Go
package auth
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"backend/internal/modules/users"
|
|
"backend/internal/platform/middleware"
|
|
"backend/internal/platform/security"
|
|
)
|
|
|
|
// customer cookie name/path are intentionally distinct from the admin ones
|
|
// (see admin_handler.go) so the two spaces never share a session cookie.
|
|
const (
|
|
customerRefreshCookieName = "customer_refresh_token"
|
|
customerRefreshCookiePath = "/api/auth/customer"
|
|
)
|
|
|
|
// UserCreator is the minimal slice of users.Service that customer
|
|
// registration needs (create-only, consumer-defined per the project's Go
|
|
// interface convention).
|
|
type UserCreator interface {
|
|
Create(ctx context.Context, username, password, role string) (*users.User, error)
|
|
}
|
|
|
|
// AccountsGate reports whether the admin has turned on the customer login
|
|
// page and the customer registration page. CustomerRegistrationEnabled is a
|
|
// sub-toggle of CustomerLoginEnabled (site.Settings.CustomerLoginEnabled /
|
|
// CustomerRegistrationEnabled): an admin can allow login for already-existing
|
|
// accounts while keeping self-service registration closed, but turning login
|
|
// off always closes registration too, since a newly registered account is
|
|
// signed in immediately.
|
|
type AccountsGate interface {
|
|
CustomerLoginEnabled(ctx context.Context) (bool, error)
|
|
CustomerRegistrationEnabled(ctx context.Context) (bool, error)
|
|
}
|
|
|
|
// CustomerHandler mirrors AdminHandler but issues/accepts only
|
|
// customer-audience tokens, and additionally gates on AccountsGate since
|
|
// this space, unlike the admin one, can be turned off entirely by the
|
|
// site's admin.
|
|
type CustomerHandler struct {
|
|
service *Service
|
|
users UserCreator
|
|
gate AccountsGate
|
|
cookieSecure bool
|
|
}
|
|
|
|
func NewCustomerHandler(service *Service, users UserCreator, gate AccountsGate, cookieSecure bool) *CustomerHandler {
|
|
return &CustomerHandler{service: service, users: users, gate: gate, cookieSecure: cookieSecure}
|
|
}
|
|
|
|
func (h *CustomerHandler) loginEnabledOrAbort(c *gin.Context) bool {
|
|
enabled, err := h.gate.CustomerLoginEnabled(c.Request.Context())
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to check customer login setting"})
|
|
return false
|
|
}
|
|
if !enabled {
|
|
c.JSON(http.StatusForbidden, gin.H{"error": "customer login is currently disabled"})
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
func (h *CustomerHandler) registrationEnabledOrAbort(c *gin.Context) bool {
|
|
enabled, err := h.gate.CustomerRegistrationEnabled(c.Request.Context())
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to check customer registration setting"})
|
|
return false
|
|
}
|
|
if !enabled {
|
|
c.JSON(http.StatusForbidden, gin.H{"error": "customer registration is currently disabled"})
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
type registerRequest struct {
|
|
Username string `json:"username" binding:"required"`
|
|
Password string `json:"password" binding:"required,min=8"`
|
|
}
|
|
|
|
func (h *CustomerHandler) Register(c *gin.Context) {
|
|
// Registration is a sub-toggle of login: creating an account is pointless
|
|
// (and issuePair below would hand out a session) if the admin has turned
|
|
// customer login off, so both gates must pass.
|
|
if !h.loginEnabledOrAbort(c) {
|
|
return
|
|
}
|
|
if !h.registrationEnabledOrAbort(c) {
|
|
return
|
|
}
|
|
|
|
var req registerRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "validation error", "details": err.Error()})
|
|
return
|
|
}
|
|
|
|
user, err := h.users.Create(c.Request.Context(), req.Username, req.Password, users.RoleCustomer)
|
|
if err != nil {
|
|
if errors.Is(err, users.ErrUsernameTaken) {
|
|
c.JSON(http.StatusConflict, gin.H{"error": "username already taken"})
|
|
return
|
|
}
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create account"})
|
|
return
|
|
}
|
|
|
|
pair, err := h.service.issuePair(c.Request.Context(), security.AudienceCustomer, user)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "account created but failed to sign in"})
|
|
return
|
|
}
|
|
|
|
h.setRefreshCookie(c, pair.RefreshToken)
|
|
c.JSON(http.StatusCreated, accessTokenResponse{
|
|
AccessToken: pair.AccessToken,
|
|
User: &authUserResponse{ID: user.ID, Username: user.Username, Role: user.Role},
|
|
})
|
|
}
|
|
|
|
func (h *CustomerHandler) Login(c *gin.Context) {
|
|
if !h.loginEnabledOrAbort(c) {
|
|
return
|
|
}
|
|
|
|
var req loginRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "validation error", "details": err.Error()})
|
|
return
|
|
}
|
|
|
|
pair, user, err := h.service.Login(c.Request.Context(), security.AudienceCustomer, users.RoleCustomer, req.Username, req.Password)
|
|
if err != nil {
|
|
switch {
|
|
case errors.Is(err, ErrInvalidCredentials), errors.Is(err, ErrAccountDisabled):
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid credentials"})
|
|
default:
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "login failed"})
|
|
}
|
|
return
|
|
}
|
|
|
|
h.setRefreshCookie(c, pair.RefreshToken)
|
|
c.JSON(http.StatusOK, accessTokenResponse{
|
|
AccessToken: pair.AccessToken,
|
|
User: &authUserResponse{ID: user.ID, Username: user.Username, Role: user.Role},
|
|
})
|
|
}
|
|
|
|
func (h *CustomerHandler) Refresh(c *gin.Context) {
|
|
token, err := c.Cookie(customerRefreshCookieName)
|
|
if err != nil || token == "" {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "missing refresh token"})
|
|
return
|
|
}
|
|
|
|
pair, err := h.service.Refresh(c.Request.Context(), security.AudienceCustomer, token)
|
|
if err != nil {
|
|
h.clearRefreshCookie(c)
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid or expired refresh token"})
|
|
return
|
|
}
|
|
|
|
h.setRefreshCookie(c, pair.RefreshToken)
|
|
c.JSON(http.StatusOK, accessTokenResponse{AccessToken: pair.AccessToken})
|
|
}
|
|
|
|
func (h *CustomerHandler) Logout(c *gin.Context) {
|
|
if token, err := c.Cookie(customerRefreshCookieName); err == nil && token != "" {
|
|
_ = h.service.Logout(c.Request.Context(), security.AudienceCustomer, token)
|
|
}
|
|
h.clearRefreshCookie(c)
|
|
c.JSON(http.StatusOK, gin.H{"message": "logged out"})
|
|
}
|
|
|
|
func (h *CustomerHandler) Me(c *gin.Context) {
|
|
userID, ok := middleware.GetUserID(c)
|
|
if !ok {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
|
return
|
|
}
|
|
user, err := h.service.Me(c.Request.Context(), userID)
|
|
if err != nil {
|
|
if errors.Is(err, users.ErrNotFound) {
|
|
c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
|
|
return
|
|
}
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to load user"})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, authUserResponse{ID: user.ID, Username: user.Username, Role: user.Role})
|
|
}
|
|
|
|
func (h *CustomerHandler) setRefreshCookie(c *gin.Context, token string) {
|
|
c.SetSameSite(http.SameSiteStrictMode)
|
|
c.SetCookie(customerRefreshCookieName, token, int(h.service.RefreshTTL().Seconds()), customerRefreshCookiePath, "", h.cookieSecure, true)
|
|
}
|
|
|
|
func (h *CustomerHandler) clearRefreshCookie(c *gin.Context) {
|
|
c.SetSameSite(http.SameSiteStrictMode)
|
|
c.SetCookie(customerRefreshCookieName, "", -1, customerRefreshCookiePath, "", h.cookieSecure, true)
|
|
}
|