90 lines
2.4 KiB
Go
90 lines
2.4 KiB
Go
package auth
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"messenger/internal/platform/apperr"
|
|
"messenger/internal/platform/httpx"
|
|
"messenger/internal/user"
|
|
)
|
|
|
|
// Challenges sent with every 401: Basic on the login endpoint, Bearer on
|
|
// every protected one.
|
|
const (
|
|
basicChallenge = `Basic realm="messenger", charset="UTF-8"`
|
|
bearerChallenge = `Bearer realm="messenger"`
|
|
)
|
|
|
|
var errCredentialsRequired = apperr.Unauthorized("basic credentials are required")
|
|
|
|
type Handler struct {
|
|
sessions *Service
|
|
}
|
|
|
|
func NewHandler(sessions *Service) *Handler {
|
|
return &Handler{sessions: sessions}
|
|
}
|
|
|
|
// Register mounts login on the public router and logout on the router
|
|
// guarded by RequireSession.
|
|
func (h *Handler) Register(public, protected gin.IRouter) {
|
|
public.POST("/auth/sessions", h.login)
|
|
protected.DELETE("/auth/sessions/current", h.logout)
|
|
}
|
|
|
|
type sessionResponse struct {
|
|
Token string `json:"token"`
|
|
TokenType string `json:"token_type"`
|
|
ExpiresAt string `json:"expires_at"`
|
|
User user.Response `json:"user"`
|
|
}
|
|
|
|
// login accepts only the Authorization header; the body is not read.
|
|
// BasicAuth splits at the first colon, so a password may contain colons.
|
|
func (h *Handler) login(c *gin.Context) {
|
|
username, password, ok := c.Request.BasicAuth()
|
|
if !ok {
|
|
unauthorized(c, basicChallenge, errCredentialsRequired)
|
|
return
|
|
}
|
|
issued, err := h.sessions.Login(c.Request.Context(), username, password)
|
|
if err != nil {
|
|
unauthorized(c, basicChallenge, err)
|
|
return
|
|
}
|
|
httpx.JSON(c, http.StatusCreated, sessionResponse{
|
|
Token: issued.Token,
|
|
TokenType: "Bearer",
|
|
ExpiresAt: httpx.Timestamp(issued.ExpiresAt),
|
|
User: user.ToResponse(issued.User),
|
|
})
|
|
}
|
|
|
|
func (h *Handler) logout(c *gin.Context) {
|
|
token, ok := c.Get(keyToken)
|
|
if !ok {
|
|
httpx.Error(c, errors.New("logout route is missing the RequireSession middleware"))
|
|
return
|
|
}
|
|
if err := h.sessions.Logout(c.Request.Context(), token.(string)); err != nil {
|
|
httpx.Error(c, err)
|
|
return
|
|
}
|
|
// Status alone is buffered by gin; writing the header now sends the 204
|
|
// with an empty body.
|
|
c.Status(http.StatusNoContent)
|
|
c.Writer.WriteHeaderNow()
|
|
}
|
|
|
|
// unauthorized adds the challenge only to a 401: an unavailable store is a
|
|
// 503 and must not invite the client to retry its credentials.
|
|
func unauthorized(c *gin.Context, challenge string, err error) {
|
|
if apperr.KindOf(err) == apperr.KindUnauthorized {
|
|
c.Header("WWW-Authenticate", challenge)
|
|
}
|
|
httpx.Error(c, err)
|
|
}
|