80 lines
2.2 KiB
Go
80 lines
2.2 KiB
Go
package handler
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
)
|
|
|
|
// Login godoc
|
|
// @Summary Autenticação de usuário
|
|
// @Description Realiza login e retorna token JWT.
|
|
// @Description **Credenciais Padrão (Master):**
|
|
// @Description Email: `andre.fr93@gmail.com`
|
|
// @Description Senha: `teste1234`
|
|
// @Tags Autenticação
|
|
// @Accept json
|
|
// @Produce json
|
|
// @Param login body loginRequest true "Credenciais"
|
|
// @Success 200 {object} authResponse
|
|
// @Failure 401 {object} map[string]string
|
|
// @Router /api/v1/auth/login [post]
|
|
func (h *Handler) Login(w http.ResponseWriter, r *http.Request) {
|
|
var req loginRequest
|
|
if err := decodeJSON(r.Context(), r, &req); err != nil {
|
|
writeError(w, http.StatusBadRequest, err)
|
|
return
|
|
}
|
|
|
|
if req.Username == "" {
|
|
writeError(w, http.StatusBadRequest, errors.New("username is required"))
|
|
return
|
|
}
|
|
|
|
token, exp, err := h.svc.Login(r.Context(), req.Username, req.Password)
|
|
if err != nil {
|
|
writeError(w, http.StatusUnauthorized, err)
|
|
return
|
|
}
|
|
|
|
writeJSON(w, http.StatusOK, authResponse{Token: token, ExpiresAt: exp})
|
|
}
|
|
|
|
// Refresh godoc
|
|
// @Summary Atualizar token
|
|
// @Description Gera um novo JWT a partir de um token válido.
|
|
// @Tags Autenticação
|
|
// @Accept json
|
|
// @Produce json
|
|
// @Param Authorization header string true "Bearer token"
|
|
// @Success 200 {object} authResponse
|
|
// @Failure 401 {object} map[string]string
|
|
// @Router /api/v1/auth/refresh [post]
|
|
func (h *Handler) Refresh(w http.ResponseWriter, r *http.Request) {
|
|
h.RefreshToken(w, r)
|
|
}
|
|
|
|
// RefreshToken godoc
|
|
// @Summary Atualizar token
|
|
// @Description Gera um novo JWT a partir de um token válido.
|
|
// @Tags Autenticação
|
|
// @Accept json
|
|
// @Produce json
|
|
// @Param Authorization header string true "Bearer token"
|
|
// @Success 200 {object} authResponse
|
|
// @Failure 401 {object} map[string]string
|
|
// @Router /api/v1/auth/refresh-token [post]
|
|
func (h *Handler) RefreshToken(w http.ResponseWriter, r *http.Request) {
|
|
tokenStr, err := parseBearerToken(r)
|
|
if err != nil {
|
|
writeError(w, http.StatusUnauthorized, err)
|
|
return
|
|
}
|
|
|
|
token, exp, err := h.svc.RefreshToken(r.Context(), tokenStr)
|
|
if err != nil {
|
|
writeError(w, http.StatusUnauthorized, err)
|
|
return
|
|
}
|
|
|
|
writeJSON(w, http.StatusOK, authResponse{Token: token, ExpiresAt: exp})
|
|
}
|