修改文件目录

This commit is contained in:
linwenxiang committed 2020-09-04 00:21:52 +08:00
1 parent 41b06c806a
commit 01ea376015
109 files changed
+180 -172

No files matched your search

+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,
})
}