SaasUserService.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package services
  2. import (
  3. "errors"
  4. "think-go/models"
  5. "time"
  6. "github.com/beego/beego/v2/client/orm"
  7. beego "github.com/beego/beego/v2/server/web"
  8. "github.com/dgrijalva/jwt-go"
  9. )
  10. type SaasUserService struct{}
  11. type LoginClaims struct {
  12. UserID int `json:"user_id"`
  13. Mobile string `json:"mobile"`
  14. jwt.StandardClaims
  15. }
  16. type LoginResult struct {
  17. //User *models.CyySaasUser `json:"user"`
  18. Token string `json:"token"`
  19. ExpiresAt int64 `json:"expires_at"`
  20. }
  21. func (s *SaasUserService) Login(mobile, password string) (*LoginResult, error) {
  22. o := orm.NewOrm()
  23. user := &models.CyySaasUser{Mobile: mobile}
  24. err := o.Read(user, "Mobile")
  25. if err == orm.ErrNoRows {
  26. return nil, errors.New("user not found")
  27. }
  28. if err != nil {
  29. return nil, err
  30. }
  31. // TODO: add real password verification here.
  32. _ = password
  33. expireAt := time.Now().Add(24 * time.Hour).Unix()
  34. secret, _ := beego.AppConfig.String("jwt_secret")
  35. if secret == "" {
  36. secret = "your-secret-key"
  37. }
  38. claims := LoginClaims{
  39. UserID: user.Id,
  40. Mobile: user.Mobile,
  41. StandardClaims: jwt.StandardClaims{
  42. ExpiresAt: expireAt,
  43. IssuedAt: time.Now().Unix(),
  44. },
  45. }
  46. token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(secret))
  47. if err != nil {
  48. return nil, err
  49. }
  50. return &LoginResult{
  51. //User: user,
  52. Token: token,
  53. ExpiresAt: expireAt,
  54. }, nil
  55. }