verify_login_controller.go 14KB

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