41 lines
1.1 KiB
Go
41 lines
1.1 KiB
Go
|
package auth
|
||
|
|
||
|
import (
|
||
|
"net/http"
|
||
|
"time"
|
||
|
|
||
|
"github.com/zeromicro/go-zero/rest/httpx"
|
||
|
"tianyuan-api/apps/admin/internal/logic/auth"
|
||
|
"tianyuan-api/apps/admin/internal/svc"
|
||
|
"tianyuan-api/apps/admin/internal/types"
|
||
|
|
||
|
xhttp "github.com/zeromicro/x/http"
|
||
|
)
|
||
|
|
||
|
func LoginHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||
|
var req types.LoginReq
|
||
|
if err := httpx.Parse(r, &req); err != nil {
|
||
|
xhttp.JsonBaseResponseCtx(r.Context(), w, err)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
l := auth.NewLoginLogic(r.Context(), svcCtx)
|
||
|
token, err := l.Login(&req)
|
||
|
if err != nil {
|
||
|
xhttp.JsonBaseResponseCtx(r.Context(), w, err)
|
||
|
} else {
|
||
|
http.SetCookie(w, &http.Cookie{
|
||
|
Name: "Authorization",
|
||
|
Value: token, // JWT 令牌
|
||
|
HttpOnly: true, // 防止 JavaScript 访问
|
||
|
Secure: false, // HTTPS 使用
|
||
|
SameSite: http.SameSiteLaxMode, // 防止 CSRF 攻击
|
||
|
Path: "/",
|
||
|
Expires: time.Now().Add(time.Duration(svcCtx.Config.AuthJWT.AccessExpire) * time.Second), // 过期时间
|
||
|
})
|
||
|
xhttp.JsonBaseResponseCtx(r.Context(), w, nil)
|
||
|
}
|
||
|
}
|
||
|
}
|