login_auth.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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/gorm_model"
  13. "youngee_b_api/model/http_model"
  14. "youngee_b_api/model/redis_model"
  15. "youngee_b_api/model/system_model"
  16. "youngee_b_api/redis"
  17. "youngee_b_api/util"
  18. "github.com/sirupsen/logrus"
  19. )
  20. var LoginAuth *loginAuth
  21. func LoginAuthInit(config *system_model.Session) {
  22. auth := new(loginAuth)
  23. auth.sessionTTL = time.Duration(config.TTL) * time.Minute
  24. LoginAuth = auth
  25. }
  26. type loginAuth struct {
  27. sessionTTL time.Duration
  28. }
  29. func (l *loginAuth) AuthToken(ctx context.Context, token string) (*redis_model.Auth, error) {
  30. phone, err := l.parseToken(ctx, token)
  31. if err != nil {
  32. logrus.Debug("token格式错误:%+v", token)
  33. return nil, err
  34. }
  35. auth, err := l.getSessionAuth(ctx, phone)
  36. if err != nil {
  37. logrus.Debug("获取session redis错误: token:%+v,err:%+v", token, err)
  38. return nil, err
  39. }
  40. if auth.Token != token {
  41. logrus.Debug("获取session time过期错误: token:%+v", token)
  42. return nil, errors.New("auth failed")
  43. }
  44. return auth, nil
  45. }
  46. // AuthCode 判断此手机号是否有账号存在 鉴定验证码 用户信息存入redis 并返回Token
  47. func (l *loginAuth) AuthCode(ctx context.Context, phone string, code string) (string, *http_model.CodeLoginData, error) {
  48. // 1. 验证码校验
  49. vcode, err := l.getSessionCode(ctx, phone)
  50. if err != nil {
  51. return "", nil, err
  52. }
  53. fmt.Printf("缓存的验证码 vcode: %v,实际填入的 code:%v", vcode, code)
  54. if vcode != code {
  55. // 验证码错误
  56. logrus.Debugf("[AuthCode] auth fail,phone:%+v", phone)
  57. return "验证码有误", nil, errors.New("auth fail")
  58. }
  59. // 2. 查询是否存在用户信息,存在则取出,不存在则注册并取出
  60. var userData *gorm_model.YounggeeUser
  61. user, err := db.GetUserByPhone(ctx, phone)
  62. fmt.Println("login_auth", user, err)
  63. if err != nil {
  64. // 数据库操作错误
  65. return "", nil, err
  66. } else if user == nil {
  67. user, err := db.GetSubUserByPhone(ctx, phone)
  68. fmt.Println("子账号存在")
  69. if user == nil {
  70. fmt.Println("子账号也不存在")
  71. // 账号不存在,则默认注册商家账号
  72. _, err = Enterprise.CreateEnterprise(ctx, phone)
  73. if err != nil {
  74. return "账号创建失败", nil, err
  75. }
  76. user, err = db.GetUserByPhone(ctx, phone)
  77. userData = user
  78. fmt.Println("login_auth", user, err)
  79. if err != nil {
  80. return "", nil, err
  81. }
  82. } else {
  83. userData = user
  84. }
  85. } else if user != nil {
  86. userData = user
  87. }
  88. token := l.getToken(ctx, phone)
  89. var jobData gorm_model.YounggeeJob
  90. var accountData gorm_model.YounggeeSubAccount
  91. var enterpriseUser gorm_model.Enterprise
  92. var loginUserData http_model.CodeLoginData
  93. var ifEnterprise int = 0
  94. var ifSubAccount int = 0
  95. // 3. 根据用户类型的不同补充信息
  96. // 若为商家用户
  97. if string(userData.Role) == consts.BRole {
  98. ifEnterprise = 1
  99. fmt.Println("商家主账号")
  100. enterprise, err := db.GetEnterpriseByUID(ctx, userData.ID)
  101. enterpriseUser = *enterprise
  102. if err != nil {
  103. return "", nil, err
  104. }
  105. auth := &redis_model.Auth{
  106. Phone: phone,
  107. ID: userData.ID,
  108. User: userData.User,
  109. Username: userData.Username,
  110. RealName: userData.RealName,
  111. Role: userData.Role,
  112. Email: userData.Email,
  113. Token: token,
  114. EnterpriseID: enterprise.EnterpriseID,
  115. }
  116. if err := l.setSession(ctx, phone, auth); err != nil {
  117. fmt.Printf("setSession error\n")
  118. return "", nil, err
  119. }
  120. } else {
  121. // 若为商家子账号
  122. ifSubAccount = 1
  123. fmt.Printf("商家子账号")
  124. subaccount, err := db.FindSubAccountByPhone(ctx, phone)
  125. accountData = *subaccount
  126. if err != nil {
  127. return "", nil, err
  128. }
  129. auth := &redis_model.Auth{
  130. Phone: phone,
  131. ID: userData.ID,
  132. User: userData.User,
  133. Username: userData.Username,
  134. RealName: userData.RealName,
  135. Role: userData.Role,
  136. Email: userData.Email,
  137. Token: token,
  138. EnterpriseID: subaccount.EnterpriseId,
  139. }
  140. job, err := db.FindJobByJobId(ctx, subaccount.JobId)
  141. jobData = *job
  142. if err := l.setSession(ctx, phone, auth); err != nil {
  143. fmt.Printf("setSession error\n")
  144. return "", nil, err
  145. }
  146. }
  147. if ifEnterprise == 1 {
  148. loginUserData = http_model.CodeLoginData{
  149. UserId: userData.ID,
  150. Token: token,
  151. Role: userData.Role,
  152. SubAccountId: 0,
  153. JobName: "主账号无岗位",
  154. EnterpriseId: enterpriseUser.EnterpriseID,
  155. WorkshopPermission: "1",
  156. CooperatePermission: "1",
  157. FinancialPermission: "1",
  158. TaskcenterPermission: "1",
  159. }
  160. } else if ifSubAccount == 1 {
  161. loginUserData = http_model.CodeLoginData{
  162. UserId: userData.ID,
  163. Token: token,
  164. Role: userData.Role,
  165. SubAccountId: accountData.SubAccountId,
  166. JobName: jobData.JobName,
  167. EnterpriseId: accountData.EnterpriseId,
  168. WorkshopPermission: jobData.WorkshopPermission,
  169. CooperatePermission: jobData.CooperatePermission,
  170. FinancialPermission: jobData.FinancialPermission,
  171. TaskcenterPermission: jobData.TaskcenterPermission,
  172. }
  173. }
  174. return "", &loginUserData, nil
  175. }
  176. // func (l *loginAuth) AuthPassword(ctx context.Context, phone string, password string) (string, error) {
  177. // // 验证是否存在
  178. // user, err := db.GetUserByPhone(ctx, phone)
  179. // if err != nil {
  180. // return "", err
  181. // }
  182. // // 验证正确性
  183. // if user == nil || user.Role != consts.BRole || user.Password != l.encryptPassword(password) {
  184. // // 登录失败
  185. // logrus.Debugf("[AuthPassword] auth fail,phone:%+v", phone)
  186. // return "", errors.New("auth fail")
  187. // }
  188. // token := l.getToken(ctx, phone)
  189. // auth := &redis_model.Auth{
  190. // Phone: phone,
  191. // ID: user.ID,
  192. // User: user.User,
  193. // Username: user.Username,
  194. // RealName: user.RealName,
  195. // Role: user.Role,
  196. // Email: user.Email,
  197. // Token: token,
  198. // }
  199. // if err := l.setSession(ctx, phone, auth); err != nil {
  200. // return "", err
  201. // }
  202. // return token, nil
  203. // }
  204. func (l *loginAuth) setSession(ctx context.Context, phone string, auth *redis_model.Auth) error {
  205. if authJson, err := json.Marshal(auth); err == nil {
  206. err = redis.Set(ctx, l.getRedisKey(phone), string(authJson), l.sessionTTL)
  207. if err == nil {
  208. return err
  209. }
  210. }
  211. return nil
  212. }
  213. func (l *loginAuth) getSessionCode(ctx context.Context, phone string) (string, error) {
  214. value, err := redis.Get(ctx, l.getRedisKey(phone))
  215. if err != nil {
  216. if err == consts.RedisNil {
  217. return "", fmt.Errorf("not found in redis,phone:%+v", phone)
  218. }
  219. return "", err
  220. }
  221. return value, nil
  222. }
  223. func (l *loginAuth) getSessionAuth(ctx context.Context, phone string) (*redis_model.Auth, error) {
  224. value, err := redis.Get(ctx, l.getRedisKey(phone))
  225. if err != nil {
  226. if err == consts.RedisNil {
  227. return nil, fmt.Errorf("not found in redis,phone:%+v", phone)
  228. }
  229. return nil, err
  230. }
  231. auth := new(redis_model.Auth)
  232. if err = json.Unmarshal([]byte(value), auth); err != nil {
  233. return nil, err
  234. }
  235. return auth, nil
  236. }
  237. func (l *loginAuth) getToken(ctx context.Context, phone string) string {
  238. timeSeed := strconv.FormatInt(time.Now().Unix(), 10)
  239. token := phone + "." + timeSeed + "." + util.MD5(phone, timeSeed, consts.AuthSalt)
  240. return token
  241. }
  242. func (l *loginAuth) parseToken(ctx context.Context, token string) (string, error) {
  243. parts := strings.Split(token, ".")
  244. if len(parts) == 3 {
  245. phone := parts[0]
  246. timeSeed := parts[1]
  247. if parts[2] == util.MD5(phone, timeSeed, consts.AuthSalt) {
  248. return phone, nil
  249. }
  250. }
  251. return "", errors.New("token invalid")
  252. }
  253. func (l *loginAuth) encryptPassword(password string) string {
  254. return util.MD5(password)
  255. }
  256. func (l *loginAuth) getRedisKey(key string) string {
  257. return fmt.Sprintf("%s%s", consts.SessionRedisPrefix, key)
  258. }
  259. func (l *loginAuth) SubAccountAuthCode(ctx context.Context, phone string, code string) (string, error) {
  260. bSubAccountUser, err := db.FindSubAccountByPhone(ctx, phone)
  261. phoneNumber := phone
  262. fmt.Println("login_auth", bSubAccountUser, err)
  263. if err != nil {
  264. // 数据库错误
  265. return "数据库错误", err
  266. }
  267. if bSubAccountUser == nil {
  268. // 账号不存在,则判断此手机号码是否被商家主账号注册
  269. bUser, err := db.GetUserByPhone(ctx, phoneNumber)
  270. if err != nil {
  271. // 数据库操作错误
  272. return "", err
  273. }
  274. if bUser == nil {
  275. // 没有被商家主账户注册,则可以注册
  276. vcode, err := l.getSessionCode(ctx, phoneNumber)
  277. if err != nil {
  278. return "session err", err
  279. }
  280. fmt.Printf("缓存的验证码 vcode: %v,实际填入的 code:%v", vcode, code)
  281. if vcode != code {
  282. // 验证码错误
  283. logrus.Debugf("[AuthCode] auth fail,phone:%+v", phone)
  284. return "验证码有误", errors.New("auth fail")
  285. }
  286. return "1", err
  287. } else if string(bUser.Role) == consts.BRole {
  288. if bUser.AuthStatus == 1 {
  289. // 被商家主账户注册,未认证,则可以注册
  290. vcode, err := l.getSessionCode(ctx, phoneNumber)
  291. if err != nil {
  292. return "session err", err
  293. }
  294. fmt.Printf("缓存的验证码 vcode: %v,实际填入的 code:%v", vcode, code)
  295. if vcode != code {
  296. // 验证码错误
  297. logrus.Debugf("[AuthCode] auth fail,phone:%+v", phone)
  298. return "验证码有误", errors.New("auth fail")
  299. }
  300. return "1", err
  301. } else {
  302. return "主账号存在", errors.New("auth fail")
  303. }
  304. }
  305. } else {
  306. // 子账号存在,则无法注册
  307. logrus.Debugf("[AuthCode] auth fail,phone:%+v", phone)
  308. return "子账号存在", errors.New("subAccount exist")
  309. }
  310. return "", nil
  311. }