verify_login_token_service.go 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. package service
  2. import (
  3. "encoding/json"
  4. "github.com/jinzhu/gorm"
  5. "io/ioutil"
  6. "net/http"
  7. "net/url"
  8. "strconv"
  9. "time"
  10. "Xcx_New/models"
  11. "Xcx_New/utils"
  12. "fmt"
  13. "github.com/astaxie/beego"
  14. )
  15. type AdminUserInfo struct {
  16. AdminUser *models.AdminUser `json:"user"`
  17. CurrentOrgId int64 `json:"current_org_id"`
  18. CurrentAppId int64 `json:"current_app_id"`
  19. OrgIds []int64 `json:"org_ids"`
  20. Orgs map[int64]*models.Org `json:"orgs"`
  21. OrgAppIds map[int64][]int64 `json:"org_app_ids"`
  22. OrgApps map[int64](map[int64]*models.OrgApp) `json:"org_apps"`
  23. App2OrgIds map[int64]int64 `json:"app_to_org_ids"`
  24. AppRoles map[int64]*models.App_Role `json:"app_roles"`
  25. AppPurviews map[int64][]*models.Purview `json:"app_purviews"`
  26. AppUrlfors map[int64][]string `json:"app_urlfors"`
  27. Subscibes map[int64]*models.ServeSubscibe `json:"org_subscibes"`
  28. }
  29. type verifyTokenError struct {
  30. Msg string
  31. }
  32. func (e *verifyTokenError) Error() string {
  33. return e.Msg
  34. }
  35. // 验证 token 成功后返回的管理员用户的所有信息,包括:基本用户信息,所属的所有机构,机构下的所有应用,应用的用户权限
  36. // map 的数据格式为
  37. /*
  38. "admin_user": { AdminUser's json },
  39. current_org_id: 1,
  40. current_app_id: 11,
  41. "org_ids": [1, 2, 3],
  42. "orgs": { (org_id: Org_Obj)
  43. 1: { Org's json },
  44. 2: { Org's json },
  45. },
  46. "org_app_ids": { (org_id: org_app_ids)
  47. 1: [11, 12, 13],
  48. 2: [21, 22, 23],
  49. },
  50. "org_apps": { (org_id: {app_id: OrgApp_Obj})
  51. 1: {
  52. 11: { OrgApp's json },
  53. 12: { OrgApp's json },
  54. },
  55. 2: {
  56. 21: { OrgApp's json },
  57. 22: { OrgApp's json },
  58. },
  59. },
  60. "app_to_org_ids": { (app_id: org_id)
  61. 11: 1,
  62. 12: 1,
  63. 21: 2,
  64. 22: 2,
  65. },
  66. "app_roles": { (app_id: App_Role Obj)
  67. 11: {App_Role's json},
  68. 12: {App_Role's json},
  69. 21: {App_Role's json},
  70. },
  71. "purviews": { (app_id: [processed Purviews' json])
  72. 11: [
  73. {Purview's json .childs[
  74. {Purview's json},
  75. {Purview's json},
  76. ]},
  77. {Purview's json},
  78. ],
  79. 12: [
  80. {Purview's json},
  81. {Purview's json},
  82. ],
  83. },
  84. "purview_urlfors": { (app_id: [url_for])
  85. 11: [
  86. "Controller1.Action1",
  87. "Controller1.Action2",
  88. "Controller2.Action1",
  89. "Controller2.Action2",
  90. ],
  91. }
  92. 应当注意的是,屈服于 Golang 令人恶心的类型机制,这里将所有数值型的 key 或 value 全部转成了 string
  93. */
  94. // 解析用户信息,并返回
  95. func VerifyToken(token string, ip string, sessionID string) (*AdminUserInfo, error, int) {
  96. // if len(sessionID) == 0 {
  97. // return nil, &verifyTokenError{"sessionID 为空"}
  98. // }
  99. ssoDomain := beego.AppConfig.String("sso_domain")
  100. api := ssoDomain + "/verifytoken"
  101. values := make(url.Values)
  102. values.Set("token", token)
  103. values.Set("app_type", "3")
  104. values.Set("ip", ip)
  105. values.Set("session_id", sessionID)
  106. resp, requestErr := http.PostForm(api, values)
  107. if requestErr != nil {
  108. utils.ErrorLog("请求验证 sso token 接口失败: %v", requestErr)
  109. return nil, requestErr, 0
  110. }
  111. defer resp.Body.Close()
  112. body, ioErr := ioutil.ReadAll(resp.Body)
  113. if ioErr != nil {
  114. utils.ErrorLog("验证 sso token 接口返回数据读取失败: %v", ioErr)
  115. return nil, ioErr, 0
  116. }
  117. var respJSON map[string]interface{}
  118. if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
  119. utils.ErrorLog("验证 sso token 接口返回数据解析JSON失败: %v", err)
  120. return nil, err, 0
  121. }
  122. if respJSON["state"].(float64) != 1 {
  123. msg := respJSON["msg"].(string)
  124. utils.ErrorLog("验证 sso token 接口请求失败: %v", msg)
  125. return nil, &verifyTokenError{"验证 sso token 接口请求失败"}, int(respJSON["code"].(float64))
  126. } else {
  127. utils.SuccessLog("验证 sso token 成功")
  128. return processAdminUserInfo(respJSON["data"].(map[string]interface{})), nil, 0
  129. }
  130. }
  131. func processAdminUserInfo(data map[string]interface{}) *AdminUserInfo {
  132. adminUser := processAdminUser(data)
  133. currentOrgId, currentAppId := processCurrentOrgIDAndAppID(data)
  134. orgIds := processOrgIds(data)
  135. orgs := processOrgs(data)
  136. orgAppIds := processOrgAppIds(data)
  137. orgApps := processOrgApps(data)
  138. //app2OrgIds := processApp2OrgIds(data)
  139. appRoles := processAppRoles(data)
  140. appPurviews := processPurviews(data)
  141. appUrlfors := processPurviewUrlfors(data)
  142. //orgSubscibes := processOrgSubscibes(data)
  143. sessionAdminUserInfo := &AdminUserInfo{
  144. AdminUser: adminUser,
  145. CurrentOrgId: currentOrgId,
  146. CurrentAppId: currentAppId,
  147. OrgIds: orgIds,
  148. Orgs: orgs,
  149. OrgAppIds: orgAppIds,
  150. OrgApps: orgApps,
  151. //App2OrgIds: app2OrgIds,
  152. AppRoles: appRoles,
  153. AppPurviews: appPurviews,
  154. AppUrlfors: appUrlfors,
  155. //Subscibes: orgSubscibes,
  156. }
  157. return sessionAdminUserInfo
  158. }
  159. // "admin_user": { AdminUser's json },
  160. func processAdminUser(data map[string]interface{}) *models.AdminUser {
  161. userJSONStr := data["admin_user"].(string)
  162. var adminUser models.AdminUser
  163. if err := json.Unmarshal([]byte(userJSONStr), &adminUser); err != nil {
  164. utils.ErrorLog("解析用户信息失败:%v", err)
  165. return nil
  166. } else {
  167. return &adminUser
  168. }
  169. }
  170. // current_org_id: 1,
  171. // current_app_id: 11,
  172. func processCurrentOrgIDAndAppID(data map[string]interface{}) (int64, int64) {
  173. orgIDStr := data["current_org_id"].(string)
  174. appIDStr := data["current_app_id"].(string)
  175. orgID, _ := strconv.Atoi(orgIDStr)
  176. appID, _ := strconv.Atoi(appIDStr)
  177. return int64(orgID), int64(appID)
  178. }
  179. // "org_ids": [1, 2, 3],
  180. func processOrgIds(data map[string]interface{}) []int64 {
  181. orgIdStrs := data["org_ids"].([]interface{})
  182. orgIds := make([]int64, 0, len(orgIdStrs))
  183. for _, idstr := range orgIdStrs {
  184. id, _ := strconv.Atoi(idstr.(string))
  185. orgIds = append(orgIds, int64(id))
  186. }
  187. return orgIds
  188. }
  189. // "orgs": { (org_id: Org_Obj)
  190. // 1: { Org's json },
  191. // 2: { Org's json },
  192. // },
  193. func processOrgs(data map[string]interface{}) map[int64]*models.Org {
  194. orgJSONs := data["orgs"].(map[string]interface{})
  195. orgs := make(map[int64]*models.Org)
  196. for orgIdStr, orgJSON := range orgJSONs {
  197. orgId, _ := strconv.Atoi(orgIdStr)
  198. var org models.Org
  199. json.Unmarshal([]byte(orgJSON.(string)), &org)
  200. orgs[int64(orgId)] = &org
  201. }
  202. return orgs
  203. }
  204. // "org_app_ids": { (org_id: org_app_ids)
  205. // 1: [11, 12, 13],
  206. // 2: [21, 22, 23],
  207. // },
  208. func processOrgAppIds(data map[string]interface{}) map[int64][]int64 {
  209. orgAppIdStrs := data["org_app_ids"].(map[string]interface{})
  210. orgAppIds := make(map[int64][]int64)
  211. for orgIdStr, appIdStrs := range orgAppIdStrs {
  212. orgId, _ := strconv.Atoi(orgIdStr)
  213. appIds := make([]int64, 0, len(appIdStrs.([]interface{})))
  214. for _, appIdStr := range appIdStrs.([]interface{}) {
  215. appId, _ := strconv.Atoi(appIdStr.(string))
  216. appIds = append(appIds, int64(appId))
  217. }
  218. orgAppIds[int64(orgId)] = appIds
  219. }
  220. return orgAppIds
  221. }
  222. // "org_apps": { (org_id: {app_id: OrgApp_Obj})
  223. // 1: {
  224. // 11: { OrgApp's json },
  225. // 12: { OrgApp's json },
  226. // },
  227. // 2: {
  228. // 21: { OrgApp's json },
  229. // 22: { OrgApp's json },
  230. // },
  231. // },
  232. func processOrgApps(data map[string]interface{}) map[int64]map[int64]*models.OrgApp {
  233. orgAppJSONs := data["org_apps"].(map[string]interface{})
  234. orgApps := make(map[int64]map[int64]*models.OrgApp)
  235. for orgIdStr, appJSONStrMap := range orgAppJSONs {
  236. orgId, _ := strconv.Atoi(orgIdStr)
  237. apps := make(map[int64]*models.OrgApp)
  238. for appIdStr, appJSONStr := range appJSONStrMap.(map[string]interface{}) {
  239. appId, _ := strconv.Atoi(appIdStr)
  240. var app models.OrgApp
  241. json.Unmarshal([]byte(appJSONStr.(string)), &app)
  242. apps[int64(appId)] = &app
  243. }
  244. orgApps[int64(orgId)] = apps
  245. }
  246. return orgApps
  247. }
  248. // "app_to_org_ids": { (app_id: org_id)
  249. // 11: 1,
  250. // 12: 1,
  251. // 21: 2,
  252. // 22: 2,
  253. // },
  254. func processApp2OrgIds(data map[string]interface{}) map[int64]int64 {
  255. app2OrgIdStrs := data["app_to_org_ids"].(map[string]interface{})
  256. app2OrgIds := make(map[int64]int64)
  257. for appIdStr, orgIdStr := range app2OrgIdStrs {
  258. orgId, _ := strconv.Atoi(orgIdStr.(string))
  259. appId, _ := strconv.Atoi(appIdStr)
  260. app2OrgIds[int64(appId)] = int64(orgId)
  261. }
  262. return app2OrgIds
  263. }
  264. // "app_roles": { (app_id: App_Role Obj)
  265. // 11: {App_Role's json},
  266. // 12: {App_Role's json},
  267. // 21: {App_Role's json},
  268. // },
  269. func processAppRoles(data map[string]interface{}) map[int64]*models.App_Role {
  270. appRoleJSONs := data["app_roles"].(map[string]interface{})
  271. appRoles := make(map[int64]*models.App_Role)
  272. for appIDStr, appRoleJSON := range appRoleJSONs {
  273. appID, _ := strconv.Atoi(appIDStr)
  274. var appRole models.App_Role
  275. json.Unmarshal([]byte(appRoleJSON.(string)), &appRole)
  276. appRoles[int64(appID)] = &appRole
  277. }
  278. return appRoles
  279. }
  280. // "purviews": { (app_id: [processed Purviews' json])
  281. // 11: [
  282. // {Purview's json .childs[
  283. // {Purview's json},
  284. // {Purview's json},
  285. // ]},
  286. // {Purview's json},
  287. // ],
  288. // 12: [
  289. // {Purview's json},
  290. // {Purview's json},
  291. // ],
  292. // },
  293. func processPurviews(data map[string]interface{}) map[int64][]*models.Purview {
  294. appPurviewJSONsStrs := data["purviews"].(map[string]interface{})
  295. appPurviews := make(map[int64][]*models.Purview)
  296. for appIdStr, purviewJSONsStr := range appPurviewJSONsStrs {
  297. appId, _ := strconv.Atoi(appIdStr)
  298. var purviews []*models.Purview
  299. json.Unmarshal([]byte(purviewJSONsStr.(string)), &purviews)
  300. // setLinkForPurviews(purviews)
  301. appPurviews[int64(appId)] = purviews
  302. }
  303. return appPurviews
  304. }
  305. // func setLinkForPurviews(purviews []*models.Purview) {
  306. // for _, purview := range purviews {
  307. // if len(purview.Urlfor) == 0 {
  308. // purview.Link = ""
  309. // } else {
  310. // purview.Link = beego.URLFor(purview.Urlfor)
  311. // }
  312. // if purview.Childs == nil {
  313. // purview.Childs = make([]*models.Purview, 0)
  314. // } else {
  315. // setLinkForPurviews(purview.Childs)
  316. // }
  317. // // utils.TraceLog("%+v", purview)
  318. // }
  319. // }
  320. // "purview_urlfors": { (app_id: [url_for])
  321. // 11: [
  322. // "Controller1.Action1",
  323. // "Controller1.Action2",
  324. // "Controller2.Action1",
  325. // "Controller2.Action2",
  326. // ],
  327. // }
  328. func processPurviewUrlfors(data map[string]interface{}) map[int64][]string {
  329. appUrlforsStrs := data["purview_urlfors"].(map[string]interface{})
  330. appUrlfors := make(map[int64][]string)
  331. for appIdStr, urlforsStr := range appUrlforsStrs {
  332. appId, _ := strconv.Atoi(appIdStr)
  333. var urlfors []string
  334. json.Unmarshal([]byte(urlforsStr.(string)), &urlfors)
  335. appUrlfors[int64(appId)] = urlfors
  336. }
  337. return appUrlfors
  338. }
  339. // "org_subscibes": { (org_id: ServeSubscibe)
  340. // 11: {ServeSubscibe's json}
  341. // },
  342. func processOrgSubscibes(data map[string]interface{}) map[int64]*models.ServeSubscibe {
  343. subscibeJSONs := data["org_subscibes"].(map[string]interface{})
  344. subscibes := make(map[int64]*models.ServeSubscibe)
  345. for orgIDStr, subscibeJSON := range subscibeJSONs {
  346. orgID, _ := strconv.Atoi(orgIDStr)
  347. var subscibe models.ServeSubscibe
  348. json.Unmarshal([]byte(subscibeJSON.(string)), &subscibe)
  349. subscibes[int64(orgID)] = &subscibe
  350. }
  351. return subscibes
  352. }
  353. func ModifyPassword(adminID int64, password string) error {
  354. err := writeUserDb.Model(&models.AdminUser{}).Where("id = ? AND status = 1", adminID).Updates(map[string]interface{}{"password": password, "mtime": time.Now().Unix()}).Error
  355. return err
  356. }
  357. func GetPurviewById(ids string) ([]*models.Purview, error) {
  358. var originPurviews []*models.Purview
  359. getPurviewErr := readUserDb.Model(&models.Purview{}).Where(fmt.Sprintf("id in (%v) and status = 1", ids)).Order("listorder asc").Order("id asc").Find(&originPurviews).Error
  360. return originPurviews, getPurviewErr
  361. }
  362. func FindAdminUserIDA(id int64) (role models.App_Role, err error) {
  363. err = readUserDb.Model(&models.App_Role{}).Where("id = ?", id).First(&role).Error
  364. return
  365. }
  366. func GetSuperAdminUsersPurviewTreeAndUrlfors(appType int) ([]string, []*models.Purview, error) {
  367. originPurviews, getPurviewErr := getAllOriginPurviews(appType)
  368. if getPurviewErr != nil {
  369. return nil, nil, getPurviewErr
  370. }
  371. urlfors, processedPurviews := getUrlforsAndProcessPurviews2Tree(originPurviews)
  372. return urlfors, processedPurviews, nil
  373. }
  374. // 加工这些规则:树形化;以及从中取出不为空的 urlfor
  375. // 正确结果的前提是 originPurviews 以 parentid asc 排好序了的
  376. func getUrlforsAndProcessPurviews2Tree(originPurviews []*models.Purview) ([]string, []*models.Purview) {
  377. processedPurviews := make([]*models.Purview, 0)
  378. pid_childs := make(map[int][]*models.Purview)
  379. urlfors := make([]string, 0, len(originPurviews))
  380. for _, purview := range originPurviews {
  381. if len(purview.Urlfor) != 0 {
  382. urlfors = append(urlfors, purview.Urlfor)
  383. }
  384. // warning:下面这个算法只适用最多两层树形结构的菜单,对于两层以上的会丢失掉第三层及其以下的节点
  385. // 因为取出 originPurviews 的时候已经排过序了,所以顶级节点肯定最先处理,不需要担心子节点比父节点先处理
  386. if purview.Parentid == 0 {
  387. processedPurviews = append(processedPurviews, purview)
  388. } else {
  389. childs := pid_childs[int(purview.Parentid)]
  390. if pid_childs[int(purview.Parentid)] == nil {
  391. childs = make([]*models.Purview, 0)
  392. }
  393. childs = append(childs, purview)
  394. pid_childs[int(purview.Parentid)] = childs
  395. }
  396. }
  397. for _, proPurview := range processedPurviews {
  398. proPurview.Childs = pid_childs[int(proPurview.Id)]
  399. }
  400. return urlfors, processedPurviews
  401. }
  402. func getAllOriginPurviews(appType int) ([]*models.Purview, error) {
  403. var purviews []*models.Purview
  404. getPurviewErr := readUserDb.Model(models.Purview{}).Where("module = ? AND status = 1", appType).Order("listorder asc").Order("id asc").Find(&purviews).Error
  405. if getPurviewErr != nil {
  406. if getPurviewErr == gorm.ErrRecordNotFound {
  407. return nil, nil
  408. } else {
  409. return nil, getPurviewErr
  410. }
  411. }
  412. return purviews, nil
  413. }