yxh 6 лет назад
Родитель
Сommit
f90e2a79b4

+ 7 - 4
app/controller/admin/cms_menu.go

@@ -16,7 +16,7 @@ import (
 //cms栏目管理
 type CmsMenu struct{}
 
-func (c *CmsMenu) MenuList(r *ghttp.Request) {
+func (c *CmsMenu) List(r *ghttp.Request) {
 	var req *cms_category.ReqSearchList
 	//获取参数
 	if err := r.Parse(&req); err != nil {
@@ -28,6 +28,9 @@ func (c *CmsMenu) MenuList(r *ghttp.Request) {
 	if req != nil && req.Name != "" {
 		//按栏目名搜索
 		menus, err = cms_service.GetMenuListSearch(req)
+		if err != nil {
+			response.FailJson(true, r, err.Error())
+		}
 		list = gconv.Maps(menus)
 	} else {
 		//获取所有栏目
@@ -45,7 +48,7 @@ func (c *CmsMenu) MenuList(r *ghttp.Request) {
 }
 
 //添加栏目分类
-func (c *CmsMenu) MenuAdd(r *ghttp.Request) {
+func (c *CmsMenu) Add(r *ghttp.Request) {
 	if r.Method == "POST" {
 		var req *cms_category.ReqAdd
 		//获取参数
@@ -78,7 +81,7 @@ func (c *CmsMenu) MenuAdd(r *ghttp.Request) {
 }
 
 //修改栏目
-func (c *CmsMenu) MenuEdit(r *ghttp.Request) {
+func (c *CmsMenu) Edit(r *ghttp.Request) {
 	if r.Method == "POST" {
 		var req *cms_category.ReqEdit
 		//获取参数
@@ -122,7 +125,7 @@ func (c *CmsMenu) MenuEdit(r *ghttp.Request) {
 }
 
 //栏目排序
-func (c *CmsMenu) MenuSort(r *ghttp.Request) {
+func (c *CmsMenu) Sort(r *ghttp.Request) {
 	sorts := r.Get("sorts")
 	s := gconv.Map(sorts)
 	if s == nil {

+ 19 - 4
app/controller/admin/index.go

@@ -4,6 +4,7 @@ import (
 	"gfast/app/service/admin/auth_service"
 	"gfast/app/service/admin/user_service"
 	"gfast/library/response"
+	"gfast/library/utils"
 	"github.com/gogf/gf/frame/g"
 	"github.com/gogf/gf/net/ghttp"
 	"github.com/gogf/gf/util/gconv"
@@ -15,12 +16,22 @@ type Index struct{}
 //后台首页接口数据
 func (c *Index) Index(r *ghttp.Request) {
 	//获取用户信息
-	userInfo := user_service.GetLoginAdminInfo(r)
+	userEntity := user_service.GetLoginAdminInfo(r)
+	userInfo := gconv.Map(userEntity)
 	//菜单列表
 	var menuList g.List
+	isSuperAdmin := false
 	if userInfo != nil {
-		userId := gconv.Int(userInfo["id"])
+		userId := userEntity.Id
 		delete(userInfo, "user_password")
+		//获取无需验证权限的用户id
+		for _, v := range utils.NotCheckAuthAdminIds {
+			if v == userId {
+				isSuperAdmin = true
+				break
+			}
+		}
+
 		//获取用户角色信息
 		allRoles, err := auth_service.GetRoleList()
 		if err == nil {
@@ -34,7 +45,12 @@ func (c *Index) Index(r *ghttp.Request) {
 				}
 				userInfo["roles"] = strings.Join(name, ",")
 				//获取菜单信息
-				menuList, err = user_service.GetAdminMenusByRoleIds(roleIds)
+				if isSuperAdmin {
+					//超管获取所有菜单
+					menuList, err = user_service.GetAllMenus()
+				} else {
+					menuList, err = user_service.GetAdminMenusByRoleIds(roleIds)
+				}
 				if err != nil {
 					g.Log().Error(err)
 				}
@@ -46,7 +62,6 @@ func (c *Index) Index(r *ghttp.Request) {
 			g.Log().Error(err)
 			userInfo["roles"] = ""
 		}
-
 	}
 
 	result := g.Map{

+ 26 - 2
app/controller/admin/surveillance_online.go

@@ -1,7 +1,31 @@
 package admin
 
-type SurveillanceOnline struct{}
+import (
+	"gfast/app/model/admin/user_online"
+	"gfast/app/service/admin/surveillance_service"
+	"gfast/library/response"
+	"github.com/gogf/gf/frame/g"
+	"github.com/gogf/gf/net/ghttp"
+	"github.com/gogf/gf/util/gvalid"
+)
 
-func (c *SurveillanceOnline) List() {
+type SurveillanceOnline struct{}
 
+//用户状态列表
+func (c *SurveillanceOnline) List(r *ghttp.Request) {
+	var req *user_online.ReqListSearch
+	//获取参数
+	if err := r.Parse(&req); err != nil {
+		response.FailJson(true, r, err.(*gvalid.Error).FirstString())
+	}
+	total, page, list, err := surveillance_service.GetOnlineListPage(req)
+	if err != nil {
+		response.FailJson(true, r, err.Error())
+	}
+	result := g.Map{
+		"currentPage": page,
+		"total":       total,
+		"list":        list,
+	}
+	response.SusJson(true, r, "用户在线状态", result)
 }

+ 10 - 0
app/model/admin/user_online/user_online.go

@@ -0,0 +1,10 @@
+package user_online
+
+// Fill with you ideas below.
+//列表搜索参数
+type ReqListSearch struct {
+	Username string `p:"username"`
+	Ip       string `p:"ip"`
+	PageNum  int    `p:"page"`     //当前页码
+	PageSize int    `p:"pageSize"` //每页数
+}

+ 59 - 0
app/model/admin/user_online/user_online_entity.go

@@ -0,0 +1,59 @@
+// ==========================================================================
+// This is auto-generated by gf cli tool. You may not really want to edit it.
+// ==========================================================================
+
+package user_online
+
+import (
+	"database/sql"
+	"github.com/gogf/gf/database/gdb"
+)
+
+// Entity is the golang structure for table qxkj_user_online.
+type Entity struct {
+	Id         uint   `orm:"id,primary"   json:"id"`          //
+	Uuid       string `orm:"uuid"         json:"uuid"`        // 用户标识
+	Token      string `orm:"token,unique" json:"token"`       // 用户token
+	CreateTime uint64 `orm:"create_time"  json:"create_time"` // 登录时间
+	UserName   string `orm:"user_name"    json:"user_name"`   // 用户名
+	Ip         string `orm:"ip"           json:"ip"`          // 登录ip
+	Explorer   string `orm:"explorer"     json:"explorer"`    // 浏览器
+	Os         string `orm:"os"           json:"os"`          // 操作系统
+}
+
+// OmitEmpty sets OPTION_OMITEMPTY option for the model, which automatically filers
+// the data and where attributes for empty values.
+func (r *Entity) OmitEmpty() *arModel {
+	return Model.Data(r).OmitEmpty()
+}
+
+// Inserts does "INSERT...INTO..." statement for inserting current object into table.
+func (r *Entity) Insert() (result sql.Result, err error) {
+	return Model.Data(r).Insert()
+}
+
+// Replace does "REPLACE...INTO..." statement for inserting current object into table.
+// If there's already another same record in the table (it checks using primary key or unique index),
+// it deletes it and insert this one.
+func (r *Entity) Replace() (result sql.Result, err error) {
+	return Model.Data(r).Replace()
+}
+
+// Save does "INSERT...INTO..." statement for inserting/updating current object into table.
+// It updates the record if there's already another same record in the table
+// (it checks using primary key or unique index).
+func (r *Entity) Save() (result sql.Result, err error) {
+	return Model.Data(r).Save()
+}
+
+// Update does "UPDATE...WHERE..." statement for updating current object from table.
+// It updates the record if there's already another same record in the table
+// (it checks using primary key or unique index).
+func (r *Entity) Update() (result sql.Result, err error) {
+	return Model.Data(r).Where(gdb.GetWhereConditionOfStruct(r)).Update()
+}
+
+// Delete does "DELETE FROM...WHERE..." statement for deleting current object from table.
+func (r *Entity) Delete() (result sql.Result, err error) {
+	return Model.Where(gdb.GetWhereConditionOfStruct(r)).Delete()
+}

+ 367 - 0
app/model/admin/user_online/user_online_model.go

@@ -0,0 +1,367 @@
+// ==========================================================================
+// This is auto-generated by gf cli tool. You may not really want to edit it.
+// ==========================================================================
+
+package user_online
+
+import (
+	"database/sql"
+	"github.com/gogf/gf/database/gdb"
+	"github.com/gogf/gf/frame/g"
+	"time"
+)
+
+// arModel is a active record design model for table qxkj_user_online operations.
+type arModel struct {
+	M *gdb.Model
+}
+
+var (
+	// Table is the table name of qxkj_user_online.
+	Table = "qxkj_user_online"
+	// Model is the model object of qxkj_user_online.
+	Model = &arModel{g.DB("default").Table(Table).Safe()}
+)
+
+// FindOne is a convenience method for Model.FindOne.
+// See Model.FindOne.
+func FindOne(where ...interface{}) (*Entity, error) {
+	return Model.FindOne(where...)
+}
+
+// FindAll is a convenience method for Model.FindAll.
+// See Model.FindAll.
+func FindAll(where ...interface{}) ([]*Entity, error) {
+	return Model.FindAll(where...)
+}
+
+// FindValue is a convenience method for Model.FindValue.
+// See Model.FindValue.
+func FindValue(fieldsAndWhere ...interface{}) (gdb.Value, error) {
+	return Model.FindValue(fieldsAndWhere...)
+}
+
+// FindCount is a convenience method for Model.FindCount.
+// See Model.FindCount.
+func FindCount(where ...interface{}) (int, error) {
+	return Model.FindCount(where...)
+}
+
+// Insert is a convenience method for Model.Insert.
+func Insert(data ...interface{}) (result sql.Result, err error) {
+	return Model.Insert(data...)
+}
+
+// Replace is a convenience method for Model.Replace.
+func Replace(data ...interface{}) (result sql.Result, err error) {
+	return Model.Replace(data...)
+}
+
+// Save is a convenience method for Model.Save.
+func Save(data ...interface{}) (result sql.Result, err error) {
+	return Model.Save(data...)
+}
+
+// Update is a convenience method for Model.Update.
+func Update(dataAndWhere ...interface{}) (result sql.Result, err error) {
+	return Model.Update(dataAndWhere...)
+}
+
+// Delete is a convenience method for Model.Delete.
+func Delete(where ...interface{}) (result sql.Result, err error) {
+	return Model.Delete(where...)
+}
+
+// As sets an alias name for current table.
+func (m *arModel) As(as string) *arModel {
+	return &arModel{m.M.As(as)}
+}
+
+// TX sets the transaction for current operation.
+func (m *arModel) TX(tx *gdb.TX) *arModel {
+	return &arModel{m.M.TX(tx)}
+}
+
+// Master marks the following operation on master node.
+func (m *arModel) Master() *arModel {
+	return &arModel{m.M.Master()}
+}
+
+// Slave marks the following operation on slave node.
+// Note that it makes sense only if there's any slave node configured.
+func (m *arModel) Slave() *arModel {
+	return &arModel{m.M.Slave()}
+}
+
+// LeftJoin does "LEFT JOIN ... ON ..." statement on the model.
+func (m *arModel) LeftJoin(joinTable string, on string) *arModel {
+	return &arModel{m.M.LeftJoin(joinTable, on)}
+}
+
+// RightJoin does "RIGHT JOIN ... ON ..." statement on the model.
+func (m *arModel) RightJoin(joinTable string, on string) *arModel {
+	return &arModel{m.M.RightJoin(joinTable, on)}
+}
+
+// InnerJoin does "INNER JOIN ... ON ..." statement on the model.
+func (m *arModel) InnerJoin(joinTable string, on string) *arModel {
+	return &arModel{m.M.InnerJoin(joinTable, on)}
+}
+
+// Fields sets the operation fields of the model, multiple fields joined using char ','.
+func (m *arModel) Fields(fields string) *arModel {
+	return &arModel{m.M.Fields(fields)}
+}
+
+// FieldsEx sets the excluded operation fields of the model, multiple fields joined using char ','.
+func (m *arModel) FieldsEx(fields string) *arModel {
+	return &arModel{m.M.FieldsEx(fields)}
+}
+
+// Option sets the extra operation option for the model.
+func (m *arModel) Option(option int) *arModel {
+	return &arModel{m.M.Option(option)}
+}
+
+// OmitEmpty sets OPTION_OMITEMPTY option for the model, which automatically filers
+// the data and where attributes for empty values.
+func (m *arModel) OmitEmpty() *arModel {
+	return &arModel{m.M.OmitEmpty()}
+}
+
+// Filter marks filtering the fields which does not exist in the fields of the operated table.
+func (m *arModel) Filter() *arModel {
+	return &arModel{m.M.Filter()}
+}
+
+// Where sets the condition statement for the model. The parameter <where> can be type of
+// string/map/gmap/slice/struct/*struct, etc. Note that, if it's called more than one times,
+// multiple conditions will be joined into where statement using "AND".
+// Eg:
+// Where("uid=10000")
+// Where("uid", 10000)
+// Where("money>? AND name like ?", 99999, "vip_%")
+// Where("uid", 1).Where("name", "john")
+// Where("status IN (?)", g.Slice{1,2,3})
+// Where("age IN(?,?)", 18, 50)
+// Where(User{ Id : 1, UserName : "john"})
+func (m *arModel) Where(where interface{}, args ...interface{}) *arModel {
+	return &arModel{m.M.Where(where, args...)}
+}
+
+// And adds "AND" condition to the where statement.
+func (m *arModel) And(where interface{}, args ...interface{}) *arModel {
+	return &arModel{m.M.And(where, args...)}
+}
+
+// Or adds "OR" condition to the where statement.
+func (m *arModel) Or(where interface{}, args ...interface{}) *arModel {
+	return &arModel{m.M.Or(where, args...)}
+}
+
+// Group sets the "GROUP BY" statement for the model.
+func (m *arModel) Group(groupBy string) *arModel {
+	return &arModel{m.M.Group(groupBy)}
+}
+
+// Order sets the "ORDER BY" statement for the model.
+func (m *arModel) Order(orderBy string) *arModel {
+	return &arModel{m.M.Order(orderBy)}
+}
+
+// Limit sets the "LIMIT" statement for the model.
+// The parameter <limit> can be either one or two number, if passed two number is passed,
+// it then sets "LIMIT limit[0],limit[1]" statement for the model, or else it sets "LIMIT limit[0]"
+// statement.
+func (m *arModel) Limit(limit ...int) *arModel {
+	return &arModel{m.M.Limit(limit...)}
+}
+
+// Offset sets the "OFFSET" statement for the model.
+// It only makes sense for some databases like SQLServer, PostgreSQL, etc.
+func (m *arModel) Offset(offset int) *arModel {
+	return &arModel{m.M.Offset(offset)}
+}
+
+// Page sets the paging number for the model.
+// The parameter <page> is started from 1 for paging.
+// Note that, it differs that the Limit function start from 0 for "LIMIT" statement.
+func (m *arModel) Page(page, limit int) *arModel {
+	return &arModel{m.M.Page(page, limit)}
+}
+
+// Batch sets the batch operation number for the model.
+func (m *arModel) Batch(batch int) *arModel {
+	return &arModel{m.M.Batch(batch)}
+}
+
+// Cache sets the cache feature for the model. It caches the result of the sql, which means
+// if there's another same sql request, it just reads and returns the result from cache, it
+// but not committed and executed into the database.
+//
+// If the parameter <duration> < 0, which means it clear the cache with given <name>.
+// If the parameter <duration> = 0, which means it never expires.
+// If the parameter <duration> > 0, which means it expires after <duration>.
+//
+// The optional parameter <name> is used to bind a name to the cache, which means you can later
+// control the cache like changing the <duration> or clearing the cache with specified <name>.
+//
+// Note that, the cache feature is disabled if the model is operating on a transaction.
+func (m *arModel) Cache(expire time.Duration, name ...string) *arModel {
+	return &arModel{m.M.Cache(expire, name...)}
+}
+
+// Data sets the operation data for the model.
+// The parameter <data> can be type of string/map/gmap/slice/struct/*struct, etc.
+// Eg:
+// Data("uid=10000")
+// Data("uid", 10000)
+// Data(g.Map{"uid": 10000, "name":"john"})
+// Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})
+func (m *arModel) Data(data ...interface{}) *arModel {
+	return &arModel{m.M.Data(data...)}
+}
+
+// Insert does "INSERT INTO ..." statement for the model.
+// The optional parameter <data> is the same as the parameter of Model.Data function,
+// see Model.Data.
+func (m *arModel) Insert(data ...interface{}) (result sql.Result, err error) {
+	return m.M.Insert(data...)
+}
+
+// Replace does "REPLACE INTO ..." statement for the model.
+// The optional parameter <data> is the same as the parameter of Model.Data function,
+// see Model.Data.
+func (m *arModel) Replace(data ...interface{}) (result sql.Result, err error) {
+	return m.M.Replace(data...)
+}
+
+// Save does "INSERT INTO ... ON DUPLICATE KEY UPDATE..." statement for the model.
+// It updates the record if there's primary or unique index in the saving data,
+// or else it inserts a new record into the table.
+//
+// The optional parameter <data> is the same as the parameter of Model.Data function,
+// see Model.Data.
+func (m *arModel) Save(data ...interface{}) (result sql.Result, err error) {
+	return m.M.Save(data...)
+}
+
+// Update does "UPDATE ... " statement for the model.
+//
+// If the optional parameter <dataAndWhere> is given, the dataAndWhere[0] is the updated
+// data field, and dataAndWhere[1:] is treated as where condition fields.
+// Also see Model.Data and Model.Where functions.
+func (m *arModel) Update(dataAndWhere ...interface{}) (result sql.Result, err error) {
+	return m.M.Update(dataAndWhere...)
+}
+
+// Delete does "DELETE FROM ... " statement for the model.
+// The optional parameter <where> is the same as the parameter of Model.Where function,
+// see Model.Where.
+func (m *arModel) Delete(where ...interface{}) (result sql.Result, err error) {
+	return m.M.Delete(where...)
+}
+
+// Count does "SELECT COUNT(x) FROM ..." statement for the model.
+// The optional parameter <where> is the same as the parameter of Model.Where function,
+// see Model.Where.
+func (m *arModel) Count(where ...interface{}) (int, error) {
+	return m.M.Count(where...)
+}
+
+// All does "SELECT FROM ..." statement for the model.
+// It retrieves the records from table and returns the result as []*Entity.
+// It returns nil if there's no record retrieved with the given conditions from table.
+//
+// The optional parameter <where> is the same as the parameter of Model.Where function,
+// see Model.Where.
+func (m *arModel) All(where ...interface{}) ([]*Entity, error) {
+	all, err := m.M.All(where...)
+	if err != nil {
+		return nil, err
+	}
+	var entities []*Entity
+	if err = all.Structs(&entities); err != nil && err != sql.ErrNoRows {
+		return nil, err
+	}
+	return entities, nil
+}
+
+// One retrieves one record from table and returns the result as *Entity.
+// It returns nil if there's no record retrieved with the given conditions from table.
+//
+// The optional parameter <where> is the same as the parameter of Model.Where function,
+// see Model.Where.
+func (m *arModel) One(where ...interface{}) (*Entity, error) {
+	one, err := m.M.One(where...)
+	if err != nil {
+		return nil, err
+	}
+	var entity *Entity
+	if err = one.Struct(&entity); err != nil && err != sql.ErrNoRows {
+		return nil, err
+	}
+	return entity, nil
+}
+
+// Value retrieves a specified record value from table and returns the result as interface type.
+// It returns nil if there's no record found with the given conditions from table.
+//
+// If the optional parameter <fieldsAndWhere> is given, the fieldsAndWhere[0] is the selected fields
+// and fieldsAndWhere[1:] is treated as where condition fields.
+// Also see Model.Fields and Model.Where functions.
+func (m *arModel) Value(fieldsAndWhere ...interface{}) (gdb.Value, error) {
+	return m.M.Value(fieldsAndWhere...)
+}
+
+// FindOne retrieves and returns a single Record by Model.WherePri and Model.One.
+// Also see Model.WherePri and Model.One.
+func (m *arModel) FindOne(where ...interface{}) (*Entity, error) {
+	one, err := m.M.FindOne(where...)
+	if err != nil {
+		return nil, err
+	}
+	var entity *Entity
+	if err = one.Struct(&entity); err != nil && err != sql.ErrNoRows {
+		return nil, err
+	}
+	return entity, nil
+}
+
+// FindAll retrieves and returns Result by by Model.WherePri and Model.All.
+// Also see Model.WherePri and Model.All.
+func (m *arModel) FindAll(where ...interface{}) ([]*Entity, error) {
+	all, err := m.M.FindAll(where...)
+	if err != nil {
+		return nil, err
+	}
+	var entities []*Entity
+	if err = all.Structs(&entities); err != nil && err != sql.ErrNoRows {
+		return nil, err
+	}
+	return entities, nil
+}
+
+// FindValue retrieves and returns single field value by Model.WherePri and Model.Value.
+// Also see Model.WherePri and Model.Value.
+func (m *arModel) FindValue(fieldsAndWhere ...interface{}) (gdb.Value, error) {
+	return m.M.FindValue(fieldsAndWhere...)
+}
+
+// FindCount retrieves and returns the record number by Model.WherePri and Model.Count.
+// Also see Model.WherePri and Model.Count.
+func (m *arModel) FindCount(where ...interface{}) (int, error) {
+	return m.M.FindCount(where...)
+}
+
+// Chunk iterates the table with given size and callback function.
+func (m *arModel) Chunk(limit int, callback func(entities []*Entity, err error) bool) {
+	m.M.Chunk(limit, func(result gdb.Result, err error) bool {
+		var entities []*Entity
+		err = result.Structs(&entities)
+		if err == sql.ErrNoRows {
+			return false
+		}
+		return callback(entities, err)
+	})
+}

+ 91 - 0
app/service/admin/surveillance_service/online.go

@@ -0,0 +1,91 @@
+package surveillance_service
+
+import (
+	"gfast/app/model/admin/user_online"
+	"gfast/boot"
+	"gfast/library/utils"
+	"github.com/goflyfox/gtoken/gtoken"
+	"github.com/gogf/gf/encoding/gjson"
+	"github.com/gogf/gf/errors/gerror"
+	"github.com/gogf/gf/frame/g"
+	"github.com/gogf/gf/os/gcache"
+	"github.com/gogf/gf/util/gconv"
+)
+
+//获取在线用户列表
+func GetOnlineListPage(req *user_online.ReqListSearch) (total, page int, list []*user_online.Entity, err error) {
+	model := user_online.Model
+	if req != nil {
+		if req.Ip != "" {
+			model = model.Where("ip like ?", "%"+req.Ip+"%")
+		}
+		if req.Username != "" {
+			model = model.Where("username like ?", "%"+req.Username+"%")
+		}
+	}
+	total, err = model.Count()
+	if err != nil {
+		g.Log().Error(err)
+		err = gerror.New("获取总行数失败")
+		return
+	}
+	if req.PageNum == 0 {
+		req.PageNum = 1
+	}
+	page = req.PageNum
+	if req.PageSize == 0 {
+		req.PageSize = utils.AdminPageNum
+	}
+	list, err = model.FieldsEx("token").Page(page, req.PageSize).Order("create_time DESC").All()
+	if err != nil {
+		g.Log().Error(err)
+		err = gerror.New("获取数据失败")
+		return
+	}
+	return
+}
+
+//通过token获取登录用户数据
+func GetOnlineInfo(token string) g.Map {
+	uuid, userKey := GetUuidUserKeyByToken(token)
+	cacheKey := boot.AdminGfToken.CacheKey + userKey
+	switch boot.AdminGfToken.CacheMode {
+	case gtoken.CacheModeCache:
+		userCacheValue := gcache.Get(cacheKey)
+		if userCacheValue == nil {
+			return nil
+		}
+		return gconv.Map(userCacheValue)
+	case gtoken.CacheModeRedis:
+		var userCache g.Map
+		userCacheJson, err := g.Redis().Do("GET", cacheKey)
+		if err != nil {
+			g.Log().Error("[GToken]cache get error", err)
+			return nil
+		}
+		if userCacheJson == nil {
+			return nil
+		}
+		err = gjson.DecodeTo(userCacheJson, &userCache)
+		if err != nil {
+			g.Log().Error("[GToken]cache get json error", err)
+			return nil
+		}
+		if uuid != userCache["uuid"] {
+			return nil
+		}
+		return userCache
+	}
+	return nil
+}
+
+//通过token获取uuid和userKey
+func GetUuidUserKeyByToken(token string) (uuid, userKey string) {
+	decryptToken := boot.AdminGfToken.DecryptToken(token)
+	if !decryptToken.Success() {
+		return
+	}
+	userKey = decryptToken.GetString("userKey")
+	uuid = decryptToken.GetString("uuid")
+	return
+}

+ 21 - 4
app/service/admin/user_service/user.go

@@ -18,15 +18,15 @@ import (
 func GetLoginID(r *ghttp.Request) (userId int) {
 	userInfo := GetLoginAdminInfo(r)
 	if userInfo != nil {
-		userId = gconv.Int(userInfo["id"])
+		userId = userInfo.Id
 	}
 	return
 }
 
 //获取缓存的用户信息
-func GetLoginAdminInfo(r *ghttp.Request) (userInfo g.Map) {
+func GetLoginAdminInfo(r *ghttp.Request) (userInfo *user.Entity) {
 	resp := boot.AdminGfToken.GetTokenData(r)
-	userInfo = gconv.Map(resp.Get("data"))
+	gconv.Struct(resp.Get("data"), &userInfo)
 	return
 }
 
@@ -96,6 +96,23 @@ func GetAdminInfoById(id int64) (userMap g.Map) {
 	return
 }
 
+//获取菜单
+func GetAllMenus() (menus g.List, err error) {
+	//获取所有开启的菜单
+	allMenus, err := auth_service.GetIsMenuStatusList()
+	if err != nil {
+		return
+	}
+	menus = make(g.List, len(allMenus))
+	for k, v := range allMenus {
+		menu := gconv.Map(v)
+		menu["index"] = v.Name
+		menus[k] = menu
+	}
+	menus = utils.PushSonToParent(menus, 0, "pid", "id", "subs", "", nil, false)
+	return
+}
+
 //获取管理员所属角色菜单
 func GetAdminMenusByRoleIds(roleIds []int) (menus g.List, err error) {
 	//获取角色对应的菜单id
@@ -118,7 +135,7 @@ func GetAdminMenusByRoleIds(roleIds []int) (menus g.List, err error) {
 	if err != nil {
 		return
 	}
-	roleMenus := make(g.List, 0, 100)
+	roleMenus := make(g.List, 0, len(allMenus))
 	for _, v := range allMenus {
 		if _, ok := menuIds[gconv.Int64(v.Id)]; gstr.Equal(v.Condition, "nocheck") || ok {
 			roleMenu := gconv.Map(v)

+ 1 - 0
boot/boot.go

@@ -41,6 +41,7 @@ func initAdminGfToken() {
 		MultiLogin:       utils.AdminMultiLogin,
 		LoginPath:        "/sysLogin/login",
 		LoginBeforeFunc:  utils.AdminLogin,
+		LoginAfterFunc:   utils.AdminLoginAfter,
 		LogoutPath:       "/sysLogin/logout",
 		AuthPaths:        g.SliceStr{"/system/*"},
 		AuthAfterFunc:    utils.AuthAfterFunc,

Разница между файлами не показана из-за своего большого размера
+ 0 - 0
data/db.sql


+ 1 - 0
go.mod

@@ -5,6 +5,7 @@ require (
 	github.com/goflyfox/gtoken v1.3.11
 	github.com/gogf/gf v1.11.5
 	github.com/mojocn/base64Captcha v1.3.0
+    github.com/mssola/user_agent v0.5.1
 )
 
 go 1.14

+ 50 - 2
library/utils/function.go

@@ -4,6 +4,7 @@ import (
 	"database/sql"
 	"errors"
 	"gfast/app/model/admin/user"
+	"gfast/app/model/admin/user_online"
 	"gfast/library/response"
 	"github.com/goflyfox/gtoken/gtoken"
 	"github.com/gogf/gf/crypto/gaes"
@@ -15,6 +16,8 @@ import (
 	"github.com/gogf/gf/util/gconv"
 	"github.com/gogf/gf/util/gvalid"
 	"github.com/mojocn/base64Captcha"
+	"github.com/mssola/user_agent"
+	"strings"
 )
 
 const AdminCbcPublicKey = "HqmP1KLMuz09Q0Bu"
@@ -82,9 +85,9 @@ func AdminLogin(r *ghttp.Request) (string, interface{}) {
 		response.JsonExit(r, response.ErrorCode, e.String())
 	}
 	//判断验证码是否正确
-	if !VerifyString(data["idKeyC"], data["idValueC"]) {
+	/*if !VerifyString(data["idKeyC"], data["idValueC"]) {
 		response.JsonExit(r, response.ErrorCode, "验证码输入错误")
-	}
+	}*/
 	password := EncryptCBC(data["password"], AdminCbcPublicKey)
 	var keys string
 	if AdminMultiLogin {
@@ -95,11 +98,42 @@ func AdminLogin(r *ghttp.Request) (string, interface{}) {
 	if err, user := signIn(data["username"], password, r); err != nil {
 		response.JsonExit(r, response.ErrorCode, err.Error())
 	} else {
+		r.SetParam("userInfo", user)
 		return keys, user
 	}
 	return keys, nil
 }
 
+// 后台登录返回方法
+func AdminLoginAfter(r *ghttp.Request, respData gtoken.Resp) {
+	if !respData.Success() {
+		r.Response.WriteJson(respData)
+	} else {
+		token := respData.GetString("token")
+		uuid := respData.GetString("uuid")
+		var userInfo *user.Entity
+		r.GetParamVar("userInfo").Struct(&userInfo)
+		//保存用户在线状态token到数据库
+		userAgent := r.Header.Get("User-Agent")
+		ua := user_agent.New(userAgent)
+		os := ua.OS()
+		explorer, _ := ua.Browser()
+		entity := user_online.Entity{
+			Uuid:       uuid,
+			Token:      token,
+			CreateTime: gconv.Uint64(gtime.Timestamp()),
+			UserName:   userInfo.UserName,
+			Ip:         r.GetClientIp(),
+			Explorer:   explorer,
+			Os:         os,
+		}
+		entity.Save()
+		r.Response.WriteJson(gtoken.Succ(g.Map{
+			"token": token,
+		}))
+	}
+}
+
 //gtoken验证后返回
 func AuthAfterFunc(r *ghttp.Request, respData gtoken.Resp) {
 	if r.Method == "OPTIONS" || respData.Success() {
@@ -116,6 +150,20 @@ func AuthAfterFunc(r *ghttp.Request, respData gtoken.Resp) {
 
 //后台退出登陆
 func AdminLoginOut(r *ghttp.Request) bool {
+	//删除在线用户状态
+	authHeader := r.Header.Get("Authorization")
+	if authHeader != "" {
+		parts := strings.SplitN(authHeader, " ", 2)
+		if len(parts) == 2 && parts[0] == "Bearer" && parts[1] != "" {
+			//删除在线用户状态操作
+			user_online.Model.Delete("token", parts[1])
+		}
+	}
+	authHeader = r.GetString("token")
+	if authHeader != "" {
+		//删除在线用户状态操作
+		user_online.Model.Delete("token", authHeader)
+	}
 	return true
 }
 

+ 17 - 5
test/demo2_test.go

@@ -1,8 +1,9 @@
 package test
 
 import (
-	"fmt"
-	"github.com/gogf/gf/util/grand"
+	"github.com/gogf/gf/frame/g"
+	"github.com/gogf/gf/net/ghttp"
+	"github.com/gogf/gf/os/glog"
 	"testing"
 )
 
@@ -11,7 +12,18 @@ func TestDemo2(t *testing.T) {
 }
 
 func test21(t *testing.T) {
-	for i := 0; i < 10; i++ {
-		fmt.Println(grand.Letters(10))
-	}
+	// 基本事件回调使用
+	p := "/:name/info/{uid}"
+	s := g.Server()
+	s.BindHookHandlerByMap(p, map[string]ghttp.HandlerFunc{
+		ghttp.HOOK_BEFORE_SERVE:  func(r *ghttp.Request) { glog.Println(ghttp.HOOK_BEFORE_SERVE) },
+		ghttp.HOOK_AFTER_SERVE:   func(r *ghttp.Request) { glog.Println(ghttp.HOOK_AFTER_SERVE) },
+		ghttp.HOOK_BEFORE_OUTPUT: func(r *ghttp.Request) { glog.Println(ghttp.HOOK_BEFORE_OUTPUT) },
+		ghttp.HOOK_AFTER_OUTPUT:  func(r *ghttp.Request) { glog.Println(ghttp.HOOK_AFTER_OUTPUT) },
+	})
+	s.BindHandler(p, func(r *ghttp.Request) {
+		r.Response.Write("用户:", r.Get("name"), ", uid:", r.Get("uid"))
+	})
+	s.SetPort(8299)
+	s.Run()
 }

Некоторые файлы не были показаны из-за большого количества измененных файлов