feat: login post handler
This commit is contained in:
@ -3,11 +3,15 @@ package user
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"gitea.local/admin/hspguard/internal/auth"
|
||||
"gitea.local/admin/hspguard/internal/repository"
|
||||
"gitea.local/admin/hspguard/internal/web"
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
type UserHandler struct {
|
||||
@ -24,6 +28,7 @@ func (h *UserHandler) RegisterRoutes(router chi.Router, api chi.Router) {
|
||||
router.Get("/login", h.loginPage)
|
||||
router.Get("/register", h.registerPage)
|
||||
api.Post("/register", h.register)
|
||||
api.Post("/login", h.login)
|
||||
}
|
||||
|
||||
func (h *UserHandler) loginPage(w http.ResponseWriter, r *http.Request) {
|
||||
@ -92,3 +97,63 @@ func (h *UserHandler) register(w http.ResponseWriter, r *http.Request) {
|
||||
web.Error(w, "failed to encode response", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
type LoginParams struct {
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type UserClaims struct {
|
||||
UserID string `json:"user_id"`
|
||||
// Role
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
func (h *UserHandler) login(w http.ResponseWriter, r *http.Request) {
|
||||
var params LoginParams
|
||||
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
if err := decoder.Decode(¶ms); err != nil {
|
||||
web.Error(w, "failed to parse request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if params.Email == "" || params.Password == "" {
|
||||
web.Error(w, "missing required fields", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
user, err := h.repo.FindUserEmail(context.Background(), params.Email)
|
||||
if err != nil {
|
||||
web.Error(w, "user with provided email does not exists", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
claims := UserClaims{
|
||||
UserID: user.ID.String(),
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
Issuer: "hspguard",
|
||||
Subject: user.Email,
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
|
||||
},
|
||||
}
|
||||
|
||||
token, err := auth.SignJwtToken(claims)
|
||||
if err != nil {
|
||||
web.Error(w, fmt.Sprintf("failed to generate access token: %v", err), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
encoder := json.NewEncoder(w)
|
||||
|
||||
type Response struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
if err := encoder.Encode(Response{
|
||||
Token: token,
|
||||
}); err != nil {
|
||||
web.Error(w, "failed to encode response", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user