login_auth.go 9.9 KB

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