verify_login_controller.go 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. package controllers
  2. import (
  3. "XT_New/enums"
  4. "XT_New/models"
  5. "XT_New/service"
  6. "XT_New/utils"
  7. "fmt"
  8. "github.com/astaxie/beego"
  9. "net/url"
  10. "regexp"
  11. "strconv"
  12. "strings"
  13. )
  14. func VerifyUserLoginControllerRegistRouters() {
  15. beego.Router("/login", &VerifyUserLoginController{}, "get:Login")
  16. beego.Router("/logout", &VerifyUserLoginController{}, "get,post:Logout")
  17. beego.Router("/handle_error", &VerifyUserLoginController{}, "get:HandleError")
  18. beego.Router("/api/token/verify", &VerifyUserLoginAPIController{}, "post:VerifyToken")
  19. beego.Router("/api/admin/edit_info", &VerifyUserLoginAPIController{}, "post:EditAdminUserInfo")
  20. beego.Router("/api/password/code", &PersonAPIController{}, "post:CodeOfModifyPwd")
  21. beego.Router("/api/password/modify", &PersonAPIController{}, "post:ModifyPwd")
  22. }
  23. type VerifyUserLoginController struct {
  24. BaseViewController
  25. }
  26. // /login [get]
  27. // @param token?:string
  28. // @param relogin?:bool
  29. func (this *VerifyUserLoginController) Login() {
  30. token := this.Ctx.Input.Query("token")
  31. if len(token) > 0 { // 带 token 参数的一般是从 SSO 回调回来的
  32. utils.TraceLog("SSO Login 回调: token=%v", token)
  33. xtFrontEndDomain := beego.AppConfig.String("front_end_domain") + "?lt=" + token
  34. this.Redirect302(xtFrontEndDomain)
  35. } else {
  36. relogin, _ := this.GetBool("relogin", false)
  37. returnURL := url.QueryEscape(fmt.Sprintf("%v%v", beego.AppConfig.String("httpdomain"), this.Ctx.Request.RequestURI))
  38. ssoDomain := beego.AppConfig.String("sso_domain")
  39. ssoLoginURL := fmt.Sprintf("%v/login?returnurl=%v&app_type=3&relogin=%v", ssoDomain, returnURL, relogin)
  40. this.Redirect302(ssoLoginURL)
  41. }
  42. }
  43. // /logout [get/post]
  44. func (this *VerifyUserLoginController) Logout() {
  45. if this.Ctx.Request.Method == "GET" {
  46. this.DelSession("admin_user_info")
  47. this.Redirect302(fmt.Sprintf("%v/logout", beego.AppConfig.String("sso_domain")))
  48. } else if this.Ctx.Request.Method == "POST" {
  49. this.DelSession("admin_user_info")
  50. }
  51. }
  52. // /handle_error [get]
  53. // @param code:int
  54. func (this *VerifyUserLoginController) HandleError() {
  55. code, _ := this.GetInt("code")
  56. if code == enums.ErrorCodeNeverCreateTypeApp {
  57. ssoDomain := beego.AppConfig.String("sso_domain")
  58. createAppURL := fmt.Sprintf("%v/org/app/create", ssoDomain)
  59. this.Redirect302(createAppURL)
  60. } else if code == enums.ErrorCodeContactSuperAdminCreateTypeApp {
  61. ssoDomain := beego.AppConfig.String("sso_domain")
  62. hitURL := fmt.Sprintf("%v/create_app_hint", ssoDomain)
  63. this.Redirect302(hitURL)
  64. } else {
  65. this.Abort404()
  66. }
  67. }
  68. type VerifyUserLoginAPIController struct {
  69. BaseAPIController
  70. }
  71. // /api/token/verify [post]
  72. // @param token:string
  73. func (this *VerifyUserLoginAPIController) VerifyToken() {
  74. if this.Ctx.Request.Method == "OPTIONS" {
  75. this.Abort("200")
  76. } else {
  77. token := this.GetString("token")
  78. utils.TraceLog("token: %v", token)
  79. if len(token) == 0 {
  80. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  81. return
  82. }
  83. ip := utils.GetIP(this.Ctx.Request)
  84. fmt.Println("ip是什么", ip)
  85. sessionID := this.Ctx.GetCookie("s")
  86. fmt.Println("sessionID", sessionID)
  87. utils.TraceLog("Request: %v", this.Ctx.Request)
  88. utils.TraceLog("cookie session id: %v", sessionID)
  89. adminUserInfo, err, errCode := service.VerifyToken(token, ip, sessionID)
  90. fmt.Println("错误是什么", err)
  91. fmt.Println("errCode是什么", errCode)
  92. if err != nil {
  93. if errCode == 903 { // 未创建应用
  94. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeNeverCreateTypeApp)
  95. } else if errCode == 904 { // 联系超管来开通
  96. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeContactSuperAdminCreateTypeApp)
  97. } else {
  98. utils.ErrorLog("令牌验证失败:%v", err)
  99. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeInvalidToken)
  100. }
  101. return
  102. } else {
  103. adminUser := adminUserInfo.AdminUser
  104. appRole := adminUserInfo.AppRoles[adminUserInfo.CurrentAppId]
  105. userInfo := map[string]interface{}{
  106. "id": adminUser.Id,
  107. "mobile": adminUser.Mobile,
  108. "user_name": appRole.UserName,
  109. "avatar": appRole.Avatar,
  110. "intro": appRole.Intro,
  111. "user_type": appRole.UserType,
  112. "user_title": appRole.UserTitle,
  113. }
  114. curOrg := adminUserInfo.Orgs[adminUserInfo.CurrentOrgId]
  115. org := map[string]interface{}{
  116. "id": curOrg.Id,
  117. "org_name": curOrg.OrgName,
  118. "org_short_name": curOrg.OrgShortName,
  119. "org_intro": curOrg.OrgIntroduction,
  120. "org_logo": curOrg.OrgLogo,
  121. "province": curOrg.Province,
  122. "city": curOrg.City,
  123. "district": curOrg.District,
  124. "address": curOrg.Address,
  125. }
  126. var didRegistedForSCRM bool = false
  127. var didRegistedForCDM bool = false
  128. var didRegistedForMall bool = false
  129. tempInfo, _ := service.GetOrgInfoTemplate(curOrg.Id)
  130. fmt.Println("teimpInfo", tempInfo)
  131. template_info := map[string]interface{}{
  132. "id": tempInfo.ID,
  133. "org_id": tempInfo.OrgId,
  134. "template_id": tempInfo.TemplateId,
  135. }
  136. var FiledList []*models.FiledConfig
  137. FiledList, _ = service.FindFiledByOrgId(curOrg.Id)
  138. if len(FiledList) == 0 {
  139. err := service.BatchInsertFiledConfig(curOrg.Id)
  140. if err == nil {
  141. FiledList, _ = service.FindFiledByOrgId(curOrg.Id)
  142. } else {
  143. utils.ErrorLog("字段批量插入失败:%v", err)
  144. }
  145. }
  146. QualityeList, err := service.FindQualityByOrgId(curOrg.Id)
  147. if len(QualityeList) == 0 {
  148. err = service.BatchInsertQualityControl(curOrg.Id)
  149. } else {
  150. utils.ErrorLog("字段批量插入失败:%v", err)
  151. }
  152. InspectionList, err := service.FindeInspectionByOrgId(curOrg.Id)
  153. if len(InspectionList) == 0 {
  154. err = service.BatchInspectionConfiguration(curOrg.Id)
  155. } else {
  156. utils.ErrorLog("字段批量插入失败:%v", err)
  157. }
  158. var pruviews []*models.Purview
  159. var curAppUrlfors []string
  160. if len(curAppUrlfors) == 0 {
  161. if adminUser.Id == curOrg.Creator { //超级管理员
  162. urlfors, _, _ := service.GetSuperAdminUsersPurviewTreeAndUrlfors(3)
  163. didRegistedForSCRM = true
  164. didRegistedForCDM = true
  165. didRegistedForMall = true
  166. //urlfors, _, _ := service.GetSuperAdminUsersPurviewTreeAndUrlfors(4)
  167. //urlfors, _, _ := service.GetSuperAdminUsersPurviewTreeAndUrlfors(5)
  168. //urlfors, _, _ := service.GetSuperAdminUsersPurviewTreeAndUrlfors(6)
  169. curAppUrlfors = urlfors
  170. } else {
  171. appRole, _ := service.FindAdminUserIDA(appRole.Id)
  172. if appRole.Id > 0 && len(appRole.RoleIds) > 0 {
  173. role_arr := strings.Split(appRole.RoleIds, ",")
  174. var ids string
  175. for _, role_id := range role_arr {
  176. id, _ := strconv.ParseInt(role_id, 10, 64)
  177. role, _ := service.GetRoleByRoleID(id)
  178. var system_ids = ""
  179. if role.RoleName == "子管理员" && role.IsSystem > 0 {
  180. purviews, _ := service.GetSystemPurview()
  181. for _, purview := range purviews {
  182. if len(system_ids) == 0 {
  183. system_ids = strconv.FormatInt(purview.Id, 10)
  184. } else {
  185. system_ids = system_ids + "," + strconv.FormatInt(purview.Id, 10)
  186. }
  187. }
  188. }
  189. purview_ids, _ := service.GetRolePurviewIds(id)
  190. if len(ids) == 0 {
  191. ids = purview_ids
  192. } else {
  193. ids = ids + "," + purview_ids
  194. }
  195. if len(system_ids) > 0 {
  196. ids = ids + "," + system_ids
  197. }
  198. }
  199. if len(ids) != 0 {
  200. pruviews, _ = service.GetPurviewById(CompressStr(ids))
  201. for _, item := range pruviews {
  202. if item.Module == 3 && item.Parentid > 0 {
  203. fmt.Println(item.Urlfor)
  204. curAppUrlfors = append(curAppUrlfors, item.Urlfor)
  205. }
  206. }
  207. } else {
  208. curAppUrlfors = append(curAppUrlfors, "")
  209. }
  210. } else {
  211. curAppUrlfors = append(curAppUrlfors, "")
  212. }
  213. }
  214. }
  215. for _, item := range pruviews {
  216. if item.Module == 6 {
  217. didRegistedForSCRM = true
  218. }
  219. if item.Module == 4 {
  220. didRegistedForCDM = true
  221. }
  222. if item.Module == 7 {
  223. didRegistedForMall = true
  224. }
  225. }
  226. if adminUser.Id == curOrg.Creator { //超级管理员
  227. didRegistedForSCRM = true
  228. didRegistedForCDM = true
  229. didRegistedForMall = true
  230. }
  231. subscibe, _ := service.GetOrgSubscibe(adminUserInfo.CurrentOrgId)
  232. this.SetSession("admin_user_info", adminUserInfo)
  233. this.ServeSuccessJSON(map[string]interface{}{
  234. "user": userInfo,
  235. "org": org,
  236. "urlfors": curAppUrlfors,
  237. "current_org_id": adminUserInfo.CurrentOrgId,
  238. "current_app_id": adminUserInfo.CurrentAppId,
  239. "subscibe": subscibe,
  240. "scrm_role_exist": didRegistedForSCRM,
  241. "cdm_role_exist": didRegistedForCDM,
  242. "mall_role_exist": didRegistedForMall,
  243. "template_info": template_info,
  244. "fileds": FiledList,
  245. })
  246. return
  247. }
  248. }
  249. }
  250. // /api/admin/edit_info [post]
  251. // @param avatar:string
  252. // @param name:string
  253. // @param opwd?:string 没有原始密码的时候,认为不修改密码
  254. // @param npwd?:string
  255. func (this *VerifyUserLoginAPIController) EditAdminUserInfo() {
  256. adminUserInfo := this.GetAdminUserInfo()
  257. avatar := this.GetString("avatar")
  258. name := this.GetString("name")
  259. if len(name) == 0 {
  260. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeMissingUserName)
  261. return
  262. }
  263. // oldPwd := this.GetString("opwd")
  264. // newPwd := this.GetString("npwd")
  265. // modifyPwd := len(oldPwd) != 0
  266. // if modifyPwd {
  267. // if len(newPwd) == 0 {
  268. // this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodePasswordEmpty)
  269. // this.ServeJSON()
  270. // return
  271. // }
  272. // pwdRight, err := service.IsPasswordRight(adminUserInfo.AdminUser.Id, oldPwd)
  273. // if err != nil {
  274. // utils.ErrorLog("判断旧密码是否错误失败:%v", err)
  275. // this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  276. // this.ServeJSON()
  277. // return
  278. // }
  279. // if !pwdRight {
  280. // this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeOldPasswordWrong)
  281. // this.ServeJSON()
  282. // return
  283. // }
  284. // } else {
  285. // newPwd = ""
  286. // }
  287. modifyErr := service.ModifyAdminUserInfo(adminUserInfo.AdminUser.Id, adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId, name, avatar, "")
  288. if modifyErr != nil {
  289. this.ErrorLog("修改个人信息失败:%v", modifyErr)
  290. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBUpdate)
  291. } else {
  292. appRole := adminUserInfo.AppRoles[adminUserInfo.CurrentAppId]
  293. appRole.UserName = name
  294. appRole.Avatar = avatar
  295. this.ServeSuccessJSON(nil)
  296. }
  297. }
  298. type PersonAPIController struct {
  299. BaseAuthAPIController
  300. }
  301. // /api/password/code [post]
  302. func (this *PersonAPIController) CodeOfModifyPwd() {
  303. adminUserInfo := this.GetAdminUserInfo()
  304. mobile := adminUserInfo.AdminUser.Mobile
  305. if err := service.SMSSendVerificationCode(mobile); err != nil {
  306. utils.ErrorLog("修改密码发送验证码失败:%v", err)
  307. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  308. return
  309. } else {
  310. this.ServeSuccessJSON(map[string]interface{}{
  311. "msg": "短信发送成功,有效期为10分钟",
  312. })
  313. }
  314. }
  315. // /api/password/modify [post]
  316. // @param password:string
  317. // @param code:string
  318. func (this *PersonAPIController) ModifyPwd() {
  319. new_pwd := this.GetString("password")
  320. code := this.GetString("code")
  321. if len(new_pwd) == 0 || len(code) == 0 {
  322. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  323. return
  324. }
  325. adminUserInfo := this.GetAdminUserInfo()
  326. mobile := adminUserInfo.AdminUser.Mobile
  327. redisClient := service.RedisClient()
  328. defer redisClient.Close()
  329. cachedCode, err := redisClient.Get("xt_modify_pwd_" + mobile).Result()
  330. if err != nil {
  331. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAccountOrVerCodeWrong)
  332. return
  333. }
  334. if code != cachedCode {
  335. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAccountOrVerCodeWrong)
  336. return
  337. }
  338. if modifyErr := service.ModifyPassword(adminUserInfo.AdminUser.Id, new_pwd); modifyErr != nil {
  339. this.ErrorLog("修改密码失败:%v", modifyErr)
  340. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  341. return
  342. }
  343. // 清除验证码
  344. redisClient.Del("xt_modify_pwd_" + mobile)
  345. this.ServeSuccessJSON(map[string]interface{}{
  346. "msg": "密码已修改",
  347. })
  348. }
  349. func CompressStr(str string) string {
  350. if str == "" {
  351. return ""
  352. }
  353. //匹配一个或多个空白符的正则表达式
  354. reg := regexp.MustCompile("\\s+")
  355. return reg.ReplaceAllString(str, "")
  356. }