You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
67 lines
1.4 KiB
67 lines
1.4 KiB
package controller
|
|
|
|
import (
|
|
"errors"
|
|
"github.com/labstack/echo/v4"
|
|
"github.com/rs/xid"
|
|
"gorm.io/gorm"
|
|
"sorbet/internal/entities"
|
|
"sorbet/internal/errs"
|
|
"sorbet/internal/services/system/request"
|
|
"sorbet/internal/util"
|
|
"sorbet/pkg/crud"
|
|
"sorbet/pkg/db"
|
|
"sorbet/pkg/rsp"
|
|
"sync"
|
|
)
|
|
|
|
// 简单的使用内存实现,也就是重启的话必须重新登录
|
|
var logins sync.Map
|
|
|
|
type SystemAuthController struct{}
|
|
|
|
func (s *SystemAuthController) InitRoutes(r *echo.Group) {
|
|
r.POST("/system/auth/login", s.Login)
|
|
}
|
|
|
|
func (s *SystemAuthController) Login(c echo.Context) error {
|
|
req, err := crud.Bind[request.SystemAuthLoginRequest](c)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var user entities.SystemUser
|
|
err = db.
|
|
WithContext(c.Request().Context()).
|
|
Model(&user).
|
|
Where("username=?", req.Username).
|
|
First(&user).
|
|
Error
|
|
if err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return errs.ErrLoginWithUserpwd
|
|
}
|
|
return err
|
|
}
|
|
if !util.PasswordVerify(req.Password, user.Password) {
|
|
return errs.ErrLoginWithUserpwd
|
|
}
|
|
var ticket string
|
|
logins.Range(func(key, value any) bool {
|
|
x := value.(*entities.SystemUser)
|
|
if x.ID == user.ID {
|
|
ticket = key.(string)
|
|
return false
|
|
}
|
|
return true
|
|
})
|
|
if ticket == "" {
|
|
ticket = xid.New().String()
|
|
logins.Store(ticket, &user)
|
|
|
|
}
|
|
// todo 用户状态
|
|
return rsp.Ok(c, echo.Map{
|
|
"user": user,
|
|
"ticket": ticket,
|
|
})
|
|
}
|
|
|