DriveLinked/pkg/service/users.go

88 lines
2.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package service
import (
"database/sql"
"drive-linked/pkg/common"
"drive-linked/pkg/dto"
"drive-linked/pkg/model"
"drive-linked/pkg/serializer"
"drive-linked/pkg/utils"
"github.com/kataras/iris/v12"
"net/http"
"regexp"
)
type UsersService struct {
Ctx iris.Context
}
var (
UserConditions = [...]string{"id", "name", "email", "nickname"}
)
func NewUsersService(ctx iris.Context) *UsersService {
return &UsersService{Ctx: ctx}
}
func (serv *UsersService) GetOneUser(conditions *map[string]interface{}) {
var err error
resp := dto.NewResponse(serv.Ctx)
user := &model.User{}
err = user.GetProfileWithConditions(conditions)
switch err {
case nil:
// 复制到dto对象
var userResult dto.UserProfile
err = userResult.CopyOf(user)
if err != nil {
resp.Error(http.StatusInternalServerError, "service.users Error")
}
resp.Success(userResult)
case sql.ErrNoRows:
resp.Error(serializer.ErrNoUser, "用户不存在")
default:
resp.Error(http.StatusInternalServerError, "获取用户信息失败,数据库异常")
}
}
func (serv *UsersService) Login(loginParams dto.LoginParams) {
var err error
resp := dto.NewResponse(serv.Ctx)
// 登录逻辑
// 判断账号类型 邮箱/用户名
var method string
emailExp := regexp.MustCompile("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")
if emailExp.Match([]byte(loginParams.Account)) {
method = model.LoginMethodEmail
} else {
method = model.LoginMethodName
}
// 从数据库取出原密码
userLogin := model.Login{}
err = userLogin.GetLoginInfo(loginParams.Account, method)
switch err {
case nil:
// 检查密码
match, _ := utils.CheckPasswd(loginParams.Password, userLogin.Password)
if match {
// 登录成功签发token
sToken, _ := common.NewShortToken(userLogin.Name)
rToken, _ := common.NewRefreshToken(userLogin.Name)
resp.Success(serializer.LoginResponse{
Token: sToken,
RefreshToken: rToken,
})
} else {
resp.ErrBadAccPasswd()
}
case sql.ErrNoRows:
resp.Error(serializer.ErrNoUser, "用户不存在")
default:
resp.Error(http.StatusInternalServerError, "获取用户信息失败,数据库异常")
}
}