1
Some checks failed
Build / build (push) Has been cancelled
CodeQL / Analyze (go) (push) Has been cancelled
build / Build (push) Has been cancelled
GitHub Actions Mirror / mirror_to_gitee (push) Has been cancelled
GitHub Actions Mirror / mirror_to_gitlab (push) Has been cancelled
Issue Close Require / issue-close-require (push) Has been cancelled
Issue Check Inactive / issue-check-inactive (push) Has been cancelled
Some checks failed
Build / build (push) Has been cancelled
CodeQL / Analyze (go) (push) Has been cancelled
build / Build (push) Has been cancelled
GitHub Actions Mirror / mirror_to_gitee (push) Has been cancelled
GitHub Actions Mirror / mirror_to_gitlab (push) Has been cancelled
Issue Close Require / issue-close-require (push) Has been cancelled
Issue Check Inactive / issue-check-inactive (push) Has been cancelled
This commit is contained in:
182
common/middleware/handler/auth.go
Normal file
182
common/middleware/handler/auth.go
Normal file
@ -0,0 +1,182 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/common"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/go-admin-team/go-admin-core/sdk"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/api"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/config"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg/captcha"
|
||||
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg/response"
|
||||
"github.com/mssola/user_agent"
|
||||
"go-admin/common/global"
|
||||
)
|
||||
|
||||
func PayloadFunc(data interface{}) jwt.MapClaims {
|
||||
if v, ok := data.(map[string]interface{}); ok {
|
||||
u, _ := v["user"].(SysUser)
|
||||
r, _ := v["role"].(SysRole)
|
||||
return jwt.MapClaims{
|
||||
jwt.IdentityKey: u.UserId,
|
||||
jwt.RoleIdKey: r.RoleId,
|
||||
jwt.RoleKey: r.RoleKey,
|
||||
jwt.NiceKey: u.Username,
|
||||
jwt.DataScopeKey: r.DataScope,
|
||||
jwt.RoleNameKey: r.RoleName,
|
||||
}
|
||||
}
|
||||
return jwt.MapClaims{}
|
||||
}
|
||||
|
||||
func IdentityHandler(c *gin.Context) interface{} {
|
||||
claims := jwt.ExtractClaims(c)
|
||||
return map[string]interface{}{
|
||||
"IdentityKey": claims["identity"],
|
||||
"UserName": claims["nice"],
|
||||
"RoleKey": claims["rolekey"],
|
||||
"UserId": claims["identity"],
|
||||
"RoleIds": claims["roleid"],
|
||||
"DataScope": claims["datascope"],
|
||||
}
|
||||
}
|
||||
|
||||
// Authenticator 获取token
|
||||
// @Summary 登陆
|
||||
// @Description 获取token
|
||||
// @Description LoginHandler can be used by clients to get a jwt token.
|
||||
// @Description Payload needs to be json in the form of {"username": "USERNAME", "password": "PASSWORD"}.
|
||||
// @Description Reply will be of the form {"token": "TOKEN"}.
|
||||
// @Description dev mode:It should be noted that all fields cannot be empty, and a value of 0 can be passed in addition to the account password
|
||||
// @Description 注意:开发模式:需要注意全部字段不能为空,账号密码外可以传入0值
|
||||
// @Tags 登陆
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param account body Login true "account"
|
||||
// @Success 200 {string} string "{"code": 200, "expire": "2019-08-07T12:45:48+08:00", "token": ".eyJleHAiOjE1NjUxNTMxNDgsImlkIjoiYWRtaW4iLCJvcmlnX2lhdCI6MTU2NTE0OTU0OH0.-zvzHvbg0A" }"
|
||||
// @Router /api/v1/login [post]
|
||||
func Authenticator(c *gin.Context) (interface{}, error) {
|
||||
log := api.GetRequestLogger(c)
|
||||
db, err := pkg.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Errorf("get db error, %s", err.Error())
|
||||
response.Error(c, 500, err, "数据库连接获取失败")
|
||||
return nil, jwt.ErrFailedAuthentication
|
||||
}
|
||||
|
||||
var loginVals Login
|
||||
var status = "2"
|
||||
var msg = "登录成功"
|
||||
var username = ""
|
||||
defer func() {
|
||||
LoginLogToDB(c, status, msg, username)
|
||||
}()
|
||||
|
||||
if err = c.ShouldBind(&loginVals); err != nil {
|
||||
username = loginVals.Username
|
||||
msg = "数据解析失败"
|
||||
status = "1"
|
||||
|
||||
return nil, jwt.ErrMissingLoginValues
|
||||
}
|
||||
if config.ApplicationConfig.Mode != "dev" {
|
||||
if !captcha.Verify(loginVals.UUID, loginVals.Code, true) {
|
||||
username = loginVals.Username
|
||||
msg = "验证码错误"
|
||||
status = "1"
|
||||
|
||||
return nil, jwt.ErrInvalidVerificationode
|
||||
}
|
||||
}
|
||||
sysUser, role, e := loginVals.GetUser(db)
|
||||
if e == nil {
|
||||
username = loginVals.Username
|
||||
|
||||
return map[string]interface{}{"user": sysUser, "role": role}, nil
|
||||
} else {
|
||||
msg = "登录失败"
|
||||
status = "1"
|
||||
log.Warnf("%s login failed!", loginVals.Username)
|
||||
}
|
||||
return nil, jwt.ErrFailedAuthentication
|
||||
}
|
||||
|
||||
// LoginLogToDB Write log to database
|
||||
func LoginLogToDB(c *gin.Context, status string, msg string, username string) {
|
||||
if !config.LoggerConfig.EnabledDB {
|
||||
return
|
||||
}
|
||||
log := api.GetRequestLogger(c)
|
||||
l := make(map[string]interface{})
|
||||
|
||||
ua := user_agent.New(c.Request.UserAgent())
|
||||
l["ipaddr"] = common.GetClientIP(c)
|
||||
l["loginLocation"] = "" // pkg.GetLocation(common.GetClientIP(c),gaConfig.ExtConfig.AMap.Key)
|
||||
l["loginTime"] = pkg.GetCurrentTime()
|
||||
l["status"] = status
|
||||
l["remark"] = c.Request.UserAgent()
|
||||
browserName, browserVersion := ua.Browser()
|
||||
l["browser"] = browserName + " " + browserVersion
|
||||
l["os"] = ua.OS()
|
||||
l["platform"] = ua.Platform()
|
||||
l["username"] = username
|
||||
l["msg"] = msg
|
||||
|
||||
q := sdk.Runtime.GetMemoryQueue(c.Request.Host)
|
||||
message, err := sdk.Runtime.GetStreamMessage("", global.LoginLog, l)
|
||||
if err != nil {
|
||||
log.Errorf("GetStreamMessage error, %s", err.Error())
|
||||
//日志报错错误,不中断请求
|
||||
} else {
|
||||
err = q.Append(message)
|
||||
if err != nil {
|
||||
log.Errorf("Append message error, %s", err.Error())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// LogOut
|
||||
// @Summary 退出登录
|
||||
// @Description 获取token
|
||||
// LoginHandler can be used by clients to get a jwt token.
|
||||
// Reply will be of the form {"token": "TOKEN"}.
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Success 200 {string} string "{"code": 200, "msg": "成功退出系统" }"
|
||||
// @Router /logout [post]
|
||||
// @Security Bearer
|
||||
func LogOut(c *gin.Context) {
|
||||
LoginLogToDB(c, "2", "退出成功", user.GetUserName(c))
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 200,
|
||||
"msg": "退出成功",
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
func Authorizator(data interface{}, c *gin.Context) bool {
|
||||
|
||||
if v, ok := data.(map[string]interface{}); ok {
|
||||
u, _ := v["user"].(models.SysUser)
|
||||
r, _ := v["role"].(models.SysRole)
|
||||
c.Set("role", r.RoleName)
|
||||
c.Set("roleIds", r.RoleId)
|
||||
c.Set("userId", u.UserId)
|
||||
c.Set("userName", u.Username)
|
||||
c.Set("dataScope", r.DataScope)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func Unauthorized(c *gin.Context, code int, message string) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": code,
|
||||
"msg": message,
|
||||
})
|
||||
}
|
||||
22
common/middleware/handler/httpshandler.go
Normal file
22
common/middleware/handler/httpshandler.go
Normal file
@ -0,0 +1,22 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/unrolled/secure"
|
||||
|
||||
"github.com/go-admin-team/go-admin-core/sdk/config"
|
||||
)
|
||||
|
||||
func TlsHandler() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
secureMiddleware := secure.New(secure.Options{
|
||||
SSLRedirect: true,
|
||||
SSLHost: config.SslConfig.Domain,
|
||||
})
|
||||
err := secureMiddleware.Process(c.Writer, c.Request)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
33
common/middleware/handler/login.go
Normal file
33
common/middleware/handler/login.go
Normal file
@ -0,0 +1,33 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
log "github.com/go-admin-team/go-admin-core/logger"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Login struct {
|
||||
Username string `form:"UserName" json:"username" binding:"required"`
|
||||
Password string `form:"Password" json:"password" binding:"required"`
|
||||
Code string `form:"Code" json:"code" binding:"required"`
|
||||
UUID string `form:"UUID" json:"uuid" binding:"required"`
|
||||
}
|
||||
|
||||
func (u *Login) GetUser(tx *gorm.DB) (user SysUser, role SysRole, err error) {
|
||||
err = tx.Table("sys_user").Where("username = ? and status = '2'", u.Username).First(&user).Error
|
||||
if err != nil {
|
||||
log.Errorf("get user error, %s", err.Error())
|
||||
return
|
||||
}
|
||||
_, err = pkg.CompareHashAndPassword(user.Password, u.Password)
|
||||
if err != nil {
|
||||
log.Errorf("user login error, %s", err.Error())
|
||||
return
|
||||
}
|
||||
err = tx.Table("sys_role").Where("role_id = ? ", user.RoleId).First(&role).Error
|
||||
if err != nil {
|
||||
log.Errorf("get role error, %s", err.Error())
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
11
common/middleware/handler/ping.go
Normal file
11
common/middleware/handler/ping.go
Normal file
@ -0,0 +1,11 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func Ping(c *gin.Context) {
|
||||
c.JSON(200, gin.H{
|
||||
"message": "ok",
|
||||
})
|
||||
}
|
||||
24
common/middleware/handler/role.go
Normal file
24
common/middleware/handler/role.go
Normal file
@ -0,0 +1,24 @@
|
||||
package handler
|
||||
|
||||
import "go-admin/common/models"
|
||||
|
||||
type SysRole struct {
|
||||
RoleId int `json:"roleId" gorm:"primaryKey;autoIncrement"` // 角色编码
|
||||
RoleName string `json:"roleName" gorm:"size:128;"` // 角色名称
|
||||
Status string `json:"status" gorm:"size:4;"` //
|
||||
RoleKey string `json:"roleKey" gorm:"size:128;"` //角色代码
|
||||
RoleSort int `json:"roleSort" gorm:""` //角色排序
|
||||
Flag string `json:"flag" gorm:"size:128;"` //
|
||||
Remark string `json:"remark" gorm:"size:255;"` //备注
|
||||
Admin bool `json:"admin" gorm:"size:4;"`
|
||||
DataScope string `json:"dataScope" gorm:"size:128;"`
|
||||
Params string `json:"params" gorm:"-"`
|
||||
MenuIds []int `json:"menuIds" gorm:"-"`
|
||||
DeptIds []int `json:"deptIds" gorm:"-"`
|
||||
models.ControlBy
|
||||
models.ModelTime
|
||||
}
|
||||
|
||||
func (SysRole) TableName() string {
|
||||
return "sys_role"
|
||||
}
|
||||
40
common/middleware/handler/user.go
Normal file
40
common/middleware/handler/user.go
Normal file
@ -0,0 +1,40 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"go-admin/common/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type SysUser struct {
|
||||
UserId int `gorm:"primaryKey;autoIncrement;comment:编码" json:"userId"`
|
||||
Username string `json:"username" gorm:"size:64;comment:用户名"`
|
||||
Password string `json:"-" gorm:"size:128;comment:密码"`
|
||||
NickName string `json:"nickName" gorm:"size:128;comment:昵称"`
|
||||
Phone string `json:"phone" gorm:"size:11;comment:手机号"`
|
||||
RoleId int `json:"roleId" gorm:"size:20;comment:角色ID"`
|
||||
Salt string `json:"-" gorm:"size:255;comment:加盐"`
|
||||
Avatar string `json:"avatar" gorm:"size:255;comment:头像"`
|
||||
Sex string `json:"sex" gorm:"size:255;comment:性别"`
|
||||
Email string `json:"email" gorm:"size:128;comment:邮箱"`
|
||||
DeptId int `json:"deptId" gorm:"size:20;comment:部门"`
|
||||
PostId int `json:"postId" gorm:"size:20;comment:岗位"`
|
||||
Remark string `json:"remark" gorm:"size:255;comment:备注"`
|
||||
Status string `json:"status" gorm:"size:4;comment:状态"`
|
||||
DeptIds []int `json:"deptIds" gorm:"-"`
|
||||
PostIds []int `json:"postIds" gorm:"-"`
|
||||
RoleIds []int `json:"roleIds" gorm:"-"`
|
||||
//Dept *SysDept `json:"dept"`
|
||||
models.ControlBy
|
||||
models.ModelTime
|
||||
}
|
||||
|
||||
func (*SysUser) TableName() string {
|
||||
return "sys_user"
|
||||
}
|
||||
|
||||
func (e *SysUser) AfterFind(_ *gorm.DB) error {
|
||||
e.DeptIds = []int{e.DeptId}
|
||||
e.PostIds = []int{e.PostId}
|
||||
e.RoleIds = []int{e.RoleId}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user