修改文件目录

This commit is contained in:
linwenxiang
2020-09-04 00:21:52 +08:00
parent 41b06c806a
commit 01ea376015
109 changed files with 180 additions and 172 deletions
+27
View File
@@ -0,0 +1,27 @@
package middleware
import (
"time"
"go-admin/app/admin/middleware/handler"
jwt "go-admin/pkg/jwtauth"
"go-admin/tools/config"
)
func AuthInit() (*jwt.GinJWTMiddleware, error) {
return jwt.New(&jwt.GinJWTMiddleware{
Realm: "test zone",
Key: []byte(config.ApplicationConfig.JwtSecret),
Timeout: time.Hour,
MaxRefresh: time.Hour,
PayloadFunc: handler.PayloadFunc,
IdentityHandler: handler.IdentityHandler,
Authenticator: handler.Authenticator,
Authorizator: handler.Authorizator,
Unauthorized: handler.Unauthorized,
TokenLookup: "header: Authorization, query: token, cookie: jwt",
TokenHeadName: "Bearer",
TimeFunc: time.Now,
})
}
+50
View File
@@ -0,0 +1,50 @@
package middleware
import (
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
)
func CustomError(c *gin.Context) {
defer func() {
if err := recover(); err != nil {
if c.IsAborted() {
c.Status(200)
}
switch errStr := err.(type) {
case string:
p := strings.Split(errStr, "#")
if len(p) == 3 && p[0] == "CustomError" {
statusCode, e := strconv.Atoi(p[1])
if e != nil {
break
}
c.Status(statusCode)
fmt.Println(
time.Now().Format("2006-01-02 15:04:05"),
"[ERROR]",
c.Request.Method,
c.Request.URL,
statusCode,
c.Request.RequestURI,
c.ClientIP(),
p[2],
)
c.JSON(http.StatusOK, gin.H{
"code": statusCode,
"msg": p[2],
})
}
default:
panic(err)
}
}
}()
c.Next()
}
+5
View File
@@ -0,0 +1,5 @@
package middleware
import "go-admin/common/middleware"
var WithContextDb = middleware.WithContextDb
+173
View File
@@ -0,0 +1,173 @@
package handler
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/mojocn/base64Captcha"
"github.com/mssola/user_agent"
"go-admin/app/admin/models"
"go-admin/common/global"
jwt "go-admin/pkg/jwtauth"
"go-admin/tools"
"go-admin/tools/config"
)
var store = base64Captcha.DefaultMemStore
func PayloadFunc(data interface{}) jwt.MapClaims {
if v, ok := data.(map[string]interface{}); ok {
u, _ := v["user"].(models.SysUser)
r, _ := v["role"].(models.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"],
}
}
// @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值
// @Accept application/json
// @Product application/json
// @Param account body models.Login true "account"
// @Success 200 {string} string "{"code": 200, "expire": "2019-08-07T12:45:48+08:00", "token": ".eyJleHAiOjE1NjUxNTMxNDgsImlkIjoiYWRtaW4iLCJvcmlnX2lhdCI6MTU2NTE0OTU0OH0.-zvzHvbg0A" }"
// @Router /login [post]
func Authenticator(c *gin.Context) (interface{}, error) {
var loginVals models.Login
var status = "0"
var msg = "登录成功"
var username = ""
if err := c.ShouldBind(&loginVals); err != nil {
username = loginVals.Username
msg = "数据解析失败"
status = "1"
LoginLogToDB(c, status, msg, username)
return nil, jwt.ErrMissingLoginValues
}
if config.ApplicationConfig.Mode != "dev" {
if !store.Verify(loginVals.UUID, loginVals.Code, true) {
username = loginVals.Username
msg = "验证码错误"
status = "1"
LoginLogToDB(c, status, msg, username)
return nil, jwt.ErrInvalidVerificationode
}
}
user, role, e := loginVals.GetUser()
if e == nil {
username = loginVals.Username
LoginLogToDB(c, status, msg, username)
return map[string]interface{}{"user": user, "role": role}, nil
} else {
msg = "登录失败"
status = "1"
LoginLogToDB(c, status, msg, username)
global.RequestLogger.Println(e.Error())
}
return nil, jwt.ErrFailedAuthentication
}
// Write log to database
func LoginLogToDB(c *gin.Context, status string, msg string, username string) {
if config.LoggerConfig.EnabledDB {
var loginlog models.LoginLog
ua := user_agent.New(c.Request.UserAgent())
loginlog.Ipaddr = c.ClientIP()
loginlog.Username = username
location := tools.GetLocation(c.ClientIP())
loginlog.LoginLocation = location
loginlog.LoginTime = tools.GetCurrentTime()
loginlog.Status = status
loginlog.Remark = c.Request.UserAgent()
browserName, browserVersion := ua.Browser()
loginlog.Browser = browserName + " " + browserVersion
loginlog.Os = ua.OS()
loginlog.Msg = msg
loginlog.Platform = ua.Platform()
_, _ = loginlog.Create()
}
}
// @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) {
var loginlog models.LoginLog
ua := user_agent.New(c.Request.UserAgent())
loginlog.Ipaddr = c.ClientIP()
location := tools.GetLocation(c.ClientIP())
loginlog.LoginLocation = location
loginlog.LoginTime = tools.GetCurrentTime()
loginlog.Status = "0"
loginlog.Remark = c.Request.UserAgent()
browserName, browserVersion := ua.Browser()
loginlog.Browser = browserName + " " + browserVersion
loginlog.Os = ua.OS()
loginlog.Platform = ua.Platform()
loginlog.Username = tools.GetUserName(c)
loginlog.Msg = "退出成功"
loginlog.Create()
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,
})
}
@@ -0,0 +1,22 @@
package handler
import (
"github.com/gin-gonic/gin"
"github.com/unrolled/secure"
"go-admin/tools/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()
}
}
+19
View File
@@ -0,0 +1,19 @@
package handler
import (
"log"
"net/http"
"github.com/gin-gonic/gin"
jwt "go-admin/pkg/jwtauth"
)
func NoFound(c *gin.Context) {
claims := jwt.ExtractClaims(c)
log.Printf("NoRoute claims: %#v\n", claims)
c.JSON(http.StatusOK, gin.H{
"code": "404",
"message": "not found",
})
}
+11
View 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",
})
}
+166
View File
@@ -0,0 +1,166 @@
package sd
import (
"fmt"
"net/http"
"runtime"
"time"
"github.com/gin-gonic/gin"
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/disk"
"github.com/shirou/gopsutil/load"
"github.com/shirou/gopsutil/mem"
"go-admin/tools/app"
)
const (
B = 1
KB = 1024 * B
MB = 1024 * KB
GB = 1024 * MB
)
// 健康状况
// @Summary 健康状况 HealthCheck shows OK as the ping-pong result.
// @Description 健康状况
// @Accept text/html
// @Produce text/html
// @Success 200 {string} string "OK"
// @Router /sd/health [get]
// @BasePath
func HealthCheck(c *gin.Context) {
app.OK(c, "", "OK")
}
// @Summary 服务器硬盘使用量
// @Description 服务器硬盘使用量 DiskCheck checks the disk usage.
// @Accept text/html
// @Produce text/html
// @Success 200 {string} string "OK - Free space: 16321MB (15GB) / 51200MB (50GB) | Used: 31%"
// @Failure 500 {string} string "CRITICAL"
// @Failure 429 {string} string "WARNING"
// @Router /sd/disk [get]
// @BasePath
func DiskCheck(c *gin.Context) {
u, _ := disk.Usage("/")
usedMB := int(u.Used) / MB
usedGB := int(u.Used) / GB
totalMB := int(u.Total) / MB
totalGB := int(u.Total) / GB
usedPercent := int(u.UsedPercent)
status := http.StatusOK
text := "OK"
if usedPercent >= 95 {
status = http.StatusOK
text = "CRITICAL"
} else if usedPercent >= 90 {
status = http.StatusTooManyRequests
text = "WARNING"
}
message := fmt.Sprintf("%s - Free space: %dMB (%dGB) / %dMB (%dGB) | Used: %d%%", text, usedMB, usedGB, totalMB, totalGB, usedPercent)
c.String(status, "\n"+message)
}
// @Summary OS
// @Description Os
// @Accept text/html
// @Produce text/html
// @Success 200 {string} string ""
// @Router /sd/os [get]
// @BasePath
func OSCheck(c *gin.Context) {
status := http.StatusOK
app.Custum(c, gin.H{
"code": 200,
"status": status,
"goOs": runtime.GOOS,
"compiler": runtime.Compiler,
"numCpu": runtime.NumCPU(),
"version": runtime.Version(),
"numGoroutine": runtime.NumGoroutine(),
})
}
// @Summary CPU 使用量
// @Description CPU 使用量 DiskCheck checks the disk usage.
// @Accept text/html
// @Produce text/html
// @Success 200 {string} string ""
// @Router /sd/cpu [get]
// @BasePath
func CPUCheck(c *gin.Context) {
cores, _ := cpu.Counts(false)
cpus, err := cpu.Percent(time.Duration(200)*time.Millisecond, true)
if err == nil {
for i, c := range cpus {
fmt.Printf("cpu%d : %f%%\n", i, c)
}
}
a, _ := load.Avg()
l1 := a.Load1
l5 := a.Load5
l15 := a.Load15
status := http.StatusOK
text := "OK"
if l5 >= float64(cores-1) {
status = http.StatusInternalServerError
text = "CRITICAL"
} else if l5 >= float64(cores-2) {
status = http.StatusTooManyRequests
text = "WARNING"
}
app.Custum(c, gin.H{
"code": 200,
"msg": text,
"status": status,
"cores": cores,
"load1": l1,
"load5": l5,
"load15": l15,
})
}
// @Summary 内存使用量
// @Description 内存使用量 RAMCheck checks the disk usage.
// @Accept text/html
// @Produce text/html
// @Success 200 {string} string ""
// @Router /sd/ram [get]
// @BasePath
func RAMCheck(c *gin.Context) {
u, _ := mem.VirtualMemory()
usedMB := int(u.Used) / MB
totalMB := int(u.Total) / MB
usedPercent := int(u.UsedPercent)
status := http.StatusOK
text := "OK"
if usedPercent >= 95 {
status = http.StatusInternalServerError
text = "CRITICAL"
} else if usedPercent >= 90 {
status = http.StatusTooManyRequests
text = "WARNING"
}
app.Custum(c, gin.H{
"code": 200,
"msg": text,
"status": status,
"used": usedMB,
"total": totalMB,
"usedPercent": usedPercent,
})
}
+48
View File
@@ -0,0 +1,48 @@
package middleware
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
)
// NoCache is a middleware function that appends headers
// to prevent the client from caching the HTTP response.
func NoCache(c *gin.Context) {
c.Header("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate, value")
c.Header("Expires", "Thu, 01 Jan 1970 00:00:00 GMT")
c.Header("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
c.Next()
}
// Options is a middleware function that appends headers
// for options requests and aborts then exits the middleware
// chain and ends the request.
func Options(c *gin.Context) {
if c.Request.Method != "OPTIONS" {
c.Next()
} else {
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS")
c.Header("Access-Control-Allow-Headers", "authorization, origin, content-type, accept")
c.Header("Allow", "HEAD,GET,POST,PUT,PATCH,DELETE,OPTIONS")
c.Header("Content-Type", "application/json")
c.AbortWithStatus(200)
}
}
// Secure is a middleware function that appends security
// and resource access headers.
func Secure(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*")
//c.Header("X-Frame-Options", "DENY")
c.Header("X-Content-Type-Options", "nosniff")
c.Header("X-XSS-Protection", "1; mode=block")
if c.Request.TLS != nil {
c.Header("Strict-Transport-Security", "max-age=31536000")
}
// Also consider adding Content-Security-Policy headers
// c.Header("Content-Security-Policy", "script-src 'self' https://cdnjs.cloudflare.com")
}
+20
View File
@@ -0,0 +1,20 @@
package middleware
import (
"github.com/gin-gonic/gin"
)
func InitMiddleware(r *gin.Engine) {
// 日志处理
r.Use(LoggerToFile())
// 自定义错误处理
r.Use(CustomError)
// NoCache is a middleware function that appends headers
r.Use(NoCache)
// 跨域处理
r.Use(Options)
// Secure is a middleware function that appends security
r.Use(Secure)
// Set X-Request-Id header
r.Use(RequestId())
}
+110
View File
@@ -0,0 +1,110 @@
package middleware
import (
"fmt"
"strings"
"time"
"github.com/gin-gonic/gin"
"go-admin/app/admin/models"
"go-admin/common/global"
"go-admin/tools"
config2 "go-admin/tools/config"
)
// 日志记录到文件
func LoggerToFile() gin.HandlerFunc {
return func(c *gin.Context) {
// 开始时间
startTime := time.Now()
// 处理请求
c.Next()
// 结束时间
endTime := time.Now()
// 执行时间
latencyTime := endTime.Sub(startTime)
// 请求方式
reqMethod := c.Request.Method
// 请求路由
reqUri := c.Request.RequestURI
// 状态码
statusCode := c.Writer.Status()
// 请求IP
clientIP := c.ClientIP()
// 日志格式
fmt.Printf("%s [INFO] %s %s %3d %13v %15s \r\n",
startTime.Format("2006-01-02 15:04:05"),
reqMethod,
reqUri,
statusCode,
latencyTime,
clientIP,
)
global.RequestLogger.Info(statusCode, latencyTime, clientIP, reqMethod, reqUri)
if c.Request.Method != "GET" && c.Request.Method != "OPTIONS" && config2.LoggerConfig.EnabledDB {
SetDBOperLog(c, clientIP, statusCode, reqUri, reqMethod, latencyTime)
}
}
}
// 写入操作日志表
// 该方法后续即将弃用
func SetDBOperLog(c *gin.Context, clientIP string, statusCode int, reqUri string, reqMethod string, latencyTime time.Duration) {
menu := models.Menu{}
menu.Path = reqUri
menu.Action = reqMethod
menuList, _ := menu.Get()
sysOperLog := models.SysOperLog{}
sysOperLog.OperIp = clientIP
sysOperLog.OperLocation = tools.GetLocation(clientIP)
sysOperLog.Status = tools.IntToString(statusCode)
sysOperLog.OperName = tools.GetUserName(c)
sysOperLog.RequestMethod = c.Request.Method
sysOperLog.OperUrl = reqUri
if reqUri == "/login" {
sysOperLog.BusinessType = "10"
sysOperLog.Title = "用户登录"
sysOperLog.OperName = "-"
} else if strings.Contains(reqUri, "/api/v1/logout") {
sysOperLog.BusinessType = "11"
} else if strings.Contains(reqUri, "/api/v1/getCaptcha") {
sysOperLog.BusinessType = "12"
sysOperLog.Title = "验证码"
} else {
if reqMethod == "POST" {
sysOperLog.BusinessType = "1"
} else if reqMethod == "PUT" {
sysOperLog.BusinessType = "2"
} else if reqMethod == "DELETE" {
sysOperLog.BusinessType = "3"
}
}
sysOperLog.Method = reqMethod
if len(menuList) > 0 {
sysOperLog.Title = menuList[0].Title
}
b, _ := c.Get("body")
sysOperLog.OperParam, _ = tools.StructToJsonStr(b)
sysOperLog.CreateBy = tools.GetUserName(c)
sysOperLog.OperTime = tools.GetCurrentTime()
sysOperLog.LatencyTime = (latencyTime).String()
sysOperLog.UserAgent = c.Request.UserAgent()
if c.Err() == nil {
sysOperLog.Status = "0"
} else {
sysOperLog.Status = "1"
}
_, _ = sysOperLog.Create()
}
+43
View File
@@ -0,0 +1,43 @@
package middleware
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
mycasbin "go-admin/pkg/casbin"
"go-admin/pkg/jwtauth"
"go-admin/tools"
)
//权限检查中间件
func AuthCheckRole() gin.HandlerFunc {
return func(c *gin.Context) {
data, _ := c.Get(jwtauth.JwtPayloadKey)
v := data.(jwtauth.MapClaims)
e, err := mycasbin.Casbin()
tools.HasError(err, "", 500)
//检查权限
res, err := e.Enforce(v["rolekey"], c.Request.URL.Path, c.Request.Method)
tools.HasError(err, "", 500)
fmt.Printf("%s [INFO] %s %s %s \r\n",
tools.GetCurrentTimeStr(),
c.Request.Method,
c.Request.URL.Path,
v["rolekey"],
)
if res {
c.Next()
} else {
c.JSON(http.StatusOK, gin.H{
"code": 403,
"msg": "对不起,您没有该接口访问权限,请联系管理员",
})
c.Abort()
return
}
}
}
+26
View File
@@ -0,0 +1,26 @@
package middleware
import (
"github.com/gin-gonic/gin"
"github.com/satori/go.uuid"
)
func RequestId() gin.HandlerFunc {
return func(c *gin.Context) {
// Check for incoming header, use it if exists
requestId := c.Request.Header.Get("X-Request-Id")
// Create request id with UUID4
if requestId == "" {
u4 := uuid.NewV4()
requestId = u4.String()
}
// Expose it for use in the application
c.Set("X-Request-Id", requestId)
// Set X-Request-Id header
c.Writer.Header().Set("X-Request-Id", requestId)
c.Next()
}
}