feat: 管理后台登录
This commit is contained in:
44
server/internal/handler/auth_handler.go
Normal file
44
server/internal/handler/auth_handler.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/zs/InsightReply/internal/service"
|
||||
)
|
||||
|
||||
type AuthHandler struct {
|
||||
svc *service.AuthService
|
||||
}
|
||||
|
||||
func NewAuthHandler(svc *service.AuthService) *AuthHandler {
|
||||
return &AuthHandler{svc: svc}
|
||||
}
|
||||
|
||||
// Login handles user authentication and returns a JWT token
|
||||
func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
SendError(w, http.StatusBadRequest, 4001, "Invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
if body.Email == "" || body.Password == "" {
|
||||
SendError(w, http.StatusBadRequest, 4001, "Email and Password are required")
|
||||
return
|
||||
}
|
||||
|
||||
token, err := h.svc.Login(body.Email, body.Password)
|
||||
if err != nil {
|
||||
SendError(w, http.StatusUnauthorized, 4001, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
SendSuccess(w, map[string]string{
|
||||
"token": token,
|
||||
})
|
||||
}
|
||||
@@ -18,6 +18,7 @@ func NewUserHandler(svc *service.UserService) *UserHandler {
|
||||
func (h *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
Identity string `json:"identity"`
|
||||
}
|
||||
|
||||
@@ -26,7 +27,7 @@ func (h *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
user, err := h.svc.Register(body.Email, body.Identity)
|
||||
user, err := h.svc.Register(body.Email, body.Password, body.Identity)
|
||||
if err != nil {
|
||||
SendError(w, http.StatusInternalServerError, 5001, "Failed to register user")
|
||||
return
|
||||
|
||||
Reference in New Issue
Block a user