login_auth.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "youngee_b_api/consts"
  11. "youngee_b_api/db"
  12. "youngee_b_api/model/redis_model"
  13. "youngee_b_api/model/system_model"
  14. "youngee_b_api/redis"
  15. "youngee_b_api/util"
  16. "github.com/sirupsen/logrus"
  17. )
  18. var LoginAuth *loginAuth
  19. func LoginAuthInit(config *system_model.Session) {
  20. auth := new(loginAuth)
  21. auth.sessionTTL = time.Duration(config.TTL) * time.Minute
  22. LoginAuth = auth
  23. }
  24. type loginAuth struct {
  25. sessionTTL time.Duration
  26. }
  27. func (l *loginAuth) AuthToken(ctx context.Context, token string) (*redis_model.Auth, error) {
  28. phone, err := l.parseToken(ctx, token)
  29. if err != nil {
  30. logrus.Debug("token格式错误:%+v", token)
  31. return nil, err
  32. }
  33. auth, err := l.getSessionAuth(ctx, phone)
  34. if err != nil {
  35. logrus.Debug("获取session redis错误: token:%+v,err:%+v", token, err)
  36. return nil, err
  37. }
  38. if auth.Token != token {
  39. logrus.Debug("获取session time过期错误: token:%+v", token)
  40. return nil, errors.New("auth failed")
  41. }
  42. return auth, nil
  43. }
  44. // AuthCode 判断此手机号是否有账号存在 鉴定验证码 用户信息存入redis 并返回Token
  45. func (l *loginAuth) AuthCode(ctx context.Context, phone string, code string) (string, error) {
  46. user, err := db.GetUserByPhone(ctx, phone)
  47. fmt.Println("login_auth", user, err)
  48. if err != nil {
  49. return "", err
  50. } else if user == nil {
  51. // 账号不存在,则注册账号
  52. _, err = Enterprise.CreateEnterprise(ctx, phone)
  53. if err != nil {
  54. return "账号创建失败", err
  55. }
  56. user, err = db.GetUserByPhone(ctx, phone)
  57. fmt.Println("login_auth", user, err)
  58. if err != nil {
  59. return "", err
  60. }
  61. } else if string(user.Role) != consts.BRole {
  62. // 账号权限有误
  63. logrus.Debugf("[AuthCode] auth fail,phone:%+v", phone)
  64. return "权限错误,请登录企业账号", errors.New("auth fail")
  65. }
  66. vcode, err := l.getSessionCode(ctx, phone)
  67. if err != nil {
  68. return "", err
  69. }
  70. fmt.Printf("缓存的验证码 vcode: %v,实际填入的 code:%v", vcode, code)
  71. if vcode != code {
  72. // 验证码错误
  73. logrus.Debugf("[AuthCode] auth fail,phone:%+v", phone)
  74. return "验证码有误", errors.New("auth fail")
  75. }
  76. token := l.getToken(ctx, phone)
  77. enterprise, err := db.GetEnterpriseByUID(ctx, user.ID)
  78. if err != nil {
  79. return "", err
  80. }
  81. auth := &redis_model.Auth{
  82. Phone: phone,
  83. ID: user.ID,
  84. User: user.User,
  85. Username: user.Username,
  86. RealName: user.RealName,
  87. Role: user.Role,
  88. Email: user.Email,
  89. Token: token,
  90. EnterpriseID: enterprise.EnterpriseID,
  91. }
  92. if err := l.setSession(ctx, phone, auth); err != nil {
  93. fmt.Printf("setSession error\n")
  94. return "", err
  95. }
  96. return token, nil
  97. }
  98. // func (l *loginAuth) AuthPassword(ctx context.Context, phone string, password string) (string, error) {
  99. // // 验证是否存在
  100. // user, err := db.GetUserByPhone(ctx, phone)
  101. // if err != nil {
  102. // return "", err
  103. // }
  104. // // 验证正确性
  105. // if user == nil || user.Role != consts.BRole || user.Password != l.encryptPassword(password) {
  106. // // 登录失败
  107. // logrus.Debugf("[AuthPassword] auth fail,phone:%+v", phone)
  108. // return "", errors.New("auth fail")
  109. // }
  110. // token := l.getToken(ctx, phone)
  111. // auth := &redis_model.Auth{
  112. // Phone: phone,
  113. // ID: user.ID,
  114. // User: user.User,
  115. // Username: user.Username,
  116. // RealName: user.RealName,
  117. // Role: user.Role,
  118. // Email: user.Email,
  119. // Token: token,
  120. // }
  121. // if err := l.setSession(ctx, phone, auth); err != nil {
  122. // return "", err
  123. // }
  124. // return token, nil
  125. // }
  126. func (l *loginAuth) setSession(ctx context.Context, phone string, auth *redis_model.Auth) error {
  127. if authJson, err := json.Marshal(auth); err == nil {
  128. err = redis.Set(ctx, l.getRedisKey(phone), string(authJson), l.sessionTTL)
  129. if err == nil {
  130. return err
  131. }
  132. }
  133. return nil
  134. }
  135. func (l *loginAuth) getSessionCode(ctx context.Context, phone string) (string, error) {
  136. value, err := redis.Get(ctx, l.getRedisKey(phone))
  137. if err != nil {
  138. if err == consts.RedisNil {
  139. return "", fmt.Errorf("not found in redis,phone:%+v", phone)
  140. }
  141. return "", err
  142. }
  143. return value, nil
  144. }
  145. func (l *loginAuth) getSessionAuth(ctx context.Context, phone string) (*redis_model.Auth, error) {
  146. value, err := redis.Get(ctx, l.getRedisKey(phone))
  147. if err != nil {
  148. if err == consts.RedisNil {
  149. return nil, fmt.Errorf("not found in redis,phone:%+v", phone)
  150. }
  151. return nil, err
  152. }
  153. auth := new(redis_model.Auth)
  154. if err = json.Unmarshal([]byte(value), auth); err != nil {
  155. return nil, err
  156. }
  157. return auth, nil
  158. }
  159. func (l *loginAuth) getToken(ctx context.Context, phone string) string {
  160. timeSeed := strconv.FormatInt(time.Now().Unix(), 10)
  161. token := phone + "." + timeSeed + "." + util.MD5(phone, timeSeed, consts.AuthSalt)
  162. return token
  163. }
  164. func (l *loginAuth) parseToken(ctx context.Context, token string) (string, error) {
  165. parts := strings.Split(token, ".")
  166. if len(parts) == 3 {
  167. phone := parts[0]
  168. timeSeed := parts[1]
  169. if parts[2] == util.MD5(phone, timeSeed, consts.AuthSalt) {
  170. return phone, nil
  171. }
  172. }
  173. return "", errors.New("token invalid")
  174. }
  175. func (l *loginAuth) encryptPassword(password string) string {
  176. return util.MD5(password)
  177. }
  178. func (l *loginAuth) getRedisKey(key string) string {
  179. return fmt.Sprintf("%s%s", consts.SessionRedisPrefix, key)
  180. }