路由架构修改,定时任务修复

This commit is contained in:
yxh
2020-08-07 12:13:39 +08:00
parent 913184f09e
commit 7c85e49905
20 changed files with 831 additions and 229 deletions
+4 -3
View File
@@ -84,7 +84,8 @@ go run main.go 直接访问http://localhost:8200
</tr>
</table>
##交流QQ群
QQ群二维码 <img src="https://gitee.com/tiger1103/gfast/raw/master/public/qqcode.png"/>
## 交流QQ群
快来加入群聊【Gfast框架交流群】(群号865697297),发现精彩内容。
> <img src="https://gitee.com/tiger1103/gfast/raw/master/public/qqcode.png"/>
> 快来加入群聊【Gfast框架交流群】(群号865697297),发现精彩内容。
+50
View File
@@ -0,0 +1,50 @@
package admin
import (
"gfast/app/model/admin/web_set"
"gfast/app/service/admin/web_set_service"
"gfast/library/response"
"github.com/gogf/gf/encoding/gjson"
"github.com/gogf/gf/errors/gerror"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/net/ghttp"
"github.com/gogf/gf/util/gvalid"
)
type WebSet struct{}
func (c *WebSet) Update(r *ghttp.Request) {
if r.Method == "POST" {
var req *web_set.UpdateReq
err := r.Parse(&req)
if err != nil {
response.FailJson(true, r, err.(*gvalid.Error).FirstString())
}
err = web_set_service.UpdateSave(req)
if err != nil {
response.FailJson(true, r, err.Error())
}
response.SusJson(true, r, "更新成功!")
}
// 不是post提交的请求就到修改页面后查询出要修改的记录
id := r.GetInt("webId")
params, err := web_set_service.GetInfoByID(id)
if err != nil {
response.FailJson(true, r, err.Error())
}
response.SusJson(true, r, "ok", params)
}
// 查询站点信息
func (c *WebSet) GetInfo(r *ghttp.Request) {
res, err := web_set.Model.FindOne()
if err != nil {
g.Log().Error(err)
err = gerror.New("查询站点信息失败!")
response.FailJson(true, r, err.Error())
}
response.SusJson(true, r, "站点信息", g.Map{
"web_id": res.WebId,
"web_content": gjson.New(res.WebContent),
})
}
@@ -1,4 +1,4 @@
package admin
package common
import (
"gfast/library/response"
@@ -7,7 +7,7 @@ import (
"github.com/gogf/gf/net/ghttp"
)
type Public struct{}
type Captcha struct{}
// @Summary 获取验证码图片信息
// @Description 获取验证码图片信息
@@ -15,7 +15,7 @@ type Public struct{}
// @Success 0 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /system/public/verify [post]
// @Security
func (p *Public) Verify(r *ghttp.Request) {
func (p *Captcha) Img(r *ghttp.Request) {
idKeyC, base64stringC := service.GetVerifyImgString()
response.SusJson(true, r, "ok", g.MapStrStr{"idKeyC": idKeyC, "base64stringC": base64stringC})
}
+2 -2
View File
@@ -180,7 +180,7 @@ func JobStart(job *Entity) error {
rs := gcron.Search(job.InvokeTarget)
if rs == nil {
if job.MisfirePolicy == 1 {
task, err := gcron.Add(job.CronExpression, f.Run, job.InvokeTarget)
task, err := gcron.AddSingleton(job.CronExpression, f.Run, job.InvokeTarget)
if err != nil || task == nil {
return err
}
@@ -208,7 +208,7 @@ func JobStop(job *Entity) error {
}
rs := gcron.Search(job.InvokeTarget)
if rs != nil {
gcron.Stop(job.InvokeTarget)
gcron.Remove(job.InvokeTarget)
}
job.Status = 1
job.Update()
@@ -20,6 +20,7 @@ type Entity struct {
Status int `orm:"status" json:"status"` // 登录状态(0成功 1失败)
Msg string `orm:"msg" json:"msg"` // 提示消息
LoginTime int64 `orm:"login_time" json:"login_time"` // 访问时间
Module string `orm:"module" json:"module"` //登录模块
}
// OmitEmpty sets OPTION_OMITEMPTY option for the model, which automatically filers
+5 -2
View File
@@ -15,7 +15,7 @@ type ReqListSearch struct {
}
//获取在线用户列表
func GetOnlineListPage(req *ReqListSearch) (total, page int, list []*Entity, err error) {
func GetOnlineListPage(req *ReqListSearch, hasToken bool) (total, page int, list []*Entity, err error) {
page = req.PageNum
model := Model
if req.Ip != "" {
@@ -30,8 +30,11 @@ func GetOnlineListPage(req *ReqListSearch) (total, page int, list []*Entity, err
err = gerror.New("获取总行数失败")
return
}
if !hasToken {
list, err = model.FieldsEx("token").Page(page, req.PageSize).Order("create_time DESC").All()
} else {
list, err = model.Page(page, req.PageSize).Order("create_time DESC").All()
}
if err != nil {
g.Log().Error(err)
err = gerror.New("获取数据失败")
+40
View File
@@ -0,0 +1,40 @@
package web_set
import (
"github.com/gogf/gf/errors/gerror"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/util/gconv"
)
// updateReq 用于存储页面更新(新增、修改)网址的信息
type UpdateReq struct {
WebContent g.Map `p:"webContent" v:"required#站点信息不能为空"` // 站点信息
}
// 更新站点信息
func UpdateSave(req *UpdateReq) error {
var entity = Entity{
WebId: gconv.Int(req.WebContent["webId"]),
WebContent: gconv.String(req.WebContent),
}
_, err := entity.Replace()
if err != nil {
g.Log().Error(err)
return gerror.New("更新站点信息失败")
}
return nil
}
// GetInfoByID 根据ID查询站点信息
func GetInfoByID(id int) (*Entity, error) {
entity, err := Model.FindOne("web_id", id)
if err != nil {
g.Log().Error(err)
return nil, gerror.New("根据ID查询站点信息出错")
}
if entity == nil {
return nil, gerror.New("根据ID未能查询到站点信息")
}
return entity, nil
}
+58
View File
@@ -0,0 +1,58 @@
// ==========================================================================
// This is auto-generated by gf cli tool. You may not really want to edit it.
// ==========================================================================
package web_set
import (
"database/sql"
"github.com/gogf/gf/database/gdb"
)
// Entity is the golang structure for table web_set.
type Entity struct {
WebId int `orm:"web_id,primary" json:"web_id"` // 主键
WebContent string `orm:"web_content" json:"web_content"` // 站点信息
}
// 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()
}
// InsertIgnore does "INSERT IGNORE INTO ..." statement for inserting current object into table.
func (r *Entity) InsertIgnore() (result sql.Result, err error) {
return Model.Data(r).InsertIgnore()
}
// 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()
}
+345
View File
@@ -0,0 +1,345 @@
// ==========================================================================
// This is auto-generated by gf cli tool. You may not really want to edit it.
// ==========================================================================
package web_set
import (
"database/sql"
"github.com/gogf/gf/database/gdb"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/frame/gmvc"
"time"
)
// arModel is a active record design model for table web_set operations.
type arModel struct {
gmvc.M
}
var (
// Table is the table name of web_set.
Table = "web_set"
// Model is the model object of web_set.
Model = &arModel{g.DB("default").Table(Table).Safe()}
// Columns defines and stores column names for table web_set.
Columns = struct {
WebId string // 主键
WebContent string // 站点信息
}{
WebId: "web_id",
WebContent: "web_content",
}
)
// 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...)
}
// FindArray is a convenience method for Model.FindArray.
// See Model.FindArray.
func FindArray(fieldsAndWhere ...interface{}) ([]gdb.Value, error) {
return Model.FindArray(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...)
}
// InsertIgnore is a convenience method for Model.InsertIgnore.
func InsertIgnore(data ...interface{}) (result sql.Result, err error) {
return Model.InsertIgnore(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.
// The parameter <table> can be joined table and its joined condition,
// and also with its alias name, like:
// Table("user").LeftJoin("user_detail", "user_detail.uid=user.uid")
// Table("user", "u").LeftJoin("user_detail", "ud", "ud.uid=u.uid")
func (m *arModel) LeftJoin(table ...string) *arModel {
return &arModel{m.M.LeftJoin(table...)}
}
// RightJoin does "RIGHT JOIN ... ON ..." statement on the model.
// The parameter <table> can be joined table and its joined condition,
// and also with its alias name, like:
// Table("user").RightJoin("user_detail", "user_detail.uid=user.uid")
// Table("user", "u").RightJoin("user_detail", "ud", "ud.uid=u.uid")
func (m *arModel) RightJoin(table ...string) *arModel {
return &arModel{m.M.RightJoin(table...)}
}
// InnerJoin does "INNER JOIN ... ON ..." statement on the model.
// The parameter <table> can be joined table and its joined condition,
// and also with its alias name, like:
// Table("user").InnerJoin("user_detail", "user_detail.uid=user.uid")
// Table("user", "u").InnerJoin("user_detail", "ud", "ud.uid=u.uid")
func (m *arModel) InnerJoin(table ...string) *arModel {
return &arModel{m.M.InnerJoin(table...)}
}
// 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(duration time.Duration, name ...string) *arModel {
return &arModel{m.M.Cache(duration, 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...)}
}
// 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
}
// 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
}
// 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)
})
}
// LockUpdate sets the lock for update for current operation.
func (m *arModel) LockUpdate() *arModel {
return &arModel{m.M.LockUpdate()}
}
// LockShared sets the lock in share mode for current operation.
func (m *arModel) LockShared() *arModel {
return &arModel{m.M.LockShared()}
}
// Unscoped enables/disables the soft deleting feature.
func (m *arModel) Unscoped() *arModel {
return &arModel{m.M.Unscoped()}
}
+1 -39
View File
@@ -4,12 +4,8 @@ import (
"gfast/app/model/admin/user_online"
"gfast/boot"
"gfast/library/service"
"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"
)
//获取在线用户列表
@@ -20,41 +16,7 @@ func GetOnlineListPage(req *user_online.ReqListSearch) (total, page int, list []
if req.PageSize == 0 {
req.PageSize = service.AdminPageNum
}
return user_online.GetOnlineListPage(req)
}
//通过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
return user_online.GetOnlineListPage(req, false)
}
//通过token获取uuid和userKey
@@ -0,0 +1,13 @@
package web_set_service
import "gfast/app/model/admin/web_set"
// 更新站点信息
func UpdateSave(req *web_set.UpdateReq) error {
return web_set.UpdateSave(req)
}
// GetInfoByID 根据ID查询站点信息
func GetInfoByID(id int) (*web_set.Entity, error) {
return web_set.GetInfoByID(id)
}
+95
View File
@@ -1,5 +1,15 @@
package task
import (
"gfast/app/model/admin/user_online"
"gfast/boot"
"github.com/goflyfox/gtoken/gtoken"
"github.com/gogf/gf/encoding/gjson"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/os/gcache"
"github.com/gogf/gf/util/gconv"
)
func init() {
var task1 Entity
task1.FuncName = "test1"
@@ -12,6 +22,12 @@ func init() {
task2.Param = nil
task2.Run = Test2
Add(task2)
var checkUserOnline Entity
checkUserOnline.FuncName = "checkUserOnline"
checkUserOnline.Param = nil
checkUserOnline.Run = CheckUserOnline
Add(checkUserOnline)
}
//无参测试
@@ -30,3 +46,82 @@ func Test2() {
println(v)
}
}
//检查在线用户
func CheckUserOnline() {
param := &user_online.ReqListSearch{
PageNum: 1,
PageSize: 50,
}
var total int
for {
var (
list []*user_online.Entity
err error
)
total, _, list, err = user_online.GetOnlineListPage(param, true)
if err != nil {
g.Log().Error(err)
break
}
if list == nil {
break
}
for _, entity := range list {
onlineInfo := GetOnlineInfo(entity.Token)
if onlineInfo == nil {
entity.Delete()
}
}
param.PageNum++
if param.PageNum*param.PageSize >= total {
break
}
}
}
//通过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
}
+2 -48
View File
@@ -4,65 +4,19 @@ import (
"fmt"
"gfast/library/service"
_ "gfast/swagger"
"github.com/goflyfox/gtoken/gtoken"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/os/glog"
"github.com/gogf/gf/os/gtime"
)
var AdminGfToken *gtoken.GfToken
func init() {
gtime.SetTimeZone("Asia/Shanghai") //设置系统时区
showLogo()
g.Log().SetFlags(glog.F_ASYNC | glog.F_TIME_DATE | glog.F_TIME_TIME | glog.F_FILE_LONG)
//g.Server().SetPort(8200)
g.Server().AddStaticPath("/public", g.Cfg().GetString("server.ServerRoot"))
//后台初始化配置
initAdmin()
//前台初始化
initFront()
}
func initAdmin() {
//无需验证权限的用户id
service.NotCheckAuthAdminIds = g.Cfg().GetInts("adminInfo.notCheckAuthAdminIds")
//后端分页长度配置
service.AdminPageNum = g.Cfg().GetInt("adminInfo.pageNum")
// 设置并启动后台gtoken处理
initAdminGfToken()
}
func initFront() {
gtoken := &gtoken.GfToken{
LoginPath: "/front/login",
LoginBeforeFunc: service.FrontLogin,
LogoutPath: "/front/logout",
AuthPaths: g.SliceStr{"/front/*"},
AuthAfterFunc: service.AuthAfterFunc,
}
gtoken.Start()
}
func initAdminGfToken() {
//多端登陆配置
service.AdminMultiLogin = g.Cfg().GetBool("gToken.MultiLogin")
AdminGfToken = &gtoken.GfToken{
CacheMode: g.Cfg().GetInt8("gToken.CacheMode"),
CacheKey: g.Cfg().GetString("gToken.CacheKey"),
Timeout: g.Cfg().GetInt("gToken.Timeout"),
MaxRefresh: g.Cfg().GetInt("gToken.MaxRefresh"),
TokenDelimiter: g.Cfg().GetString("gToken.TokenDelimiter"),
EncryptKey: g.Cfg().GetBytes("gToken.EncryptKey"),
AuthFailMsg: g.Cfg().GetString("gToken.AuthFailMsg"),
MultiLogin: service.AdminMultiLogin,
LoginPath: "/sysLogin/login",
LoginBeforeFunc: service.AdminLogin,
LoginAfterFunc: service.AdminLoginAfter,
LogoutPath: "/sysLogin/logout",
AuthPaths: g.SliceStr{"/system/*"},
AuthAfterFunc: service.AuthAfterFunc,
LogoutBeforeFunc: service.AdminLoginOut,
}
AdminGfToken.Start()
}
func showLogo() {
+41
View File
@@ -0,0 +1,41 @@
package boot
import (
"gfast/library/service"
"github.com/goflyfox/gtoken/gtoken"
"github.com/gogf/gf/frame/g"
)
var AdminGfToken *gtoken.GfToken
func initAdmin() {
//无需验证权限的用户id
service.NotCheckAuthAdminIds = g.Cfg().GetInts("adminInfo.notCheckAuthAdminIds")
//后端分页长度配置
service.AdminPageNum = g.Cfg().GetInt("adminInfo.pageNum")
// 设置并启动后台gtoken处理
initAdminGfToken()
}
func initAdminGfToken() {
//多端登陆配置
service.AdminMultiLogin = g.Cfg().GetBool("gToken.MultiLogin")
AdminGfToken = &gtoken.GfToken{
CacheMode: g.Cfg().GetInt8("gToken.CacheMode"),
CacheKey: g.Cfg().GetString("gToken.CacheKey"),
Timeout: g.Cfg().GetInt("gToken.Timeout"),
MaxRefresh: g.Cfg().GetInt("gToken.MaxRefresh"),
TokenDelimiter: g.Cfg().GetString("gToken.TokenDelimiter"),
EncryptKey: g.Cfg().GetBytes("gToken.EncryptKey"),
AuthFailMsg: g.Cfg().GetString("gToken.AuthFailMsg"),
MultiLogin: service.AdminMultiLogin,
LoginPath: "/sysLogin/login",
LoginBeforeFunc: service.AdminLogin,
LoginAfterFunc: service.LoginAfter,
LogoutPath: "/sysLogin/logout",
AuthPaths: g.SliceStr{"/system/*"},
AuthAfterFunc: service.AuthAfterFunc,
LogoutBeforeFunc: service.LoginOut,
}
AdminGfToken.Start()
}
+42 -17
View File
File diff suppressed because one or more lines are too long
+61
View File
@@ -0,0 +1,61 @@
package service
import (
"gfast/library/response"
"gfast/library/utils"
"github.com/gogf/gf/crypto/gmd5"
"github.com/gogf/gf/net/ghttp"
"github.com/gogf/gf/util/gvalid"
)
var (
AdminMultiLogin bool //是否允许后台管理员多端登陆
AdminPageNum = 20 //后台分页长度
NotCheckAuthAdminIds []int //无需验证权限的用户id
)
//AdminLogin 后台用户登陆验证
func AdminLogin(r *ghttp.Request) (string, interface{}) {
data := r.GetFormMapStrStr()
rules := map[string]string{
"idValueC": "required",
"username": "required",
"password": "required",
}
msgs := map[string]interface{}{
"idValueC": "请输入验证码",
"username": "账号不能为空",
"password": "密码不能为空",
}
if e := gvalid.CheckMap(data, rules, msgs); e != nil {
response.JsonExit(r, response.ErrorCode, e.String())
}
//判断验证码是否正确
if !VerifyString(data["idKeyC"], data["idValueC"]) {
response.JsonExit(r, response.ErrorCode, "验证码输入错误")
}
password := utils.EncryptCBC(data["password"], utils.AdminCbcPublicKey)
var keys string
if AdminMultiLogin {
keys = data["username"] + password + gmd5.MustEncryptString(utils.GetClientIp(r))
} else {
keys = data["username"] + password
}
ip := utils.GetClientIp(r)
userAgent := r.Header.Get("User-Agent")
if err, user := signIn(data["username"], password, r); err != nil {
go loginLog(0, data["username"], ip, userAgent, err.Error(), "系统后台")
response.JsonExit(r, response.ErrorCode, err.Error())
} else {
//判断是否后台用户
if user.IsAdmin != 1 {
response.JsonExit(r, response.ErrorCode, "抱歉!此用户不属于后台管理员!")
}
r.SetParam("userInfo", user)
go loginLog(1, data["username"], ip, userAgent, "登录成功", "系统后台")
return keys, user
}
return keys, nil
}
+4 -58
View File
@@ -6,16 +6,13 @@ import (
"gfast/app/model/admin/sys_login_log"
"gfast/app/model/admin/user"
"gfast/app/model/admin/user_online"
"gfast/library/response"
"gfast/library/utils"
"github.com/goflyfox/gtoken/gtoken"
"github.com/gogf/gf/crypto/gmd5"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/net/ghttp"
"github.com/gogf/gf/os/gtime"
"github.com/gogf/gf/text/gstr"
"github.com/gogf/gf/util/gconv"
"github.com/gogf/gf/util/gvalid"
"github.com/mojocn/base64Captcha"
"github.com/mssola/user_agent"
"strings"
@@ -24,12 +21,6 @@ import (
//版本号
const Version = "1.0.02"
var (
AdminMultiLogin bool //是否允许后台管理员多端登陆
AdminPageNum = 20 //后台分页长度
NotCheckAuthAdminIds []int //无需验证权限的用户id
)
//获取数字验证码
func GetVerifyImgDigit() (idKeyC string, base64stringC string) {
driver := &base64Captcha.DriverDigit{80, 240, 5, 0.7, 5}
@@ -77,54 +68,8 @@ func FrontLogin(r *ghttp.Request) (string, interface{}) {
return "test", nil
}
//AdminLogin 后台用户登陆验证
func AdminLogin(r *ghttp.Request) (string, interface{}) {
data := r.GetFormMapStrStr()
rules := map[string]string{
"idValueC": "required",
"username": "required",
"password": "required",
}
msgs := map[string]interface{}{
"idValueC": "请输入验证码",
"username": "账号不能为空",
"password": "密码不能为空",
}
if e := gvalid.CheckMap(data, rules, msgs); e != nil {
response.JsonExit(r, response.ErrorCode, e.String())
}
//判断验证码是否正确
if !VerifyString(data["idKeyC"], data["idValueC"]) {
response.JsonExit(r, response.ErrorCode, "验证码输入错误")
}
password := utils.EncryptCBC(data["password"], utils.AdminCbcPublicKey)
var keys string
if AdminMultiLogin {
keys = data["username"] + password + gmd5.MustEncryptString(utils.GetClientIp(r))
} else {
keys = data["username"] + password
}
ip := utils.GetClientIp(r)
userAgent := r.Header.Get("User-Agent")
if err, user := signIn(data["username"], password, r); err != nil {
go loginLog(0, data["username"], ip, userAgent, err.Error())
response.JsonExit(r, response.ErrorCode, err.Error())
} else {
//判断是否后台用户
if user.IsAdmin != 1 {
response.JsonExit(r, response.ErrorCode, "抱歉!此用户不属于后台管理员!")
}
r.SetParam("userInfo", user)
go loginLog(1, data["username"], ip, userAgent, "登录成功")
return keys, user
}
return keys, nil
}
// 后台登录返回方法
func AdminLoginAfter(r *ghttp.Request, respData gtoken.Resp) {
func LoginAfter(r *ghttp.Request, respData gtoken.Resp) {
if !respData.Success() {
r.Response.WriteJson(respData)
} else {
@@ -168,7 +113,7 @@ func AuthAfterFunc(r *ghttp.Request, respData gtoken.Resp) {
}
//后台退出登陆
func AdminLoginOut(r *ghttp.Request) bool {
func LoginOut(r *ghttp.Request) bool {
//删除在线用户状态
authHeader := r.Header.Get("Authorization")
if authHeader != "" {
@@ -208,7 +153,7 @@ func signIn(username, password string, r *ghttp.Request) (error, *user.User) {
}
//登录日志记录
func loginLog(status int, username, ip, userAgent, msg string) {
func loginLog(status int, username, ip, userAgent, msg string, module string) {
var log sys_login_log.Entity
log.LoginName = username
log.Ipaddr = ip
@@ -219,5 +164,6 @@ func loginLog(status int, username, ip, userAgent, msg string) {
log.Status = status
log.Msg = msg
log.LoginTime = gtime.Timestamp()
log.Module = module
log.Save()
}
+2 -2
View File
@@ -21,9 +21,9 @@ func CORS(r *ghttp.Request) {
//权限判断处理中间件
func Auth(r *ghttp.Request) {
if r.Method != "GET" {
/*if r.Method != "GET" {
response.FailJson(true, r, "演示系统禁止操作")
}
}*/
//获取登陆用户id
adminId := user_service.GetLoginID(r)
//获取无需验证权限的用户id
-54
View File
@@ -1,9 +1,6 @@
package router
import (
"gfast/app/controller/admin"
"gfast/app/controller/front"
"gfast/hook"
"gfast/middleWare"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/net/ghttp"
@@ -19,51 +16,6 @@ func init() {
group.Hook("/pub_upload/*", ghttp.HOOK_BEFORE_SERVE, func(r *ghttp.Request) {
r.Response.CORSDefault()
})
group.Group("/sysLogin", func(group *ghttp.RouterGroup) {
group.ALL("/public", new(admin.Public))
})
group.Group("/system", func(group *ghttp.RouterGroup) {
group.Middleware(middleWare.Auth) //后台权限验证
//后台操作日志记录
group.Hook("/*", ghttp.HOOK_AFTER_OUTPUT, hook.OperationLog)
//文件上传
group.POST("/upload", new(admin.Upload))
//后台首页
group.ALL("/index", new(admin.Index))
//权限管理
group.ALL("/auth", new(admin.Auth))
//部门管理
group.ALL("/dept", new(admin.Dept))
//个人中心
group.ALL("/user", new(admin.User))
//岗位管理
group.ALL("/post", new(admin.Post))
//配置管理
group.Group("/config", func(group *ghttp.RouterGroup) {
group.ALL("/dict", new(admin.Dict))
group.ALL("/params", new(admin.Params))
})
//系统监控
group.Group("/monitor", func(group *ghttp.RouterGroup) {
group.ALL("/online", new(admin.MonitorOnline))
group.ALL("/job", new(admin.MonitorJob))
group.ALL("/server", new(admin.MonitorServer))
group.ALL("/operlog", new(admin.MonitorOperationLog))
group.ALL("/loginlog", new(admin.MonitorLoginLog))
})
//代码生成
group.Group("/tools", func(group *ghttp.RouterGroup) {
group.ALL("/gen", new(admin.Gen))
})
})
group.GET("/swagger.json", func(r *ghttp.Request) {
jsonStr, err := swag.ReadDoc()
@@ -73,10 +25,4 @@ func init() {
}
r.Response.WriteJson(jsonStr)
})
group.Group("/front", func(group *ghttp.RouterGroup) {
//前台首页
group.ALL("/index", new(front.Index))
})
}
+61
View File
@@ -0,0 +1,61 @@
package router
import (
"gfast/app/controller/admin"
"gfast/app/controller/common"
"gfast/hook"
"gfast/middleWare"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/net/ghttp"
)
//后端路由处理
func init() {
s := g.Server()
group := s.Group("/")
group.Group("/captcha", func(group *ghttp.RouterGroup) {
group.ALL("/get", new(common.Captcha))
})
group.Group("/system", func(group *ghttp.RouterGroup) {
group.Middleware(middleWare.Auth) //后台权限验证
//后台操作日志记录
group.Hook("/*", ghttp.HOOK_AFTER_OUTPUT, hook.OperationLog)
//文件上传
group.POST("/upload", new(admin.Upload))
//后台首页
group.ALL("/index", new(admin.Index))
//权限管理
group.ALL("/auth", new(admin.Auth))
//部门管理
group.ALL("/dept", new(admin.Dept))
//个人中心
group.ALL("/user", new(admin.User))
//岗位管理
group.ALL("/post", new(admin.Post))
//配置管理
group.Group("/config", func(group *ghttp.RouterGroup) {
group.ALL("/dict", new(admin.Dict))
group.ALL("/params", new(admin.Params))
group.ALL("/webSet", new(admin.WebSet))
})
//系统监控
group.Group("/monitor", func(group *ghttp.RouterGroup) {
group.ALL("/online", new(admin.MonitorOnline))
group.ALL("/job", new(admin.MonitorJob))
group.ALL("/server", new(admin.MonitorServer))
group.ALL("/operlog", new(admin.MonitorOperationLog))
group.ALL("/loginlog", new(admin.MonitorLoginLog))
})
//代码生成
group.Group("/tools", func(group *ghttp.RouterGroup) {
group.ALL("/gen", new(admin.Gen))
})
})
}