70 lines
1.7 KiB
Go
70 lines
1.7 KiB
Go
package domain
|
||
|
||
import (
|
||
"admin/apps/user/domain/entity"
|
||
"admin/apps/user/model"
|
||
"admin/internal/errcode"
|
||
"admin/lib/passlib"
|
||
"admin/lib/xlog"
|
||
"time"
|
||
)
|
||
|
||
func (svc *CommonResourceService) EnsureInitDB() error {
|
||
return svc.userRepo.CreateAdminUsers()
|
||
}
|
||
|
||
func (svc *CommonResourceService) Login(user, pwd string) (*entity.User, error) {
|
||
userEt, find, err := svc.userRepo.GetByUser(user)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
if !find {
|
||
return nil, errcode.New(errcode.UserOrPassInValid, "")
|
||
}
|
||
|
||
pwd1 := passlib.EncryptPassword(pwd)
|
||
|
||
xlog.Tracef("user %v pass %v(%v), db pass:%v", user, pwd, pwd1, userEt.Po.UserPass)
|
||
|
||
if !passlib.ComparePassword(userEt.Po.UserPass, pwd) {
|
||
return nil, errcode.New(errcode.UserOrPassInValid, "")
|
||
}
|
||
|
||
return userEt, nil
|
||
}
|
||
|
||
func (svc *CommonResourceService) GetUserById(userId int) (*entity.User, bool, error) {
|
||
et, find, err := svc.userRepo.GetById(userId)
|
||
if err != nil {
|
||
return et, false, err
|
||
}
|
||
return et, find, nil
|
||
}
|
||
|
||
func (svc *CommonResourceService) GetOrCreateToken(userId int) (*model.Token, error) {
|
||
tokenInfo, find, err := svc.tokenRepo.GetTokenByUserId(userId)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
if !find || tokenInfo.ExpireAt.Before(time.Now()) {
|
||
tokenInfo, err = svc.tokenRepo.CreateToken(userId, time.Hour*24*15) // 15天过期的token,可以使用中加上token刷新功能
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
}
|
||
|
||
return tokenInfo, nil
|
||
}
|
||
|
||
func (svc *CommonResourceService) GetToken(userId int) (*model.Token, error) {
|
||
tokenInfo, find, err := svc.tokenRepo.GetTokenByUserId(userId)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
if !find {
|
||
return tokenInfo, errcode.New(errcode.TokenInvalid, "user %v token not found", userId)
|
||
}
|
||
|
||
return tokenInfo, nil
|
||
}
|