verify_login_token_service.go 13KB

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