| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- package services
- import (
- "errors"
- "think-go/models"
- "time"
- "github.com/beego/beego/v2/client/orm"
- beego "github.com/beego/beego/v2/server/web"
- "github.com/dgrijalva/jwt-go"
- )
- type SaasUserService struct{}
- type LoginClaims struct {
- UserID int `json:"user_id"`
- Mobile string `json:"mobile"`
- jwt.StandardClaims
- }
- type LoginResult struct {
- //User *models.CyySaasUser `json:"user"`
- Token string `json:"token"`
- ExpiresAt int64 `json:"expires_at"`
- }
- func (s *SaasUserService) Login(mobile, password string) (*LoginResult, error) {
- o := orm.NewOrm()
- user := &models.CyySaasUser{Mobile: mobile}
- err := o.Read(user, "Mobile")
- if err == orm.ErrNoRows {
- return nil, errors.New("user not found")
- }
- if err != nil {
- return nil, err
- }
- // TODO: add real password verification here.
- _ = password
- expireAt := time.Now().Add(24 * time.Hour).Unix()
- secret, _ := beego.AppConfig.String("jwt_secret")
- if secret == "" {
- secret = "your-secret-key"
- }
- claims := LoginClaims{
- UserID: user.Id,
- Mobile: user.Mobile,
- StandardClaims: jwt.StandardClaims{
- ExpiresAt: expireAt,
- IssuedAt: time.Now().Unix(),
- },
- }
- token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(secret))
- if err != nil {
- return nil, err
- }
- return &LoginResult{
- //User: user,
- Token: token,
- ExpiresAt: expireAt,
- }, nil
- }
- // SaveAiceUser saves or updates an AiceUsers record by userid string.
- func (s *SaasUserService) SaveAiceUser(email, token, username, userid, address, password string) error {
- u := &models.AiceUsers{
- Userid: userid,
- Email: email,
- Token: token,
- Username: username,
- Address: address,
- Password: password,
- }
- o := orm.NewOrm()
- // check if exists
- v := models.AiceUsers{Userid: userid}
- err := o.Read(&v)
- if err == nil {
- // exists -> update
- return models.UpdateAiceUsersById(u)
- }
- if err == orm.ErrNoRows {
- _, err2 := models.AddAiceUsers(u)
- return err2
- }
- return err
- }
|