53 lines
1.2 KiB
Go
53 lines
1.2 KiB
Go
package super
|
|
|
|
import (
|
|
"quyun/v2/app/errorx"
|
|
"quyun/v2/app/http/super/dto"
|
|
"quyun/v2/app/services"
|
|
"quyun/v2/pkg/consts"
|
|
"quyun/v2/providers/app"
|
|
"quyun/v2/providers/jwt"
|
|
|
|
"github.com/gofiber/fiber/v3"
|
|
)
|
|
|
|
// @provider
|
|
type auth struct {
|
|
app *app.Config
|
|
jwt *jwt.JWT
|
|
}
|
|
|
|
// Login
|
|
//
|
|
// @Tags Super
|
|
// @Accept json
|
|
// @Produce json
|
|
// @Param form body dto.LoginForm true "form"
|
|
// @Success 200 {object} dto.LoginResponse "成功"
|
|
//
|
|
// @Router /super/v1/auth/login [post]
|
|
// @Bind form body
|
|
func (ctl *auth) login(ctx fiber.Ctx, form *dto.LoginForm) (*dto.LoginResponse, error) {
|
|
m, err := services.User.FindByUsername(ctx, form.Username)
|
|
if err != nil {
|
|
return nil, errorx.Wrap(err).WithMsg("用户名或密码错误")
|
|
}
|
|
|
|
if ok := m.ComparePassword(ctx, form.Password); !ok {
|
|
return nil, errorx.Wrap(err).WithMsg("用户名或密码错误")
|
|
}
|
|
|
|
if !m.Roles.Contains(consts.RoleSuperAdmin) {
|
|
return nil, errorx.Wrap(errorx.ErrInvalidCredentials).WithMsg("用户名或密码错误")
|
|
}
|
|
|
|
token, err := ctl.jwt.CreateToken(ctl.jwt.CreateClaims(jwt.BaseClaims{
|
|
UserID: m.ID,
|
|
}))
|
|
if err != nil {
|
|
return nil, errorx.Wrap(err).WithMsg("登录凭证生成失败")
|
|
}
|
|
|
|
return &dto.LoginResponse{Token: token}, nil
|
|
}
|