完善登录与鉴权机制
This commit is contained in:
@@ -1,52 +0,0 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"platform/web/models"
|
||||
q "platform/web/queries"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
type CreateClientReq struct {
|
||||
ClientID string `query:"client_id"`
|
||||
ClientSecret string `query:"client_secret"`
|
||||
}
|
||||
|
||||
func CreateClient(c *fiber.Ctx) error {
|
||||
// 验证请求参数
|
||||
req := new(CreateClientReq)
|
||||
if err := c.QueryParser(req); err != nil {
|
||||
return err
|
||||
}
|
||||
if req.ClientID == "" {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "client_id不能为空")
|
||||
}
|
||||
if req.ClientSecret == "" {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "client_secret不能为空")
|
||||
}
|
||||
|
||||
// 创建客户端
|
||||
hashedSecret, err := bcrypt.GenerateFromPassword([]byte(req.ClientSecret), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
client := &models.Client{
|
||||
ClientID: req.ClientID,
|
||||
ClientSecret: string(hashedSecret),
|
||||
Name: "默认客户端 - " + time.Now().String(),
|
||||
Spec: 0,
|
||||
GrantCode: true,
|
||||
GrantClient: true,
|
||||
GrantRefresh: true,
|
||||
Version: 0,
|
||||
}
|
||||
|
||||
err = q.Client.Create(client)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.JSON(client)
|
||||
}
|
||||
@@ -18,8 +18,9 @@ type LoginReq struct {
|
||||
}
|
||||
|
||||
type LoginResp struct {
|
||||
Token string `json:"token"`
|
||||
Expires int64 `json:"expires"`
|
||||
Token string `json:"token"`
|
||||
Expires int64 `json:"expires"`
|
||||
Auth services.AuthContext `json:"auth"`
|
||||
}
|
||||
|
||||
func Login(c *fiber.Ctx) error {
|
||||
@@ -65,6 +66,7 @@ func loginByPhone(c *fiber.Ctx, req *LoginReq) error {
|
||||
if user == nil {
|
||||
user = &models.User{
|
||||
Phone: req.Username,
|
||||
Name: req.Username,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,8 +89,10 @@ func loginByPhone(c *fiber.Ctx, req *LoginReq) error {
|
||||
"user": {},
|
||||
},
|
||||
Payload: services.Payload{
|
||||
Type: services.PayloadUser,
|
||||
Id: user.ID,
|
||||
Id: user.ID,
|
||||
Type: services.PayloadUser,
|
||||
Name: user.Name,
|
||||
Avatar: user.Avatar,
|
||||
},
|
||||
}
|
||||
duration := time.Hour * 24
|
||||
@@ -103,5 +107,6 @@ func loginByPhone(c *fiber.Ctx, req *LoginReq) error {
|
||||
return c.JSON(LoginResp{
|
||||
Token: token.AccessToken,
|
||||
Expires: token.AccessTokenExpires.Unix(),
|
||||
Auth: auth,
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user