SaasUserService.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. }
  56. // SaveAiceUser saves or updates an AiceUsers record by userid string.
  57. func (s *SaasUserService) SaveAiceUser(email, token, username, userid, address, password string) error {
  58. u := &models.AiceUsers{
  59. Userid: userid,
  60. Email: email,
  61. Token: token,
  62. Username: username,
  63. Address: address,
  64. Password: password,
  65. }
  66. o := orm.NewOrm()
  67. // check if exists
  68. v := models.AiceUsers{Userid: userid}
  69. err := o.Read(&v)
  70. if err == nil {
  71. // exists -> update
  72. return models.UpdateAiceUsersById(u)
  73. }
  74. if err == orm.ErrNoRows {
  75. _, err2 := models.AddAiceUsers(u)
  76. return err2
  77. }
  78. return err
  79. }