123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305 |
- package mobile_api_controllers
-
- import (
- "XT_New/controllers"
- "XT_New/enums"
- "XT_New/models"
- "XT_New/service"
- "bytes"
- "encoding/json"
- "fmt"
- "log"
- "os"
- "path"
- "regexp"
- "runtime"
- "strconv"
- "strings"
- "time"
- )
-
- type MobileBaseAPIController struct {
- controllers.BaseAPIController
- }
-
- func (this *MobileBaseAPIController) Prepare() {
- this.BaseAPIController.Prepare()
-
- // beego.Trace("============================================================")
- // beego.Trace("session ID: %v", this.Ctx.Input.Cookie("beegosessionID"))
- // beego.Trace("session : %v", this.GetSession("info"))
- // this.SetSession("info", time.Now().Format("2006/01/02 15:04:05"))
- // beego.Trace("============================================================")
- }
-
- //
-
- func (this *MobileBaseAPIController) GetMobileAdminUserInfo() *MobileAdminUserInfo {
- userInfo := this.GetSession("mobile_admin_user_info")
- if userInfo == nil {
- return nil
- } else {
- return userInfo.(*MobileAdminUserInfo)
- }
- }
-
- type MobileAdminUserInfo struct {
- AdminUser *models.AdminUser
- Org *models.Org
- App *models.OrgApp
- AppRole *models.App_Role
- Subscibe *models.ServeSubscibe
- TemplateInfo *models.GobalTemplate
- }
-
- type MobileBaseAPIAuthController struct {
- MobileBaseAPIController
- }
-
- func (this *MobileBaseAPIAuthController) Prepare() {
- token := this.Ctx.GetCookie("token_cookie")
- logout_cookie := this.Ctx.GetCookie("logout_cookie")
-
- //if len(token) == 0{
- // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeNotLogin)
- // this.StopRun()
- //}
- this.MobileBaseAPIController.Prepare()
- adminUserInfo := this.GetMobileAdminUserInfo()
-
- if len(token) == 0 {
- this.DelSession("mobile_admin_user_info")
- // fmt.Println(logout_cookie)
- if len(logout_cookie) == 1 {
- this.Ctx.SetCookie("logout_cookie", "2")
- this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeLogOut)
- this.StopRun()
- } else {
-
- this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeLoginTimeout)
- this.StopRun()
- }
-
- } else {
- if adminUserInfo == nil {
- this.DelSession("mobile_admin_user_info")
- this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeNotLogin)
- this.StopRun()
- }
- }
-
- //if this.Ctx.Request.Method != "GET" {
- // err := service.GetOrgSubscibeState(adminUserInfo.Subscibe)
- // if err != nil || adminUserInfo.Subscibe.State == 3 {
- // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeNotSubscibe)
- // this.StopRun()
- // }
- //}
-
- if adminUserInfo.AppRole != nil {
- if adminUserInfo.AppRole.Id > 0 {
- app_role, _ := service.FindAppRoleById(adminUserInfo.AppRole.Id)
- if app_role != nil {
- if app_role.Status != 1 {
- this.DelSession("mobile_admin_user_info")
- this.Ctx.SetCookie("token_cookie", "")
- this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeForbidden)
- this.StopRun()
- }
- }
- }
-
- }
-
- if this.Ctx.Request.Header.Get("Permission") == "1" {
- if adminUserInfo.AdminUser.Id != adminUserInfo.Org.Creator { //超级管理员不受此限制
- err_msgs := LoadErrMsgConfig("./err_msg.json").Msgs
-
- isPermission := false
- adminUserInfo := this.GetMobileAdminUserInfo()
- //该机构下该用户有多少个
- redisClient := service.RedisClient()
- defer redisClient.Close()
- key2 := strconv.FormatInt(adminUserInfo.Org.Id, 10) + "_" + strconv.FormatInt(adminUserInfo.AdminUser.Id, 10) + "_role_ids"
- result, _ := redisClient.Get(key2).Result()
- var role models.App_Role
- var roles []string
- if len(result) == 0 {
- //该机构下该用户有多少个
- role, _ = service.GetUserAllRole(adminUserInfo.Org.Id, adminUserInfo.AdminUser.Id)
- redisClient.Set(key2, role, time.Second*60*60*18)
- if len(role.RoleIds) > 0 { //该用户没有设置角色
- roles = strings.Split(role.RoleIds, ",")
- }
- } else {
- json.Unmarshal([]byte(result), &role)
- if len(role.RoleIds) > 0 { //该用户没有设置角色
- roles = strings.Split(role.RoleIds, ",")
- }
- }
- //redis相关处理逻辑
- redis := service.RedisClient()
- defer redis.Close()
-
- //redis key值
- key := "purviews_" + strconv.FormatInt(adminUserInfo.Org.Id, 10) + strconv.FormatInt(adminUserInfo.AdminUser.Id, 10)
- purviews_json_str, _ := redis.Get(key).Result()
- //获取该用户下所有角色的权限总集
- var userRolePurviews string
- var userRolePurviewsArr []string
-
- fmt.Println("----redis 开始----")
- fmt.Println(purviews_json_str)
- fmt.Println("----redis 结束----")
-
- if len(purviews_json_str) == 0 {
- for _, item := range roles {
- role_id, _ := strconv.ParseInt(item, 10, 64)
- purviews, _ := service.GetRoleFuncPurviewIds(role_id)
- if len(userRolePurviews) == 0 {
- userRolePurviews = purviews
- } else {
- userRolePurviews = userRolePurviews + "," + purviews
- }
- }
- //该用户所拥有角色的权限的总集
- userRolePurviewsArr = RemoveRepeatedPurviewElement(strings.Split(userRolePurviews, ","))
- //缓存数据
- purview_json, err := json.Marshal(userRolePurviewsArr)
- if err == nil {
- redis.Set(key, purview_json, time.Minute*60*60*24)
- }
- } else {
- var dat []string
- if err := json.Unmarshal([]byte(purviews_json_str), &dat); err == nil {
-
- } else {
-
- }
- userRolePurviewsArr = dat
- }
-
- // fmt.Println(userRolePurviewsArr)
-
- //系统所记录的权限列表
- allPermission, _ := service.GetAllFunctionPurview()
- for _, item := range allPermission {
- //判断当前路由是否在权限路由列表里面
- if strings.Split(item.Urlfor, ",")[0] == strings.Split(this.Ctx.Request.RequestURI, "?")[0]+"?"+"mode="+this.GetString("mode") {
-
- //获取该角色的所有权限
- for _, items := range userRolePurviewsArr {
- id, _ := strconv.ParseInt(items, 10, 64)
-
- if id == item.ID {
- isPermission = true
- }
- }
- if !isPermission {
- //msg, _ := service.FindErrorMsgByStr(strings.Split(this.Ctx.Request.RequestURI, "?")[0] + "?" + "mode=" + this.GetString("mode"))
- var msg string
- for _, item := range err_msgs {
- if strings.Index(item.Url, strings.Split(this.Ctx.Request.RequestURI, "?")[0]+"?"+"mode="+this.GetString("mode")) != -1 {
- msg = item.ErrMsg
- }
- }
-
- json := make(map[string]interface{})
- json["msg"] = msg
- json["code"] = 0
- json["state"] = 0
- this.Data["json"] = json
- this.ServeJSON()
- this.StopRun()
- }
- }
- }
- }
- }
-
- }
-
- func RemoveRepeatedPurviewElement(arr []string) (newArr []string) {
- newArr = make([]string, 0)
- for i := 0; i < len(arr); i++ {
- repeat := false
- for j := i + 1; j < len(arr); j++ {
- if arr[i] == arr[j] {
- repeat = true
- break
- }
- }
- if !repeat {
- newArr = append(newArr, arr[i])
- }
- }
- return
- }
-
- type AdminUserInfo struct {
- AdminUser *models.AdminUser `json:"user"`
- CurrentOrgId int64 `json:"current_org_id"`
- CurrentAppId int64 `json:"current_app_id"`
- OrgIds []int64 `json:"org_ids"`
- Orgs map[int64]*models.Org `json:"orgs"`
- OrgAppIds map[int64][]int64 `json:"org_app_ids"`
- OrgApps map[int64](map[int64]*models.OrgApp) `json:"org_apps"`
- App2OrgIds map[int64]int64 `json:"app_to_org_ids"`
- AppRoles map[int64]*models.App_Role `json:"app_roles"`
- AppPurviews map[int64][]*models.Purview `json:"app_purviews"`
- AppUrlfors map[int64][]string `json:"app_urlfors"`
- Subscibes map[int64]*models.ServeSubscibe `json:"org_subscibes"`
- }
-
- type ErrMsgConfig struct {
- Msgs []*models.ErrMsg "json:msg"
- }
-
- func LoadErrMsgConfig(dataFile string) *ErrMsgConfig {
- var config ErrMsgConfig
- _, filename, _, _ := runtime.Caller(1)
- datapath := path.Join(path.Dir(filename), dataFile)
- config_file, err := os.Open(datapath)
- if err != nil {
- emit("Failed to open config file '%s': %s\n", datapath, err)
- return &config
- }
- fi, _ := config_file.Stat()
- buffer := make([]byte, fi.Size())
- _, err = config_file.Read(buffer)
- buffer, err = StripComments(buffer) //去掉注释
- if err != nil {
- emit("Failed to strip comments from json: %s\n", err)
- return &config
- }
- buffer = []byte(os.ExpandEnv(string(buffer))) //特殊
- err = json.Unmarshal(buffer, &config) //解析json格式数据
- if err != nil {
- emit("Failed unmarshalling json: %s\n", err)
- return &config
- }
- return &config
- }
-
- func emit(msgfmt string, args ...interface{}) {
- log.Printf(msgfmt, args...)
- }
-
- func StripComments(data []byte) ([]byte, error) {
- data = bytes.Replace(data, []byte("\r"), []byte(""), 0) // Windows
- lines := bytes.Split(data, []byte("\n")) //split to muli lines
- filtered := make([][]byte, 0)
-
- for _, line := range lines {
- match, err := regexp.Match(`^\s*#`, line)
- if err != nil {
- return nil, err
- }
- if !match {
- filtered = append(filtered, line)
- }
- }
-
- return bytes.Join(filtered, []byte("\n")), nil
- }
|