| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- 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
- }
|