62 lines
1.8 KiB
Go
62 lines
1.8 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/gogf/gf/v2/errors/gerror"
|
|
"github.com/gogf/gf/v2/frame/g"
|
|
"golang.org/x/crypto/bcrypt"
|
|
|
|
"36wisdom/biz/consts"
|
|
"36wisdom/biz/dao"
|
|
"36wisdom/common/auth"
|
|
)
|
|
|
|
type parent struct{}
|
|
|
|
var Parent = &parent{}
|
|
|
|
// Register 家长注册:手机号唯一、bcrypt 落库、签发 token。
|
|
func (s *parent) Register(ctx context.Context, phone, password, nickname string) (parentId int64, token string, err error) {
|
|
rec, err := dao.Parent.Model().Ctx(ctx).Where("phone", phone).One()
|
|
if err != nil {
|
|
return 0, "", err
|
|
}
|
|
if !rec.IsEmpty() {
|
|
return 0, "", gerror.Newf("手机号 %s 已注册", phone)
|
|
}
|
|
|
|
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
return 0, "", err
|
|
}
|
|
parentId, err = dao.Parent.InsertAndReturnId(ctx, g.Map{
|
|
"phone": phone,
|
|
"password": string(hash),
|
|
"nickname": nickname,
|
|
"status": consts.StatusEnabled,
|
|
})
|
|
if err != nil {
|
|
return 0, "", err
|
|
}
|
|
token, err = auth.GenerateToken(auth.Secret(ctx), parentId, consts.RoleParent, consts.AuthExpireSeconds)
|
|
return parentId, token, err
|
|
}
|
|
|
|
// Login 家长登录:校验手机号与密码,签发 token。
|
|
func (s *parent) Login(ctx context.Context, phone, password string) (parentId int64, token string, err error) {
|
|
rec, err := dao.Parent.Model().Ctx(ctx).Where("phone", phone).One()
|
|
if err != nil {
|
|
return 0, "", err
|
|
}
|
|
if rec.IsEmpty() {
|
|
return 0, "", gerror.New("手机号或密码错误")
|
|
}
|
|
if err = bcrypt.CompareHashAndPassword([]byte(rec["password"].String()), []byte(password)); err != nil {
|
|
return 0, "", gerror.New("手机号或密码错误")
|
|
}
|
|
parentId = rec["id"].Int64()
|
|
token, err = auth.GenerateToken(auth.Secret(ctx), parentId, consts.RoleParent, consts.AuthExpireSeconds)
|
|
return parentId, token, err
|
|
}
|