提交 d56512e8 编写于 作者: G Granty1

Migrate all methods in the model package to the service package

上级 5629ad96
......@@ -3,7 +3,7 @@ package v1
import (
"fmt"
"gin-vue-admin/global/response"
"gin-vue-admin/model"
"gin-vue-admin/service"
"gin-vue-admin/utils"
"github.com/gin-gonic/gin"
"io/ioutil"
......@@ -35,7 +35,7 @@ func BreakpointContinue(c *gin.Context) {
cen, _ := ioutil.ReadAll(f)
defer f.Close()
if flag := utils.CheckMd5(cen, chunkMd5); flag {
err, file := new(model.ExaFile).FindOrCreateFile(fileMd5, fileName, chunkTotal)
err, file := service.FindOrCreateFile(fileMd5, fileName, chunkTotal)
if err != nil {
response.Result(response.ERROR, nil, fmt.Sprintf("%v", err), c)
} else {
......@@ -43,7 +43,7 @@ func BreakpointContinue(c *gin.Context) {
if err != nil {
response.Result(response.ERROR, nil, fmt.Sprintf("%v", err), c)
} else {
err = file.CreateFileChunk(pathc, chunkNumber)
err = service.CreateFileChunk(file.ID, pathc, chunkNumber)
if err != nil {
response.Result(response.ERROR, nil, fmt.Sprintf("%v", err), c)
} else {
......@@ -69,7 +69,7 @@ func FindFile(c *gin.Context) {
fileMd5 := c.Query("fileMd5")
fileName := c.Query("fileName")
chunkTotal, _ := strconv.Atoi(c.Query("chunkTotal"))
err, file := new(model.ExaFile).FindOrCreateFile(fileMd5, fileName, chunkTotal)
err, file := service.FindOrCreateFile(fileMd5, fileName, chunkTotal)
if err != nil {
response.Result(response.ERROR, nil, fmt.Sprintf("查找失败:%v", err), c)
} else {
......@@ -109,7 +109,7 @@ func RemoveChunk(c *gin.Context) {
fileName := c.Query("fileName")
filePath := c.Query("filePath")
err := utils.RemoveChunk(fileMd5)
err = new(model.ExaFile).DeleteFileChunk(fileMd5, fileName, filePath)
err = service.DeleteFileChunk(fileMd5, fileName, filePath)
if err != nil {
response.Result(response.ERROR, gin.H{"filePath": filePath}, fmt.Sprintf("缓存切片删除失败:%v", err), c)
} else {
......
......@@ -3,8 +3,9 @@ package v1
import (
"fmt"
"gin-vue-admin/global/response"
"gin-vue-admin/middleware"
"gin-vue-admin/model"
"gin-vue-admin/model/request"
"gin-vue-admin/service"
"github.com/gin-gonic/gin"
)
......@@ -20,10 +21,10 @@ func CreateExaCustomer(c *gin.Context) {
var cu model.ExaCustomer
_ = c.ShouldBindJSON(&cu)
claims, _ := c.Get("claims")
waitUse := claims.(*middleware.CustomClaims)
waitUse := claims.(*request.CustomClaims)
cu.SysUserID = waitUse.ID
cu.SysUserAuthorityID = waitUse.AuthorityId
err := cu.CreateExaCustomer()
err := service.CreateExaCustomer(cu)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("创建失败:%v", err), c)
} else {
......@@ -42,7 +43,7 @@ func CreateExaCustomer(c *gin.Context) {
func DeleteExaCustomer(c *gin.Context) {
var cu model.ExaCustomer
_ = c.ShouldBindJSON(&cu)
err := cu.DeleteExaCustomer()
err := service.DeleteExaCustomer(cu)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("删除失败:%v", err), c)
} else {
......@@ -61,7 +62,7 @@ func DeleteExaCustomer(c *gin.Context) {
func UpdateExaCustomer(c *gin.Context) {
var cu model.ExaCustomer
_ = c.ShouldBindJSON(&cu)
err := cu.UpdateExaCustomer()
err := service.UpdateExaCustomer(&cu)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("更新失败:%v", err), c)
} else {
......@@ -80,7 +81,7 @@ func UpdateExaCustomer(c *gin.Context) {
func GetExaCustomer(c *gin.Context) {
var cu model.ExaCustomer
_ = c.ShouldBindJSON(&cu)
err, customer := cu.GetExaCustomer()
err, customer := service.GetExaCustomer(cu.ID)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("获取失败:%v", err), c)
} else {
......@@ -100,12 +101,10 @@ func GetExaCustomer(c *gin.Context) {
// @Router /customer/getExaCustomerList [post]
func GetExaCustomerList(c *gin.Context) {
claims, _ := c.Get("claims")
waitUse := claims.(*middleware.CustomClaims)
var cu model.ExaCustomer
cu.SysUserAuthorityID = waitUse.AuthorityId
var pageInfo model.PageInfo
waitUse := claims.(*request.CustomClaims)
var pageInfo request.PageInfo
_ = c.ShouldBindJSON(&pageInfo)
err, customerList, total := cu.GetInfoList(pageInfo)
err, customerList, total := service.GetCustomerInfoList(waitUse.AuthorityId, pageInfo)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("创建失败:%v", err), c)
} else {
......
......@@ -4,6 +4,8 @@ import (
"fmt"
"gin-vue-admin/global/response"
"gin-vue-admin/model"
"gin-vue-admin/model/request"
"gin-vue-admin/service"
"gin-vue-admin/utils"
"github.com/gin-gonic/gin"
"strings"
......@@ -36,7 +38,7 @@ func UploadFile(c *gin.Context) {
file.Tag = s[len(s)-1]
file.Key = key
if noSave == "0" {
err = file.Upload()
err = service.Upload(file)
}
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("修改数据库链接失败,%v", err), c)
......@@ -58,7 +60,7 @@ func UploadFile(c *gin.Context) {
func DeleteFile(c *gin.Context) {
var file model.ExaFileUploadAndDownload
_ = c.ShouldBindJSON(&file)
err, f := file.FindFile()
err, f := service.FindFile(file.ID)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("删除失败,%v", err), c)
} else {
......@@ -67,7 +69,7 @@ func DeleteFile(c *gin.Context) {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("删除失败,%v", err), c)
} else {
err = f.DeleteFile()
err = service.DeleteFile(f)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("删除失败,%v", err), c)
} else {
......@@ -86,9 +88,9 @@ func DeleteFile(c *gin.Context) {
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /fileUploadAndDownload/getFileList [post]
func GetFileList(c *gin.Context) {
var pageInfo model.PageInfo
var pageInfo request.PageInfo
_ = c.ShouldBindJSON(&pageInfo)
err, list, total := new(model.ExaFileUploadAndDownload).GetInfoList(pageInfo)
err, list, total := service.GetFileRecordInfoList(pageInfo)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("获取数据失败,%v", err), c)
} else {
......
......@@ -4,6 +4,8 @@ import (
"fmt"
"gin-vue-admin/global/response"
"gin-vue-admin/model"
"gin-vue-admin/model/request"
"gin-vue-admin/service"
"github.com/gin-gonic/gin"
)
......@@ -18,7 +20,7 @@ import (
func CreateApi(c *gin.Context) {
var api model.SysApi
_ = c.ShouldBindJSON(&api)
err := api.CreateApi()
err := service.CreateApi(api)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("创建失败,%v", err), c)
} else {
......@@ -37,7 +39,7 @@ func CreateApi(c *gin.Context) {
func DeleteApi(c *gin.Context) {
var a model.SysApi
_ = c.ShouldBindJSON(&a)
err := a.DeleteApi()
err := service.DeleteApi(a)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("删除失败,%v", err), c)
} else {
......@@ -57,9 +59,9 @@ func DeleteApi(c *gin.Context) {
// @Router /api/getApiList [post]
func GetApiList(c *gin.Context) {
// 此结构体仅本方法使用
var sp model.SearchApiParams
var sp request.SearchApiParams
_ = c.ShouldBindJSON(&sp)
err, list, total := sp.SysApi.GetInfoList(sp.PageInfo, sp.OrderKey, sp.Desc)
err, list, total := service.GetAPIInfoList(sp.SysApi, sp.PageInfo, sp.OrderKey, sp.Desc)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("获取数据失败,%v", err), c)
} else {
......@@ -81,9 +83,9 @@ func GetApiList(c *gin.Context) {
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /api/getApiById [post]
func GetApiById(c *gin.Context) {
var idInfo model.GetById
var idInfo request.GetById
_ = c.ShouldBindJSON(&idInfo)
err, api := new(model.SysApi).GetApiById(idInfo.Id)
err, api := service.GetApiById(idInfo.Id)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("获取数据失败,%v", err), c)
} else {
......@@ -105,7 +107,7 @@ func GetApiById(c *gin.Context) {
func UpdateApi(c *gin.Context) {
var api model.SysApi
_ = c.ShouldBindJSON(&api)
err := api.UpdateApi()
err := service.UpdateApi(api)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("修改数据失败,%v", err), c)
} else {
......@@ -121,7 +123,7 @@ func UpdateApi(c *gin.Context) {
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /api/getAllApis [post]
func GetAllApis(c *gin.Context) {
err, apis := new(model.SysApi).GetAllApis()
err, apis := service.GetAllApis()
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("获取数据失败,%v", err), c)
} else {
......
......@@ -4,6 +4,8 @@ import (
"fmt"
"gin-vue-admin/global/response"
"gin-vue-admin/model"
"gin-vue-admin/model/request"
"gin-vue-admin/service"
"github.com/gin-gonic/gin"
)
......@@ -18,7 +20,7 @@ import (
func CreateAuthority(c *gin.Context) {
var auth model.SysAuthority
_ = c.ShouldBindJSON(&auth)
err, authBack := auth.CreateAuthority()
err, authBack := service.CreateAuthority(&auth)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("创建失败,%v", err), c)
} else {
......@@ -40,7 +42,7 @@ func DeleteAuthority(c *gin.Context) {
var a model.SysAuthority
_ = c.ShouldBindJSON(&a)
//删除角色之前需要判断是否有用户正在使用此角色
err := a.DeleteAuthority()
err := service.DeleteAuthority(a)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("删除失败,%v", err), c)
} else {
......@@ -57,9 +59,9 @@ func DeleteAuthority(c *gin.Context) {
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /authority/getAuthorityList [post]
func GetAuthorityList(c *gin.Context) {
var pageInfo model.PageInfo
var pageInfo request.PageInfo
_ = c.ShouldBindJSON(&pageInfo)
err, list, total := new(model.SysAuthority).GetInfoList(pageInfo)
err, list, total := service.GetAuthorityInfoList(pageInfo)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("获取数据失败,%v", err), c)
} else {
......@@ -83,7 +85,7 @@ func GetAuthorityList(c *gin.Context) {
func SetDataAuthority(c *gin.Context) {
var auth model.SysAuthority
_ = c.ShouldBindJSON(&auth)
err := auth.SetDataAuthority()
err := service.SetDataAuthority(auth)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("设置关联失败,%v", err), c)
} else {
......
......@@ -4,6 +4,7 @@ import (
"fmt"
"gin-vue-admin/global/response"
"gin-vue-admin/model"
"gin-vue-admin/service"
"github.com/gin-gonic/gin"
"os"
)
......@@ -19,7 +20,7 @@ import (
func CreateTemp(c *gin.Context) {
var a model.AutoCodeStruct
_ = c.ShouldBindJSON(&a)
err := a.CreateTemp()
err := service.CreateTemp(a)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("创建失败,%v", err), c)
os.Remove("./ginvueadmin.zip")
......
......@@ -3,7 +3,8 @@ package v1
import (
"fmt"
"gin-vue-admin/global/response"
"gin-vue-admin/model"
"gin-vue-admin/model/request"
"gin-vue-admin/service"
"github.com/gin-gonic/gin"
)
......@@ -16,9 +17,9 @@ import (
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /casbin/UpdateCasbin [post]
func UpdateCasbin(c *gin.Context) {
var cmr model.CasbinInReceive
var cmr request.CasbinInReceive
_ = c.ShouldBindJSON(&cmr)
err := new(model.CasbinModel).UpdateCasbin(cmr.AuthorityId, cmr.CasbinInfos)
err := service.UpdateCasbin(cmr.AuthorityId, cmr.CasbinInfos)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("添加规则失败,%v", err), c)
} else {
......@@ -35,9 +36,9 @@ func UpdateCasbin(c *gin.Context) {
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /casbin/getPolicyPathByAuthorityId [post]
func GetPolicyPathByAuthorityId(c *gin.Context) {
var cmr model.CasbinInReceive
var cmr request.CasbinInReceive
_ = c.ShouldBindJSON(&cmr)
paths := new(model.CasbinModel).GetPolicyPathByAuthorityId(cmr.AuthorityId)
paths := service.GetPolicyPathByAuthorityId(cmr.AuthorityId)
response.Result(response.SUCCESS, gin.H{"paths": paths}, "获取规则成功", c)
}
......
......@@ -4,6 +4,7 @@ import (
"fmt"
"gin-vue-admin/global/response"
"gin-vue-admin/model"
"gin-vue-admin/service"
"github.com/gin-gonic/gin"
)
......@@ -16,10 +17,10 @@ import (
// @Router /jwt/jsonInBlacklist [post]
func JsonInBlacklist(c *gin.Context) {
token := c.Request.Header.Get("x-token")
ModelJwt := model.JwtBlacklist{
modelJwt := model.JwtBlacklist{
Jwt: token,
}
err := ModelJwt.JsonInBlacklist()
err := service.JsonInBlacklist(modelJwt)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("jwt作废失败,%v", err), c)
} else {
......
......@@ -3,8 +3,9 @@ package v1
import (
"fmt"
"gin-vue-admin/global/response"
"gin-vue-admin/middleware"
"gin-vue-admin/model"
"gin-vue-admin/model/request"
"gin-vue-admin/service"
"github.com/gin-gonic/gin"
)
......@@ -17,8 +18,8 @@ import (
// @Router /menu/getMenu [post]
func GetMenu(c *gin.Context) {
claims, _ := c.Get("claims")
waitUse := claims.(*middleware.CustomClaims)
err, menus := new(model.SysMenu).GetMenuTree(waitUse.AuthorityId)
waitUse := claims.(*request.CustomClaims)
err, menus := service.GetMenuTree(waitUse.AuthorityId)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("获取失败,%v", err), c)
} else {
......@@ -35,9 +36,9 @@ func GetMenu(c *gin.Context) {
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /menu/getMenuList [post]
func GetMenuList(c *gin.Context) {
var pageInfo model.PageInfo
var pageInfo request.PageInfo
_ = c.ShouldBindJSON(&pageInfo)
err, menuList, total := new(model.SysBaseMenu).GetInfoList(pageInfo)
err, menuList, total := service.GetInfoList(pageInfo)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("获取数据失败,%v", err), c)
} else {
......@@ -59,9 +60,9 @@ func GetMenuList(c *gin.Context) {
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /menu/addBaseMenu [post]
func AddBaseMenu(c *gin.Context) {
var addMenu model.SysBaseMenu
_ = c.ShouldBindJSON(&addMenu)
err := addMenu.AddBaseMenu()
var menu model.SysBaseMenu
_ = c.ShouldBindJSON(&menu)
err := service.AddBaseMenu(menu)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("添加失败,%v", err), c)
} else {
......@@ -77,7 +78,7 @@ func AddBaseMenu(c *gin.Context) {
// @Success 200 {string} string "{"success":true,"data":{},"msg":"返回成功"}"
// @Router /menu/getBaseMenuTree [post]
func GetBaseMenuTree(c *gin.Context) {
err, menus := new(model.SysBaseMenu).GetBaseMenuTree()
err, menus := service.GetBaseMenuTree()
if err != nil {
response.Result(response.ERROR, gin.H{"menus": menus}, fmt.Sprintf("获取失败,%v", err), c)
} else {
......@@ -95,10 +96,10 @@ func GetBaseMenuTree(c *gin.Context) {
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /menu/addMenuAuthority [post]
func AddMenuAuthority(c *gin.Context) {
var addMenuAuthorityInfo model.AddMenuAuthorityInfo
var addMenuAuthorityInfo request.AddMenuAuthorityInfo
_ = c.ShouldBindJSON(&addMenuAuthorityInfo)
err := new(model.SysMenu).AddMenuAuthority(addMenuAuthorityInfo.Menus, addMenuAuthorityInfo.AuthorityId)
err := service.AddMenuAuthority(addMenuAuthorityInfo.Menus, addMenuAuthorityInfo.AuthorityId)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("添加失败,%v", err), c)
} else {
......@@ -115,9 +116,9 @@ func AddMenuAuthority(c *gin.Context) {
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /menu/GetMenuAuthority [post]
func GetMenuAuthority(c *gin.Context) {
var authorityIdInfo model.AuthorityIdInfo
var authorityIdInfo request.AuthorityIdInfo
_ = c.ShouldBindJSON(&authorityIdInfo)
err, menus := new(model.SysMenu).GetMenuAuthority(authorityIdInfo.AuthorityId)
err, menus := service.GetMenuAuthority(authorityIdInfo.AuthorityId)
if err != nil {
response.Result(response.ERROR, gin.H{"menus": menus}, fmt.Sprintf("添加失败,%v", err), c)
} else {
......@@ -134,9 +135,9 @@ func GetMenuAuthority(c *gin.Context) {
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /menu/deleteBaseMenu [post]
func DeleteBaseMenu(c *gin.Context) {
var idInfo model.GetById
var idInfo request.GetById
_ = c.ShouldBindJSON(&idInfo)
err := new(model.SysBaseMenu).DeleteBaseMenu(idInfo.Id)
err := service.DeleteBaseMenu(idInfo.Id)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("删除失败:%v", err), c)
} else {
......@@ -156,7 +157,7 @@ func DeleteBaseMenu(c *gin.Context) {
func UpdateBaseMenu(c *gin.Context) {
var menu model.SysBaseMenu
_ = c.ShouldBindJSON(&menu)
err := menu.UpdateBaseMenu()
err := service.UpdateBaseMenu(menu)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("修改失败:%v", err), c)
} else {
......@@ -173,9 +174,9 @@ func UpdateBaseMenu(c *gin.Context) {
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /menu/getBaseMenuById [post]
func GetBaseMenuById(c *gin.Context) {
var idInfo model.GetById
var idInfo request.GetById
_ = c.ShouldBindJSON(&idInfo)
err, menu := new(model.SysBaseMenu).GetBaseMenuById(idInfo.Id)
err, menu := service.GetBaseMenuById(idInfo.Id)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("查询失败:%v", err), c)
} else {
......
......@@ -4,6 +4,7 @@ import (
"fmt"
"gin-vue-admin/global/response"
"gin-vue-admin/model"
"gin-vue-admin/service"
"github.com/gin-gonic/gin"
)
......@@ -14,7 +15,7 @@ import (
// @Success 200 {string} string "{"success":true,"data":{},"msg":"返回成功"}"
// @Router /system/getSystemConfig [post]
func GetSystemConfig(c *gin.Context) {
err, config := new(model.System).GetSystemConfig()
err, config := service.GetSystemConfig()
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("获取失败,%v", err), c)
} else {
......@@ -32,7 +33,7 @@ func GetSystemConfig(c *gin.Context) {
func SetSystemConfig(c *gin.Context) {
var sys model.System
_ = c.ShouldBindJSON(&sys)
err := sys.SetSystemConfig()
err := service.SetSystemConfig(sys)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("设置失败,%v", err), c)
} else {
......@@ -51,7 +52,7 @@ func SetSystemConfig(c *gin.Context) {
func ReloadSystem(c *gin.Context) {
var sys model.System
_ = c.ShouldBindJSON(&sys)
err := sys.SetSystemConfig()
err := service.SetSystemConfig(sys)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("设置失败,%v", err), c)
} else {
......
......@@ -6,6 +6,8 @@ import (
"gin-vue-admin/global/response"
"gin-vue-admin/middleware"
"gin-vue-admin/model"
"gin-vue-admin/model/request"
"gin-vue-admin/service"
"gin-vue-admin/utils"
"github.com/dchest/captcha"
"github.com/dgrijalva/jwt-go"
......@@ -27,10 +29,10 @@ const (
// @Success 200 {string} string "{"success":true,"data":{},"msg":"注册成功"}"
// @Router /base/register [post]
func Register(c *gin.Context) {
var R model.RegisterStruct
var R request.RegisterStruct
_ = c.ShouldBindJSON(&R)
user := &model.SysUser{Username: R.Username, NickName: R.NickName, Password: R.Password, HeaderImg: R.HeaderImg, AuthorityId: R.AuthorityId}
err, user := user.Register()
err, user := service.Register(user)
if err != nil {
response.Result(response.ERROR, gin.H{
"user": user,
......@@ -49,11 +51,11 @@ func Register(c *gin.Context) {
// @Success 200 {string} string "{"success":true,"data":{},"msg":"登陆成功"}"
// @Router /base/login [post]
func Login(c *gin.Context) {
var L model.RegisterAndLoginStruct
var L request.RegisterAndLoginStruct
_ = c.ShouldBindJSON(&L)
if captcha.VerifyString(L.CaptchaId, L.Captcha) {
U := &model.SysUser{Username: L.Username, Password: L.Password}
if err, user := U.Login(); err != nil {
if err, user := service.Login(U); err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("用户名密码错误或%v", err), c)
} else {
tokenNext(c, *user)
......@@ -69,7 +71,7 @@ func tokenNext(c *gin.Context, user model.SysUser) {
j := &middleware.JWT{
[]byte(global.GVA_CONFIG.JWT.SigningKey), // 唯一签名
}
clams := middleware.CustomClaims{
clams := request.CustomClaims{
UUID: user.UUID,
ID: user.ID,
NickName: user.NickName,
......@@ -87,9 +89,9 @@ func tokenNext(c *gin.Context, user model.SysUser) {
if global.GVA_CONFIG.System.UseMultipoint {
var loginJwt model.JwtBlacklist
loginJwt.Jwt = token
err, jwtStr := loginJwt.GetRedisJWT(user.Username)
err, jwtStr := service.GetRedisJWT(user.Username)
if err == redis.Nil {
err2 := loginJwt.SetRedisJWT(user.Username)
err2 := service.SetRedisJWT(loginJwt, user.Username)
if err2 != nil {
response.Result(response.ERROR, gin.H{}, "设置登录状态失败", c)
} else {
......@@ -98,13 +100,13 @@ func tokenNext(c *gin.Context, user model.SysUser) {
} else if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("%v", err), c)
} else {
var blackjWT model.JwtBlacklist
blackjWT.Jwt = jwtStr
err3 := blackjWT.JsonInBlacklist()
var blackJWT model.JwtBlacklist
blackJWT.Jwt = jwtStr
err3 := service.JsonInBlacklist(blackJWT)
if err3 != nil {
response.Result(response.ERROR, gin.H{}, "jwt作废失败", c)
} else {
err2 := loginJwt.SetRedisJWT(user.Username)
err2 := service.SetRedisJWT(loginJwt, user.Username)
if err2 != nil {
response.Result(response.ERROR, gin.H{}, "设置登录状态失败", c)
} else {
......@@ -126,10 +128,10 @@ func tokenNext(c *gin.Context, user model.SysUser) {
// @Success 200 {string} string "{"success":true,"data":{},"msg":"修改成功"}"
// @Router /user/changePassword [put]
func ChangePassword(c *gin.Context) {
var params model.ChangePasswordStutrc
var params request.ChangePasswordStruct
_ = c.ShouldBindJSON(&params)
U := &model.SysUser{Username: params.Username, Password: params.Password}
if err, _ := U.ChangePassword(params.NewPassword); err != nil {
if err, _ := service.ChangePassword(U, params.NewPassword); err != nil {
response.Result(response.ERROR, gin.H{}, "修改失败,请检查用户名密码", c)
} else {
response.Result(response.SUCCESS, gin.H{}, "修改成功", c)
......@@ -153,7 +155,7 @@ func UploadHeaderImg(c *gin.Context) {
claims, _ := c.Get("claims")
//获取头像文件
// 这里我们通过断言获取 claims内的所有内容
waitUse := claims.(*middleware.CustomClaims)
waitUse := claims.(*request.CustomClaims)
uuid := waitUse.UUID
_, header, err := c.Request.FormFile("headerImg")
//便于找到用户 以后从jwt中取
......@@ -166,7 +168,7 @@ func UploadHeaderImg(c *gin.Context) {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("接收返回值失败,%v", err), c)
} else {
//修改数据库后得到修改后的user并且返回供前端使用
err, user := new(model.SysUser).UploadHeaderImg(uuid, filePath)
err, user := service.UploadHeaderImg(uuid, filePath)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("修改数据库链接失败,%v", err), c)
} else {
......@@ -185,9 +187,9 @@ func UploadHeaderImg(c *gin.Context) {
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /user/getUserList [post]
func GetUserList(c *gin.Context) {
var pageInfo model.PageInfo
var pageInfo request.PageInfo
_ = c.ShouldBindJSON(&pageInfo)
err, list, total := new(model.SysUser).GetInfoList(pageInfo)
err, list, total := service.GetUserInfoList(pageInfo)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("获取数据失败,%v", err), c)
} else {
......@@ -209,9 +211,9 @@ func GetUserList(c *gin.Context) {
// @Success 200 {string} string "{"success":true,"data":{},"msg":"修改成功"}"
// @Router /user/setUserAuthority [post]
func SetUserAuthority(c *gin.Context) {
var sua model.SetUserAuth
var sua request.SetUserAuth
_ = c.ShouldBindJSON(&sua)
err := new(model.SysUser).SetUserAuthority(sua.UUID, sua.AuthorityId)
err := service.SetUserAuthority(sua.UUID, sua.AuthorityId)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("修改失败,%v", err), c)
} else {
......
......@@ -4,6 +4,7 @@ import (
"fmt"
"gin-vue-admin/global/response"
"gin-vue-admin/model"
"gin-vue-admin/service"
"github.com/gin-gonic/gin"
)
......@@ -16,7 +17,7 @@ import (
func CreateWorkFlow(c *gin.Context) {
var wk model.SysWorkflow
_ = c.ShouldBindJSON(&wk)
err := wk.Create()
err := service.Create(wk)
if err != nil {
response.Result(response.ERROR, gin.H{}, fmt.Sprintf("获取失败:%v", err), c)
} else {
......
......@@ -2,7 +2,8 @@ package middleware
import (
"gin-vue-admin/global/response"
"gin-vue-admin/model"
"gin-vue-admin/model/request"
"gin-vue-admin/service"
"github.com/gin-gonic/gin"
)
......@@ -10,14 +11,14 @@ import (
func CasbinHandler() gin.HandlerFunc {
return func(c *gin.Context) {
claims, _ := c.Get("claims")
waitUse := claims.(*CustomClaims)
waitUse := claims.(*request.CustomClaims)
//获取请求的URI
obj := c.Request.URL.RequestURI()
//获取请求方法
act := c.Request.Method
//获取用户的角色
sub := waitUse.AuthorityId
e := model.Casbin()
e := service.Casbin()
//判断策略中是否存在
if e.Enforce(sub, obj, act) {
c.Next()
......
......@@ -5,9 +5,10 @@ import (
"gin-vue-admin/global"
"gin-vue-admin/global/response"
"gin-vue-admin/model"
"gin-vue-admin/model/request"
"gin-vue-admin/service"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
uuid "github.com/satori/go.uuid"
"time"
)
......@@ -15,7 +16,7 @@ func JWTAuth() gin.HandlerFunc {
return func(c *gin.Context) {
// 我们这里jwt鉴权取头部信息 x-token 登录时回返回token信息 这里前端需要把token存储到cookie或者本地localSstorage中 不过需要跟后端协商过期时间 可以约定刷新令牌或者重新登录
token := c.Request.Header.Get("x-token")
ModelToken := model.JwtBlacklist{
modelToken := model.JwtBlacklist{
Jwt: token,
}
if token == "" {
......@@ -25,7 +26,7 @@ func JWTAuth() gin.HandlerFunc {
c.Abort()
return
}
if ModelToken.IsBlacklist(token) {
if service.IsBlacklist(token,modelToken) {
response.Result(response.ERROR, gin.H{
"reload": true,
}, "您的帐户异地登陆或令牌失效", c)
......@@ -65,13 +66,7 @@ var (
TokenInvalid error = errors.New("Couldn't handle this token:")
)
type CustomClaims struct {
UUID uuid.UUID
ID uint
NickName string
AuthorityId string
jwt.StandardClaims
}
func NewJWT() *JWT {
return &JWT{
......@@ -80,14 +75,14 @@ func NewJWT() *JWT {
}
//创建一个token
func (j *JWT) CreateToken(claims CustomClaims) (string, error) {
func (j *JWT) CreateToken(claims request. CustomClaims) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(j.SigningKey)
}
//解析 token
func (j *JWT) ParseToken(tokenString string) (*CustomClaims, error) {
token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (i interface{}, e error) {
func (j *JWT) ParseToken(tokenString string) (*request.CustomClaims, error) {
token, err := jwt.ParseWithClaims(tokenString, &request.CustomClaims{}, func(token *jwt.Token) (i interface{}, e error) {
return j.SigningKey, nil
})
if err != nil {
......@@ -105,7 +100,7 @@ func (j *JWT) ParseToken(tokenString string) (*CustomClaims, error) {
}
}
if token != nil {
if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
if claims, ok := token.Claims.(*request.CustomClaims); ok && token.Valid {
return claims, nil
}
return nil, TokenInvalid
......@@ -122,13 +117,13 @@ func (j *JWT) RefreshToken(tokenString string) (string, error) {
jwt.TimeFunc = func() time.Time {
return time.Unix(0, 0)
}
token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
token, err := jwt.ParseWithClaims(tokenString, &request.CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
return j.SigningKey, nil
})
if err != nil {
return "", err
}
if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
if claims, ok := token.Claims.(*request.CustomClaims); ok && token.Valid {
jwt.TimeFunc = time.Now
claims.StandardClaims.ExpiresAt = time.Now().Add(1 * time.Hour).Unix()
return j.CreateToken(*claims)
......
package model
import (
"gin-vue-admin/global"
"github.com/jinzhu/gorm"
)
......@@ -22,76 +21,4 @@ type ExaFileChunk struct {
ExaFileId uint
FileChunkNumber int
FileChunkPath string
}
// @title FileCreateComplete
// @description file creation, 文件合成完成
// @auth (2020/04/05 20:22 )
// @param FileMd5 string
// @param FileName string
// @param FilePath string
// @return error
func (f *ExaFile) FileCreateComplete(FileMd5 string, FileName string, FilePath string) error {
var file ExaFile
upDateFile := make(map[string]interface{})
upDateFile["FilePath"] = FilePath
upDateFile["IsFinish"] = true
err := global.GVA_DB.Where("file_md5 = ? AND file_name = ?", FileMd5, FileName).First(&file).Updates(upDateFile).Error
return err
}
// @title FindOrCreateFile
// @description Check your file if it does not exist, or return current slice of the file
// 上传文件时检测当前文件属性,如果没有文件则创建,有则返回文件的当前切片
// @auth (2020/04/05 20:22 )
// @param FileMd5 string
// @param FileName string
// @param ChunkTotal int
// @return err error
// @return file ExaFile
func (f *ExaFile) FindOrCreateFile(FileMd5 string, FileName string, ChunkTotal int) (err error, file ExaFile) {
var cfile ExaFile
cfile.FileMd5 = FileMd5
cfile.FileName = FileName
cfile.ChunkTotal = ChunkTotal
notHaveSameMd5Finish := global.GVA_DB.Where("file_md5 = ? AND is_finish = ?", FileMd5, true).First(&file).RecordNotFound()
if notHaveSameMd5Finish {
err = global.GVA_DB.Where("file_md5 = ? AND file_name = ?", FileMd5, FileName).Preload("ExaFileChunk").FirstOrCreate(&file, cfile).Error
return err, file
} else {
cfile.IsFinish = true
cfile.FilePath = file.FilePath
err = global.GVA_DB.Create(&cfile).Error
return err, cfile
}
}
// @title CreateFileChunk
// @description create a chunk of the file, 创建文件切片记录
// @auth (2020/04/05 20:22 )
// @param FileChunkPath string
// @param FileChunkNumber int
// @return error
func (f *ExaFile) CreateFileChunk(FileChunkPath string, FileChunkNumber int) error {
var chunk ExaFileChunk
chunk.FileChunkPath = FileChunkPath
chunk.ExaFileId = f.ID
chunk.FileChunkNumber = FileChunkNumber
err := global.GVA_DB.Create(&chunk).Error
return err
}
// @title DeleteFileChunk
// @description delete a chuck of the file, 删除文件切片记录
// @auth (2020/04/05 20:22 )
// @param FileMd5 string
// @param FileName string
// @param FilePath string
// @return error
func (f *ExaFile) DeleteFileChunk(fileMd5 string, fileName string, filePath string) error {
var chunks []ExaFileChunk
var file ExaFile
err := global.GVA_DB.Where("file_md5 = ? AND file_name = ?", fileMd5, fileName).First(&file).Update("IsFinish", true).Update("file_path", filePath).Error
err = global.GVA_DB.Where("exa_file_id = ?", file.ID).Delete(&chunks).Unscoped().Error
return err
}
}
\ No newline at end of file
package model
import (
"gin-vue-admin/global"
"github.com/jinzhu/gorm"
)
......@@ -12,71 +11,4 @@ type ExaCustomer struct {
SysUserID uint `json:"sysUserId"`
SysUserAuthorityID string `json:"sysUserAuthorityID"`
SysUser SysUser `json:"sysUser"`
}
// @title CreateExaCustomer
// @description create a customer, 创建用户
// @auth (2020/04/05 20:22 )
// @return err error
func (e *ExaCustomer) CreateExaCustomer() (err error) {
err = global.GVA_DB.Create(e).Error
return err
}
// @title DeleteFileChunk
// @description delete a customer, 删除用户
// @auth (2020/04/05 20:22 )
// @return error
func (e *ExaCustomer) DeleteExaCustomer() (err error) {
err = global.GVA_DB.Delete(e).Error
return err
}
// @title UpdateExaCustomer
// @description update a customer, 更新用户
// @auth (2020/04/05 20:22 )
// @return error
func (e *ExaCustomer) UpdateExaCustomer() (err error) {
err = global.GVA_DB.Save(e).Error
return err
}
// @title GetExaCustomer
// @description get the info of a costumer , 获取用户信息
// @auth (2020/04/05 20:22 )
// @return error
// @return customer ExaCustomer
func (e *ExaCustomer) GetExaCustomer() (err error, customer ExaCustomer) {
err = global.GVA_DB.Where("id = ?", e.ID).First(&customer).Error
return
}
// @title GetInfoList
// @description get customer list by pagination, 分页获取用户列表
// @auth (2020/04/05 20:22 )
// @param info PageInfo
// @return error
func (e *ExaCustomer) GetInfoList(info PageInfo) (err error, list interface{}, total int) {
limit := info.PageSize
offset := info.PageSize * (info.Page - 1)
db := global.GVA_DB
if err != nil {
return
} else {
var a SysAuthority
a.AuthorityId = e.SysUserAuthorityID
err, auth := a.GetAuthorityInfo()
var dataId []string
for _, v := range auth.DataAuthorityId {
dataId = append(dataId, v.AuthorityId)
}
var CustomerList []ExaCustomer
err = db.Where("sys_user_authority_id in (?)", dataId).Find(&CustomerList).Count(&total).Error
if err != nil {
return err, CustomerList, total
} else {
err = db.Limit(limit).Offset(offset).Preload("SysUser").Where("sys_user_authority_id in (?)", dataId).Find(&CustomerList).Error
}
return err, CustomerList, total
}
}
}
\ No newline at end of file
package model
import (
"gin-vue-admin/global"
"github.com/jinzhu/gorm"
)
......@@ -11,52 +10,4 @@ type ExaFileUploadAndDownload struct {
Url string `json:"url"`
Tag string `json:"tag"`
Key string `json:"key"`
}
// @title Upload
// @description 删除文件切片记录
// @auth (2020/04/05 20:22 )
// @return error
func (f *ExaFileUploadAndDownload) Upload() error {
err := global.GVA_DB.Create(f).Error
return err
}
// @title DeleteFile
// @description 删除文件切片记录
// @auth (2020/04/05 20:22 )
// @return error
func (f *ExaFileUploadAndDownload) DeleteFile() error {
err := global.GVA_DB.Where("id = ?", f.ID).Unscoped().Delete(f).Error
return err
}
// @title FindFile
// @description 删除文件切片记录
// @auth (2020/04/05 20:22 )
// @return error
func (f *ExaFileUploadAndDownload) FindFile() (error, ExaFileUploadAndDownload) {
var file ExaFileUploadAndDownload
err := global.GVA_DB.Where("id = ?", f.ID).First(&file).Error
return err, file
}
// @title GetInfoList
// @description 分页获取数据
// @auth (2020/04/05 20:22 )
// @param info PageInfo
// @return err error
// @return list error
// @return total error
func (f *ExaFileUploadAndDownload) GetInfoList(info PageInfo) (err error, list interface{}, total int) {
limit := info.PageSize
offset := info.PageSize * (info.Page - 1)
db := global.GVA_DB
if err != nil {
return
} else {
var fileLists []ExaFileUploadAndDownload
err = db.Limit(limit).Offset(offset).Order("updated_at desc").Find(&fileLists).Error
return err, fileLists, total
}
}
}
\ No newline at end of file
package model
import uuid "github.com/satori/go.uuid"
/****************************** common start ****************************************************/
// 分页公用入参结构体
type PageInfo struct {
Page int `json:"page"`
PageSize int `json:"pageSize"`
}
//根据id查询结构体
type GetById struct {
Id float64 `json:"id"`
}
/****************************** common end ****************************************************/
/****************************** api start ****************************************************/
//api分页条件查询及排序结构体
type SearchApiParams struct {
SysApi
PageInfo
OrderKey string `json:"orderKey"`
Desc bool `json:"desc"`
}
/****************************** api end ****************************************************/
/****************************** Authority start ****************************************************/
// 添加角色和menu关系
type AddMenuAuthorityInfo struct {
Menus []SysBaseMenu
AuthorityId string
}
// 根据角色id获取角色
type AuthorityIdInfo struct {
AuthorityId string
}
/****************************** Authority end ****************************************************/
/****************************** user start ****************************************************/
// 修改密码结构体
type ChangePasswordStutrc struct {
Username string `json:"username"`
Password string `json:"password"`
NewPassword string `json:"newPassword"`
}
// 设置用户权限
type SetUserAuth struct {
UUID uuid.UUID `json:"uuid"`
AuthorityId string `json:"authorityId"`
}
/****************************** user end ****************************************************/
package request
// Paging common input parameter structure
type PageInfo struct {
Page int `json:"page"`
PageSize int `json:"pageSize"`
}
// Find by id structure
type GetById struct {
Id float64 `json:"id"`
}
package request
import (
"github.com/dgrijalva/jwt-go"
uuid "github.com/satori/go.uuid"
)
// Custom claims structure
type CustomClaims struct {
UUID uuid.UUID
ID uint
NickName string
AuthorityId string
jwt.StandardClaims
}
\ No newline at end of file
package request
import "gin-vue-admin/model"
//api分页条件查询及排序结构体
type SearchApiParams struct {
model.SysApi
PageInfo
OrderKey string `json:"orderKey"`
Desc bool `json:"desc"`
}
package request
// Casbin info structure
type CasbinInfo struct {
Path string `json:"path"`
Method string `json:"method"`
}
// Casbin structure for input parameters
type CasbinInReceive struct {
AuthorityId string `json:"authorityId"`
CasbinInfos []CasbinInfo `json:"casbinInfos"`
}
package request
import "gin-vue-admin/model"
// Add menu authority info structure
type AddMenuAuthorityInfo struct {
Menus []model.SysBaseMenu
AuthorityId string
}
// Get role by id structure
type AuthorityIdInfo struct {
AuthorityId string
}
\ No newline at end of file
package request
import uuid "github.com/satori/go.uuid"
// User register structure
type RegisterStruct struct {
Username string `json:"userName"`
Password string `json:"passWord"`
NickName string `json:"nickName" gorm:"default:'QMPlusUser'"`
HeaderImg string `json:"headerImg" gorm:"default:'http://www.henrongyi.top/avatar/lufu.jpg'"`
AuthorityId string `json:"authorityId" gorm:"default:888"`
}
// User login structure
type RegisterAndLoginStruct struct {
Username string `json:"username"`
Password string `json:"password"`
Captcha string `json:"captcha"`
CaptchaId string `json:"captchaId"`
}
// Modify password structure
type ChangePasswordStruct struct {
Username string `json:"username"`
Password string `json:"password"`
NewPassword string `json:"newPassword"`
}
// Modify user's auth structure
type SetUserAuth struct {
UUID uuid.UUID `json:"uuid"`
AuthorityId string `json:"authorityId"`
}
\ No newline at end of file
package model
import (
"gin-vue-admin/global"
"github.com/jinzhu/gorm"
"github.com/pkg/errors"
)
type SysApi struct {
......@@ -12,135 +10,4 @@ type SysApi struct {
Description string `json:"description"`
ApiGroup string `json:"apiGroup"`
Method string `json:"method" gorm:"default:'POST'"`
}
type CreateApiParams struct {
Path string `json:"path"`
Description string `json:"description"`
}
type DeleteApiParams struct {
ID uint `json:"id"`
}
// @title CreateApi
// @description create base apis, 新增基础api
// @auth (2020/04/05 20:22 )
// @param FileMd5 string
// @param FileName string
// @param FilePath string
// @return error
func (a *SysApi) CreateApi() (err error) {
findOne := global.GVA_DB.Where("path = ?", a.Path).Find(&SysApi{}).Error
if findOne == nil {
return errors.New("存在相同api")
} else {
err = global.GVA_DB.Create(a).Error
}
return err
}
// @title DeleteApi
// @description delete base apis, 删除基础api
// @auth (2020/04/05 20:22 )
// @return error
func (a *SysApi) DeleteApi() (err error) {
err = global.GVA_DB.Delete(a).Error
new(CasbinModel).ClearCasbin(1, a.Path)
return err
}
// @title UpdateApi
// @description update a base api, update api
// @auth (2020/04/05 20:22 )
// @return error
func (a *SysApi) UpdateApi() (err error) {
var oldA SysApi
flag := global.GVA_DB.Where("path = ?", a.Path).Find(&SysApi{}).RecordNotFound()
if !flag {
return errors.New("存在相同api路径")
}
err = global.GVA_DB.Where("id = ?", a.ID).First(&oldA).Error
if err != nil {
return err
} else {
err = new(CasbinModel).UpdateCasbinApi(oldA.Path, a.Path)
if err != nil {
return err
} else {
err = global.GVA_DB.Save(a).Error
}
}
return err
}
// @title GetApiById
// @description get the apis of the selected user, 获取选中角色所拥有的api
// @auth (2020/04/05 20:22 )
// @param id float64
// @return error
func (a *SysApi) GetApiById(id float64) (err error, api SysApi) {
err = global.GVA_DB.Where("id = ?", id).First(&api).Error
return
}
// @title GetAllApis
// @description get all apis, 获取所有的api
// @auth (2020/04/05 20:22 )
// @return err error
// @return apis []SysApi
func (a *SysApi) GetAllApis() (err error, apis []SysApi) {
err = global.GVA_DB.Find(&apis).Error
return
}
// @title GetInfoList
// @description get apis by pagination, 分页获取数据
// @auth (2020/04/05 20:22 )
// @param info PageInfo
// @return err error
// @return list interface{}
// @return total int
func (a *SysApi) GetInfoList(info PageInfo, Order string, Desc bool) (err error, list interface{}, total int) {
limit := info.PageSize
offset := info.PageSize * (info.Page - 1)
db := global.GVA_DB
if err != nil {
return
} else {
var apiList []SysApi
if a.Path != "" {
db = db.Where("path LIKE ?", "%"+a.Path+"%")
}
if a.Description != "" {
db = db.Where("description LIKE ?", "%"+a.Description+"%")
}
if a.Method != "" {
db = db.Where("method = ?", a.Method)
}
err = db.Find(&apiList).Count(&total).Error
if err != nil {
return err, apiList, total
} else {
db = db.Limit(limit).Offset(offset)
if Order != "" {
var OrderStr string
if Desc {
OrderStr = Order + " desc"
} else {
OrderStr = Order
}
err = db.Order(OrderStr, true).Find(&apiList).Error
} else {
err = db.Order("api_group", true).Find(&apiList).Error
}
}
return err, apiList, total
}
}
}
\ No newline at end of file
package model
import (
"gin-vue-admin/global"
"github.com/pkg/errors"
"time"
)
......@@ -16,128 +14,4 @@ type SysAuthority struct {
DataAuthorityId []SysAuthority `json:"dataAuthorityId" gorm:"many2many:sys_data_authority_id;association_jointable_foreignkey:data_authority_id"`
Children []SysAuthority `json:"children"`
SysBaseMenus []SysBaseMenu `json:"menus" gorm:"many2many:sys_authority_menus;"`
}
// @title CreateAuthority
// @description create authority, 创建一个权限
// @auth (2020/04/05 20:22 )
// @param FileMd5 string
// @param FileName string
// @param FilePath string
// @return error
func (a *SysAuthority) CreateAuthority() (err error, authority *SysAuthority) {
err = global.GVA_DB.Create(a).Error
return err, a
}
// @title DeleteAuthority
// @description 删除文件切片记录
// @auth (2020/04/05 20:22 )
// @param FileMd5 string
// @param FileName string
// @param FilePath string
// @return error
// 删除角色
func (a *SysAuthority) DeleteAuthority() (err error) {
err = global.GVA_DB.Where("authority_id = ?", a.AuthorityId).Find(&SysUser{}).Error
if err == nil {
err = errors.New("此角色有用户正在使用禁止删除")
return
}
err = global.GVA_DB.Where("parent_id = ?", a.AuthorityId).Find(&SysAuthority{}).Error
if err == nil {
err = errors.New("此角色存在子角色不允许删除")
return
}
db := global.GVA_DB.Preload("SysBaseMenus").Where("authority_id = ?", a.AuthorityId).First(a).Unscoped().Delete(a)
if len(a.SysBaseMenus) > 0 {
err = db.Association("SysBaseMenus").Delete(a.SysBaseMenus).Error
} else {
err = db.Error
}
new(CasbinModel).ClearCasbin(0, a.AuthorityId)
return err
}
// @title GetInfoList
// @description 删除文件切片记录
// @auth (2020/04/05 20:22 )
// @param FileMd5 string
// @param FileName string
// @param FilePath string
// @return error
// 分页获取数据
func (a *SysAuthority) GetInfoList(info PageInfo) (err error, list interface{}, total int) {
limit := info.PageSize
offset := info.PageSize * (info.Page - 1)
db := global.GVA_DB
if err != nil {
return
} else {
var authority []SysAuthority
err = db.Limit(limit).Offset(offset).Preload("DataAuthorityId").Where("parent_id = 0").Find(&authority).Error
if len(authority) > 0 {
for k, _ := range authority {
err = findChildrenAuthority(&authority[k])
}
}
return err, authority, total
}
}
// @title findChildrenAuthority
// @description 删除文件切片记录
// @auth (2020/04/05 20:22 )
// @param FileMd5 string
// @param FileName string
// @param FilePath string
// @return error
func findChildrenAuthority(authority *SysAuthority) (err error) {
err = global.GVA_DB.Preload("DataAuthorityId").Where("parent_id = ?", authority.AuthorityId).Find(&authority.Children).Error
if len(authority.Children) > 0 {
for k, _ := range authority.Children {
err = findChildrenAuthority(&authority.Children[k])
}
}
return err
}
// @title SetDataAuthority
// @description 删除文件切片记录
// @auth (2020/04/05 20:22 )
// @param FileMd5 string
// @param FileName string
// @param FilePath string
// @return error
func (a *SysAuthority) SetDataAuthority() error {
var s SysAuthority
global.GVA_DB.Preload("DataAuthorityId").First(&s, "authority_id = ?", a.AuthorityId)
err := global.GVA_DB.Model(&s).Association("DataAuthorityId").Replace(&a.DataAuthorityId).Error
return err
}
// @title SetMuneAuthority
// @description 删除文件切片记录
// @auth (2020/04/05 20:22 )
// @param FileMd5 string
// @param FileName string
// @param FilePath string
// @return error
func (a *SysAuthority) SetMuneAuthority() error {
var s SysAuthority
global.GVA_DB.Preload("SysBaseMenus").First(&s, "authority_id = ?", a.AuthorityId)
err := global.GVA_DB.Model(&s).Association("SysBaseMenus").Replace(&a.SysBaseMenus).Error
return err
}
// @title GetAuthorityInfo
// @description 删除文件切片记录
// @auth (2020/04/05 20:22 )
// @param FileMd5 string
// @param FileName string
// @param FilePath string
// @return error
func (a *SysAuthority) GetAuthorityInfo() (err error, sa SysAuthority) {
err = global.GVA_DB.Preload("DataAuthorityId").Where("authority_id = ?", a.AuthorityId).First(&sa).Error
return err, sa
}
}
\ No newline at end of file
package model
import (
"gin-vue-admin/global"
)
type SysMenu struct {
SysBaseMenu
MenuId string `json:"menuId"`
AuthorityId string `json:"-"`
Children []SysMenu `json:"children"`
}
// @title AddMenuAuthority
// @description 为角色增加menu树
// @auth (2020/04/05 20:22 )
// @param menus []SysBaseMenu
// @param authorityId string
// @return error
func (m *SysMenu) AddMenuAuthority(menus []SysBaseMenu, authorityId string) (err error) {
var auth SysAuthority
auth.AuthorityId = authorityId
auth.SysBaseMenus = menus
err = auth.SetMuneAuthority()
return err
}
// @title GetMenuAuthority
// @description 查看当前角色树
// @auth (2020/04/05 20:22 )
// @param authorityId string
// @return err error
// @return menus []SysBaseMenu
func (m *SysMenu) GetMenuAuthority(authorityId string) (err error, menus []SysMenu) {
SQLstatement := "SELECT authority_menu.created_at,authority_menu.updated_at,authority_menu.deleted_at,authority_menu.menu_level,authority_menu.parent_id,authority_menu.path,authority_menu.`name`,authority_menu.hidden,authority_menu.component,authority_menu.title,authority_menu.icon,authority_menu.sort,authority_menu.menu_id,authority_menu.authority_id FROM authority_menu WHERE authority_menu.authority_id = ?"
err = global.GVA_DB.Raw(SQLstatement, authorityId).Scan(&menus).Error
return err, menus
}
// @title GetMenuTree
// @description 获取动态菜单树
// @auth (2020/04/05 20:22 )
// @param authorityId string
// @return err error
// @return menus []SysMenu
func (m *SysMenu) GetMenuTree(authorityId string) (err error, menus []SysMenu) {
SQLstatement := "SELECT authority_menu.created_at,authority_menu.updated_at,authority_menu.deleted_at,authority_menu.menu_level,authority_menu.parent_id,authority_menu.path,authority_menu.`name`,authority_menu.hidden,authority_menu.component,authority_menu.title,authority_menu.icon,authority_menu.sort,authority_menu.menu_id,authority_menu.authority_id FROM authority_menu WHERE authority_menu.authority_id = ? AND authority_menu.parent_id = ?"
err = global.GVA_DB.Raw(SQLstatement, authorityId, 0).Scan(&menus).Error
for i := 0; i < len(menus); i++ {
err = getChildrenList(&menus[i], SQLstatement)
}
return err, menus
}
// @title getChildrenList
// @description 获取子菜单
// @auth (2020/04/05 20:22 )
// @param menu *SysMenu
// @param SQLstatement string
// @return err error
func getChildrenList(menu *SysMenu, SQLstatement string) (err error) {
err = global.GVA_DB.Raw(SQLstatement, menu.AuthorityId, menu.MenuId).Scan(&menu.Children).Error
for i := 0; i < len(menu.Children); i++ {
err = getChildrenList(&menu.Children[i], SQLstatement)
}
return err
}
}
\ No newline at end of file
package model
import (
"gin-vue-admin/utils"
"html/template"
"os"
)
// 初始版本自动化代码工具
type AutoCodeStruct struct {
StructName string `json:"structName"`
......@@ -19,140 +13,4 @@ type Field struct {
FieldType string `json:"fieldType"`
FieldJson string `json:"fieldJson"`
ColumnName string `json:"columnName"`
}
// @title CreateTemp
// @description 函数的详细描述
// @auth (2020/04/05 20:22 )
// @return err error
func (a *AutoCodeStruct) CreateTemp() (err error) {
basePath := "./resource/template"
modelTmpl, err := template.ParseFiles(basePath + "/te/model.go.tpl")
if err != nil {
return err
}
apiTmpl, err := template.ParseFiles(basePath + "/te/api.go.tpl")
if err != nil {
return err
}
routerTmpl, err := template.ParseFiles(basePath + "/te/router.go.tpl")
if err != nil {
return err
}
feapiTmpl, err := template.ParseFiles(basePath + "/fe/api.js.tpl")
if err != nil {
return err
}
readmeTmpl, err := template.ParseFiles(basePath + "/readme.txt.tpl")
if err != nil {
return err
}
//自动化总目录
_autoCode := "./autoCode/"
//自动化后台代码目录
_te := "./autoCode/te/"
_dir := _te + a.PackageName
_modeldir := _te + a.PackageName + "/model"
_apidir := _te + a.PackageName + "/api"
_routerdir := _te + a.PackageName + "/router"
//自动化前台代码目录
_fe := "./autoCode/fe/"
_fe_dir := _fe + a.PackageName
_fe_apidir := _fe + a.PackageName + "/api"
err = createDir(_autoCode, _te, _dir, _modeldir, _apidir, _routerdir, _fe, _fe_dir, _fe_apidir)
if err != nil {
return err
}
model, err := os.OpenFile(_te+a.PackageName+"/model/model.go", os.O_CREATE|os.O_WRONLY, 0755)
if err != nil {
return err
}
api, err := os.OpenFile(_te+a.PackageName+"/api/api.go", os.O_CREATE|os.O_WRONLY, 0755)
if err != nil {
return err
}
router, err := os.OpenFile(_te+a.PackageName+"/router/router.go", os.O_CREATE|os.O_WRONLY, 0755)
if err != nil {
return err
}
feapi, err := os.OpenFile(_fe+a.PackageName+"/api/api.js", os.O_CREATE|os.O_WRONLY, 0755)
if err != nil {
return err
}
readme, err := os.OpenFile(_autoCode+"readme.txt", os.O_CREATE|os.O_WRONLY, 0755)
if err != nil {
return err
}
// 生成代码
{
err = modelTmpl.Execute(model, a)
if err != nil {
return err
}
err = apiTmpl.Execute(api, a)
if err != nil {
return err
}
err = routerTmpl.Execute(router, a)
if err != nil {
return err
}
err = feapiTmpl.Execute(feapi, a)
if err != nil {
return err
}
err = readmeTmpl.Execute(readme, a)
if err != nil {
return err
}
}
_ = model.Close()
_ = api.Close()
_ = router.Close()
_ = feapi.Close()
_ = readme.Close()
fileList := []string{
_te + a.PackageName + "/model/model.go",
_te + a.PackageName + "/api/api.go",
_te + a.PackageName + "/router/router.go",
_fe + a.PackageName + "/api/api.js",
_autoCode + "readme.txt",
}
err = utils.ZipFiles("./ginvueadmin.zip", fileList, ".", ".")
if err != nil {
return err
}
err = os.RemoveAll(_autoCode)
if err != nil {
return err
}
return nil
}
// @title createDir
// @description 批量创建文件夹
// @auth (2020/04/05 20:22 )
// @param dirs string
// @return err error
func createDir(dirs ...string) (err error) {
for _, v := range dirs {
exist, err := utils.PathExists(v)
if err != nil {
//log.L.Info(fmt.Sprintf("get dir error![%v]\n", err))
return err
}
if exist {
//log.L.Info(fmt.Sprintf("has dir![%v]\n"+_dir))
} else {
//log.L.Info(fmt.Sprintf("no dir![%v]\n"+_dir))
// 创建文件夹
err = os.Mkdir(v, os.ModePerm)
if err != nil {
//log.L.Error(fmt.Sprintf("mkdir error![%v]\n",err))
} else {
//log.L.Info("mkdir success!\n")
}
}
}
return err
}
}
\ No newline at end of file
package model
import (
"fmt"
"gin-vue-admin/global"
"github.com/jinzhu/gorm"
"github.com/pkg/errors"
)
type SysBaseMenu struct {
......@@ -24,118 +21,4 @@ type SysBaseMenu struct {
type Meta struct {
Title string `json:"title"`
Icon string `json:"icon"`
}
// @title AddBaseMenu
// @description 函数的详细描述
// @auth (2020/04/05 20:22 )
// @param newPassword string
// @return err error
//增加基础路由
func (b *SysBaseMenu) AddBaseMenu() (err error) {
findOne := global.GVA_DB.Where("name = ?", b.Name).Find(&SysBaseMenu{}).Error
if findOne != nil {
err = global.GVA_DB.Create(b).Error
} else {
err = errors.New("存在重复name,请修改name")
}
return err
}
// @title DeleteBaseMenu
// @description 删除基础路由
// @auth (2020/04/05 20:22 )
// @param newPassword string
// @return err error
func (b *SysBaseMenu) DeleteBaseMenu(id float64) (err error) {
err = global.GVA_DB.Where("parent_id = ?", id).First(&SysBaseMenu{}).Error
if err != nil {
db := global.GVA_DB.Preload("SysAuthoritys").Where("id = ?", id).First(&b).Delete(&b)
if len(b.SysAuthoritys) > 0 {
err = db.Association("SysAuthoritys").Delete(b.SysAuthoritys).Error
} else {
err = db.Error
}
} else {
return errors.New("此菜单存在子菜单不可删除")
}
return err
}
// @title UpdateBaseMenu
// @description 更新路由
// @auth (2020/04/05 20:22 )
// @param newPassword string
// @return err error
func (b *SysBaseMenu) UpdateBaseMenu() (err error) {
upDateMap := make(map[string]interface{})
upDateMap["parent_id"] = b.ParentId
upDateMap["path"] = b.Path
upDateMap["name"] = b.Name
upDateMap["hidden"] = b.Hidden
upDateMap["component"] = b.Component
upDateMap["title"] = b.Title
upDateMap["icon"] = b.Icon
upDateMap["sort"] = b.Sort
err = global.GVA_DB.Where("id = ?", b.ID).Find(&SysBaseMenu{}).Updates(upDateMap).Error
err1 := global.GVA_DB.Where("menu_id = ?", b.ID).Find(&[]SysMenu{}).Updates(upDateMap).Error
fmt.Printf("菜单修改时候,关联菜单err1:%v,err:%v", err1, err)
return err
}
// @title GetBaseMenuById
// @description get current menus, 返回当前选中menu
// @auth (2020/04/05 20:22 )
// @param newPassword string
// @return err error
func (b *SysBaseMenu) GetBaseMenuById(id float64) (err error, menu SysBaseMenu) {
err = global.GVA_DB.Where("id = ?", id).First(&menu).Error
return
}
// @title GetInfoList
// @description 获取路由分页
// @auth (2020/04/05 20:22 )
// @param newPassword string
// @return err error
func (b *SysBaseMenu) GetInfoList(info PageInfo) (err error, list interface{}, total int) {
limit := info.PageSize
offset := info.PageSize * (info.Page - 1)
db := global.GVA_DB
if err != nil {
return
} else {
var menuList []SysBaseMenu
err = db.Limit(limit).Offset(offset).Where("parent_id = 0").Order("sort", true).Find(&menuList).Error
for i := 0; i < len(menuList); i++ {
err = getBaseChildrenList(&menuList[i])
}
return err, menuList, total
}
}
// @title GetBaseMenuTree
// @description 获取基础路由树
// @auth (2020/04/05 20:22 )
// @return err error
// @return menus []SysBaseMenu
func (m *SysBaseMenu) GetBaseMenuTree() (err error, menus []SysBaseMenu) {
err = global.GVA_DB.Where(" parent_id = ?", 0).Order("sort", true).Find(&menus).Error
for i := 0; i < len(menus); i++ {
err = getBaseChildrenList(&menus[i])
}
return err, menus
}
// @title getBaseChildrenList
// @description get children of menu, 获取菜单的子菜单
// @auth (2020/04/05 20:22 )
// @param menu *SysBaseMenu
// @return err error
func getBaseChildrenList(menu *SysBaseMenu) (err error) {
err = global.GVA_DB.Where("parent_id = ?", menu.ID).Order("sort", true).Find(&menu.Children).Error
for i := 0; i < len(menu.Children); i++ {
err = getBaseChildrenList(&menu.Children[i])
}
return err
}
}
\ No newline at end of file
package model
import (
"errors"
"gin-vue-admin/global"
"github.com/casbin/casbin"
"github.com/casbin/casbin/util"
gormadapter "github.com/casbin/gorm-adapter"
"strings"
)
type CasbinModel struct {
ID uint `json:"id" gorm:"column:_id"`
Ptype string `json:"ptype" gorm:"column:ptype"`
AuthorityId string `json:"rolename" gorm:"column:v0"`
Path string `json:"path" gorm:"column:v1"`
Method string `json:"method" gorm:"column:v2"`
}
// 供入参使用
type CasbinInfo struct {
Path string `json:"path"`
Method string `json:"method"`
}
// 供入参使用
type CasbinInReceive struct {
AuthorityId string `json:"authorityId"`
CasbinInfos []CasbinInfo `json:"casbinInfos"`
}
// @title UpdateCasbin
// @description update casbin authority, 更新casbin权限
// @auth (2020/04/05 20:22 )
// @param authorityId string
// @param casbinInfos []CasbinInfo
// @return error
func (c *CasbinModel) UpdateCasbin(authorityId string, casbinInfos []CasbinInfo) error {
c.ClearCasbin(0, authorityId)
for _, v := range casbinInfos {
cm := CasbinModel{
ID: 0,
Ptype: "p",
AuthorityId: authorityId,
Path: v.Path,
Method: v.Method,
}
addflag := c.AddCasbin(cm)
if addflag == false {
return errors.New("存在相同api,添加失败,请联系管理员")
}
}
return nil
}
// @title UpdateCasbinApi
// @description update casbin apis, API更新随动
// @auth (2020/04/05 20:22 )
// @param oldPath string
// @param newPath string
// @return error
func (c *CasbinModel) UpdateCasbinApi(oldPath string, newPath string) error {
var cs []CasbinModel
err := global.GVA_DB.Table("casbin_rule").Where("v1 = ?", oldPath).Find(&cs).Update("v1", newPath).Error
return err
}
// @title AddCasbin
// @description add casbin authority, 添加权限
// @auth (2020/04/05 20:22 )
// @param cm CasbinModel
// @return bool
func (c *CasbinModel) AddCasbin(cm CasbinModel) bool {
e := Casbin()
return e.AddPolicy(cm.AuthorityId, cm.Path, cm.Method)
}
// @title GetPolicyPathByAuthorityId
// @description get policy path by authorityId, 获取权限列表
// @auth (2020/04/05 20:22 )
// @param authorityId string
// @return []string
func (c *CasbinModel) GetPolicyPathByAuthorityId(authorityId string) []string {
e := Casbin()
var pathList []string
list := e.GetFilteredPolicy(0, authorityId)
for _, v := range list {
pathList = append(pathList, v[1])
}
return pathList
}
// @title ClearCasbin
// @description 清除匹配的权限
// @auth (2020/04/05 20:22 )
// @param v int
// @param p string
// @return bool
func (c *CasbinModel) ClearCasbin(v int, p string) bool {
e := Casbin()
return e.RemoveFilteredPolicy(v, p)
}
// @title ParamsMatch
// @description customized rule, 自定义规则函数
// @auth (2020/04/05 20:22 )
// @param fullNameKey1 string
// @param key2 string
// @return bool
func ParamsMatch(fullNameKey1 string, key2 string) bool {
key1 := strings.Split(fullNameKey1, "?")[0]
//剥离路径后再使用casbin的keyMatch2
return util.KeyMatch2(key1, key2)
}
// @title ParamsMatchFunc
// @description customized function, 自定义规则函数
// @auth (2020/04/05 20:22 )
// @param args ...interface{}
// @return interface{}
// @return error
func ParamsMatchFunc(args ...interface{}) (interface{}, error) {
name1 := args[0].(string)
name2 := args[1].(string)
return (bool)(ParamsMatch(name1, name2)), nil
}
// @title Casbin
// @description store to DB, 持久化到数据库 引入自定义规则
// @auth (2020/04/05 20:22 )
func Casbin() *casbin.Enforcer {
a := gormadapter.NewAdapterByDB(global.GVA_DB)
e := casbin.NewEnforcer(global.GVA_CONFIG.Casbin.ModelPath, a)
e.AddFunction("ParamsMatch", ParamsMatchFunc)
_ = e.LoadPolicy()
return e
}
}
\ No newline at end of file
package model
import (
"gin-vue-admin/global"
"github.com/jinzhu/gorm"
)
type JwtBlacklist struct {
gorm.Model
Jwt string `gorm:"type:text"`
}
// @title JsonInBlacklist
// @description create jwt blacklist
// @auth (2020/04/05 20:22 )
// @return err error
func (j *JwtBlacklist) JsonInBlacklist() (err error) {
err = global.GVA_DB.Create(j).Error
return
}
// @title IsBlacklist
// @description check if the Jwt is in the blacklist or not, 判断JWT是否在黑名单内部
// @auth (2020/04/05 20:22 )
// @param newPassword string
// @return err error
func (j *JwtBlacklist) IsBlacklist(Jwt string) bool {
isNotFound := global.GVA_DB.Where("jwt = ?", Jwt).First(j).RecordNotFound()
return !isNotFound
}
// @title GetRedisJWT
// @description Get user info in redis
// @auth (2020/04/05 20:22 )
// @param newPassword string
// @return err error
func (j *JwtBlacklist) GetRedisJWT(userName string) (err error, RedisJWT string) {
RedisJWT, err = global.GVA_REDIS.Get(userName).Result()
return err, RedisJWT
}
// @title SetRedisJWT
// @description set jwt into the Redis
// @auth (2020/04/05 20:22 )
// @param userName string
// @return err error
func (j *JwtBlacklist) SetRedisJWT(userName string) (err error) {
err = global.GVA_REDIS.Set(userName, j.Jwt, 1000*1000*1000*60*60*24*7).Err()
return err
}
}
\ No newline at end of file
......@@ -2,33 +2,9 @@ package model
import (
"gin-vue-admin/config"
"gin-vue-admin/global"
"gin-vue-admin/utils"
)
//配置文件结构体
type System struct {
Config config.Server
}
// @title GetSystemConfig
// @description 读取配置文件
// @auth (2020/04/05 20:22 )
// @return err error
// @return conf Server
func (s *System) GetSystemConfig() (err error, conf config.Server) {
return nil, global.GVA_CONFIG
}
// @title SetSystemConfig
// @description set system config, 设置配置文件
// @auth (2020/04/05 20:22 )
// @return err error
func (s *System) SetSystemConfig() (err error) {
confs := utils.StructToMap(s.Config)
for k, v := range confs {
global.GVA_VP.Set(k, v)
}
err = global.GVA_VP.WriteConfig()
return err
}
}
\ No newline at end of file
package model
import (
"gin-vue-admin/global"
"gin-vue-admin/utils"
"github.com/jinzhu/gorm"
"github.com/pkg/errors"
uuid "github.com/satori/go.uuid"
)
......@@ -17,114 +14,4 @@ type SysUser struct {
HeaderImg string `json:"headerImg" gorm:"default:'http://www.henrongyi.top/avatar/lufu.jpg'"`
Authority SysAuthority `json:"authority" gorm:"ForeignKey:AuthorityId;AssociationForeignKey:AuthorityId"`
AuthorityId string `json:"authorityId" gorm:"default:888"`
}
type RegisterAndLoginStruct struct {
Username string `json:"username"`
Password string `json:"password"`
Captcha string `json:"captcha"`
CaptchaId string `json:"captchaId"`
}
type RegisterStruct struct {
Username string `json:"userName"`
Password string `json:"passWord"`
NickName string `json:"nickName" gorm:"default:'QMPlusUser'"`
HeaderImg string `json:"headerImg" gorm:"default:'http://www.henrongyi.top/avatar/lufu.jpg'"`
AuthorityId string `json:"authorityId" gorm:"default:888"`
}
// @title Register
// @description register, 用户注册
// @auth (2020/04/05 20:22 )
// @return err error
// @return userInter *SysUser
func (u *SysUser) Register() (err error, userInter *SysUser) {
var user SysUser
//判断用户名是否注册
notResigt := global.GVA_DB.Where("username = ?", u.Username).First(&user).RecordNotFound()
//notResigt为false表明读取到了 不能注册
if !notResigt {
return errors.New("用户名已注册"), nil
} else {
// 否则 附加uuid 密码md5简单加密 注册
u.Password = utils.MD5V([]byte(u.Password))
u.UUID = uuid.NewV4()
err = global.GVA_DB.Create(u).Error
}
return err, u
}
// @title ChangePassword
// @description change the password of a certain user, 修改用户密码
// @auth (2020/04/05 20:22 )
// @param newPassword string
// @return err error
// @return userInter *SysUser
func (u *SysUser) ChangePassword(newPassword string) (err error, userInter *SysUser) {
var user SysUser
//后期修改jwt+password模式
u.Password = utils.MD5V([]byte(u.Password))
err = global.GVA_DB.Where("username = ? AND password = ?", u.Username, u.Password).First(&user).Update("password", utils.MD5V([]byte(newPassword))).Error
return err, u
}
// @title SetUserAuthority
// @description set the authority of a certain user, 设置一个用户的权限
// @auth (2020/04/05 20:22 )
// @param uuid UUID
// @param authorityId string
// @return err error
func (u *SysUser) SetUserAuthority(uuid uuid.UUID, authorityId string) (err error) {
err = global.GVA_DB.Where("uuid = ?", uuid).First(&SysUser{}).Update("authority_id", authorityId).Error
return err
}
// @title Login
// @description login, 用户登录
// @auth (2020/04/05 20:22 )
// @return err error
// @return userInter *SysUser
func (u *SysUser) Login() (err error, userInter *SysUser) {
var user SysUser
u.Password = utils.MD5V([]byte(u.Password))
err = global.GVA_DB.Where("username = ? AND password = ?", u.Username, u.Password).First(&user).Error
if err != nil {
return err, &user
}
err = global.GVA_DB.Where("authority_id = ?", user.AuthorityId).First(&user.Authority).Error
return err, &user
}
// @title UploadHeaderImg
// @description upload avatar, 用户头像上传更新地址
// @auth (2020/04/05 20:22 )
// @param uuid UUID
// @param filePath string
// @return err error
// @return userInter *SysUser
func (u *SysUser) UploadHeaderImg(uuid uuid.UUID, filePath string) (err error, userInter *SysUser) {
var user SysUser
err = global.GVA_DB.Where("uuid = ?", uuid).First(&user).Update("header_img", filePath).First(&user).Error
return err, &user
}
// @title GetInfoList
// @description get user list by pagination, 分页获取数据
// @auth (2020/04/05 20:22 )
// @param PageInfo int
// @return err error
// @return list interface{}
// @return total int
func (u *SysUser) GetInfoList(info PageInfo) (err error, list interface{}, total int) {
limit := info.PageSize
offset := info.PageSize * (info.Page - 1)
db := global.GVA_DB
if err != nil {
return
} else {
var userList []SysUser
err = db.Limit(limit).Offset(offset).Preload("Authority").Find(&userList).Error
return err, userList, total
}
}
}
\ No newline at end of file
package model
import (
"gin-vue-admin/global"
"github.com/jinzhu/gorm"
)
......@@ -23,13 +22,4 @@ type SysWorkflowStepInfo struct {
StepNo float64 `json:"stepNo"` // 步骤id (第几步)
StepAuthorityID string `json:"stepAuthorityID"` // 操作者级别id
IsEnd bool `json:"isEnd"` // 是否是完结流节点
}
// @title Create
// @description create a workflow, 创建工作流
// @auth (2020/04/05 20:22 )
// @return error
func (wk *SysWorkflow) Create() error {
err := global.GVA_DB.Create(&wk).Error
return err
}
}
\ No newline at end of file
package service
import (
"gin-vue-admin/global"
"gin-vue-admin/model"
)
// @title FindOrCreateFile
// @description Check your file if it does not exist, or return current slice of the file
// 上传文件时检测当前文件属性,如果没有文件则创建,有则返回文件的当前切片
// @auth (2020/04/05 20:22 )
// @param FileMd5 string
// @param FileName string
// @param ChunkTotal int
// @return err error
// @return file ExaFile
func FindOrCreateFile(FileMd5 string, FileName string, ChunkTotal int) (err error, file model.ExaFile) {
var cfile model.ExaFile
cfile.FileMd5 = FileMd5
cfile.FileName = FileName
cfile.ChunkTotal = ChunkTotal
notHaveSameMd5Finish := global.GVA_DB.Where("file_md5 = ? AND is_finish = ?", FileMd5, true).First(&file).RecordNotFound()
if notHaveSameMd5Finish {
err = global.GVA_DB.Where("file_md5 = ? AND file_name = ?", FileMd5, FileName).Preload("ExaFileChunk").FirstOrCreate(&file, cfile).Error
return err, file
} else {
cfile.IsFinish = true
cfile.FilePath = file.FilePath
err = global.GVA_DB.Create(&cfile).Error
return err, cfile
}
}
// @title CreateFileChunk
// @description create a chunk of the file, 创建文件切片记录
// @auth (2020/04/05 20:22 )
// @param FileChunkPath string
// @param FileChunkNumber int
// @return error
func CreateFileChunk(id uint, FileChunkPath string, FileChunkNumber int) error {
var chunk model.ExaFileChunk
chunk.FileChunkPath = FileChunkPath
chunk.ExaFileId = id
chunk.FileChunkNumber = FileChunkNumber
err := global.GVA_DB.Create(&chunk).Error
return err
}
// @title FileCreateComplete
// @description file creation, 文件合成完成
// @auth (2020/04/05 20:22 )
// @param FileMd5 string
// @param FileName string
// @param FilePath string
// @return error
func FileCreateComplete(FileMd5 string, FileName string, FilePath string) error {
var file model.ExaFile
upDateFile := make(map[string]interface{})
upDateFile["FilePath"] = FilePath
upDateFile["IsFinish"] = true
err := global.GVA_DB.Where("file_md5 = ? AND file_name = ?", FileMd5, FileName).First(&file).Updates(upDateFile).Error
return err
}
// @title DeleteFileChunk
// @description delete a chuck of the file, 删除文件切片记录
// @auth (2020/04/05 20:22 )
// @param FileMd5 string
// @param FileName string
// @param FilePath string
// @return error
func DeleteFileChunk(fileMd5 string, fileName string, filePath string) error {
var chunks []model.ExaFileChunk
var file model.ExaFile
err := global.GVA_DB.Where("file_md5 = ? AND file_name = ?", fileMd5, fileName).First(&file).Update("IsFinish", true).Update("file_path", filePath).Error
err = global.GVA_DB.Where("exa_file_id = ?", file.ID).Delete(&chunks).Unscoped().Error
return err
}
package service
import (
"gin-vue-admin/global"
"gin-vue-admin/model"
"gin-vue-admin/model/request"
)
// @title CreateExaCustomer
// @description create a customer, 创建用户
// @auth (2020/04/05 20:22 )
// @return err error
func CreateExaCustomer(e model.ExaCustomer) (err error) {
err = global.GVA_DB.Create(e).Error
return err
}
// @title DeleteFileChunk
// @description delete a customer, 删除用户
// @auth (2020/04/05 20:22 )
// @return error
func DeleteExaCustomer(e model.ExaCustomer) (err error) {
err = global.GVA_DB.Delete(e).Error
return err
}
// @title UpdateExaCustomer
// @description update a customer, 更新用户
// @auth (2020/04/05 20:22 )
// @return error
func UpdateExaCustomer(e *model.ExaCustomer) (err error) {
err = global.GVA_DB.Save(e).Error
return err
}
// @title GetExaCustomer
// @description get the info of a costumer , 获取用户信息
// @auth (2020/04/05 20:22 )
// @return error
// @return customer ExaCustomer
func GetExaCustomer(id uint) (err error, customer model.ExaCustomer) {
err = global.GVA_DB.Where("id = ?",id).First(&customer).Error
return
}
// @title GetCustomerInfoList
// @description get customer list by pagination, 分页获取用户列表
// @auth (2020/04/05 20:22 )
// @param info PageInfo
// @return error
func GetCustomerInfoList(sysUserAuthorityID string, info request.PageInfo) (err error, list interface{}, total int) {
limit := info.PageSize
offset := info.PageSize * (info.Page - 1)
db := global.GVA_DB
if err != nil {
return
} else {
var a model.SysAuthority
a.AuthorityId = sysUserAuthorityID
err, auth :=GetAuthorityInfo(a)
var dataId []string
for _, v := range auth.DataAuthorityId {
dataId = append(dataId, v.AuthorityId)
}
var CustomerList []model.ExaCustomer
err = db.Where("sys_user_authority_id in (?)", dataId).Find(&CustomerList).Count(&total).Error
if err != nil {
return err, CustomerList, total
} else {
err = db.Limit(limit).Offset(offset).Preload("SysUser").Where("sys_user_authority_id in (?)", dataId).Find(&CustomerList).Error
}
return err, CustomerList, total
}
}
package service
import (
"gin-vue-admin/global"
"gin-vue-admin/model"
"gin-vue-admin/model/request"
)
// @title Upload
// @description 创建文件上传记录
// @auth (2020/04/05 20:22 )
// @return error
func Upload(f model.ExaFileUploadAndDownload) error {
err := global.GVA_DB.Create(f).Error
return err
}
// @title FindFile
// @description 删除文件切片记录
// @auth (2020/04/05 20:22 )
// @return error
func FindFile(id uint) (error, model.ExaFileUploadAndDownload) {
var file model.ExaFileUploadAndDownload
err := global.GVA_DB.Where("id = ?", id).First(&file).Error
return err, file
}
// @title DeleteFile
// @description 删除文件记录
// @auth (2020/04/05 20:22 )
// @return error
func DeleteFile(f model.ExaFileUploadAndDownload) error {
err := global.GVA_DB.Where("id = ?", f.ID).Unscoped().Delete(f).Error
return err
}
// @title GetFileRecordInfoList
// @description 分页获取数据
// @auth (2020/04/05 20:22 )
// @param info PageInfo
// @return err error
// @return list error
// @return total error
func GetFileRecordInfoList(info request.PageInfo) (err error, list interface{}, total int) {
limit := info.PageSize
offset := info.PageSize * (info.Page - 1)
db := global.GVA_DB
if err != nil {
return
} else {
var fileLists []model.ExaFileUploadAndDownload
err = db.Limit(limit).Offset(offset).Order("updated_at desc").Find(&fileLists).Error
return err, fileLists, total
}
}
package service
import (
"gin-vue-admin/global"
"gin-vue-admin/model"
)
// @title JsonInBlacklist
// @description create jwt blacklist
// @auth (2020/04/05 20:22 )
// @return err error
func JsonInBlacklist(j model.JwtBlacklist) (err error) {
err = global.GVA_DB.Create(j).Error
return
}
// @title IsBlacklist
// @description check if the Jwt is in the blacklist or not, 判断JWT是否在黑名单内部
// @auth (2020/04/05 20:22 )
// @param newPassword string
// @return err error
func IsBlacklist(Jwt string, j model.JwtBlacklist) bool {
isNotFound := global.GVA_DB.Where("jwt = ?", Jwt).First(j).RecordNotFound()
return !isNotFound
}
// @title GetRedisJWT
// @description Get user info in redis
// @auth (2020/04/05 20:22 )
// @param newPassword string
// @return err error
func GetRedisJWT(userName string) (err error, RedisJWT string) {
RedisJWT, err = global.GVA_REDIS.Get(userName).Result()
return err, RedisJWT
}
// @title SetRedisJWT
// @description set jwt into the Redis
// @auth (2020/04/05 20:22 )
// @param userName string
// @return err error
func SetRedisJWT(j model.JwtBlacklist, userName string) (err error) {
err = global.GVA_REDIS.Set(userName, j.Jwt, 1000*1000*1000*60*60*24*7).Err()
return err
}
package service
import (
"errors"
"gin-vue-admin/global"
"gin-vue-admin/model"
"gin-vue-admin/model/request"
)
// @title CreateApi
// @description create base apis, 新增基础api
// @auth (2020/04/05 20:22 )
// @param FileMd5 string
// @param FileName string
// @param FilePath string
// @return error
func CreateApi(a model.SysApi) (err error) {
findOne := global.GVA_DB.Where("path = ?", a.Path).Find(&model.SysApi{}).Error
if findOne == nil {
return errors.New("存在相同api")
} else {
err = global.GVA_DB.Create(a).Error
}
return err
}
// @title DeleteApi
// @description delete base apis, 删除基础api
// @auth (2020/04/05 20:22 )
// @return error
func DeleteApi(a model.SysApi) (err error) {
err = global.GVA_DB.Delete(a).Error
ClearCasbin(1, a.Path)
return err
}
// @title GetInfoList
// @description get apis by pagination, 分页获取数据
// @auth (2020/04/05 20:22 )
// @param info PageInfo
// @return err error
// @return list interface{}
// @return total int
func GetAPIInfoList(a model.SysApi, info request.PageInfo, Order string, Desc bool) (err error, list interface{}, total int) {
limit := info.PageSize
offset := info.PageSize * (info.Page - 1)
db := global.GVA_DB
if err != nil {
return
} else {
var apiList []model.SysApi
if a.Path != "" {
db = db.Where("path LIKE ?", "%"+a.Path+"%")
}
if a.Description != "" {
db = db.Where("description LIKE ?", "%"+a.Description+"%")
}
if a.Method != "" {
db = db.Where("method = ?", a.Method)
}
err = db.Find(&apiList).Count(&total).Error
if err != nil {
return err, apiList, total
} else {
db = db.Limit(limit).Offset(offset)
if Order != "" {
var OrderStr string
if Desc {
OrderStr = Order + " desc"
} else {
OrderStr = Order
}
err = db.Order(OrderStr, true).Find(&apiList).Error
} else {
err = db.Order("api_group", true).Find(&apiList).Error
}
}
return err, apiList, total
}
}
// @title GetAllApis
// @description get all apis, 获取所有的api
// @auth (2020/04/05 20:22 )
// @return err error
// @return apis []SysApi
func GetAllApis() (err error, apis []model.SysApi) {
err = global.GVA_DB.Find(&apis).Error
return
}
// @title GetApiById
// @description 根据id获取api
// @auth (2020/04/05 20:22 )
// @param id float64
// @return error
func GetApiById(id float64) (err error, api model.SysApi) {
err = global.GVA_DB.Where("id = ?", id).First(&api).Error
return
}
// @title UpdateApi
// @description update a base api, update api
// @auth (2020/04/05 20:22 )
// @return error
func UpdateApi(a model.SysApi) (err error) {
var oldA model.SysApi
flag := global.GVA_DB.Where("path = ?", a.Path).Find(&model.SysApi{}).RecordNotFound()
if !flag {
return errors.New("存在相同api路径")
}
err = global.GVA_DB.Where("id = ?", a.ID).First(&oldA).Error
if err != nil {
return err
} else {
err = UpdateCasbinApi(oldA.Path, a.Path)
if err != nil {
return err
} else {
err = global.GVA_DB.Save(a).Error
}
}
return err
}
package service
import (
"errors"
"gin-vue-admin/global"
"gin-vue-admin/model"
"gin-vue-admin/model/request"
)
// @title CreateAuthority
// @description 创建一个角色
// @auth (2020/04/05 20:22 )
// @param FileMd5 string
// @param FileName string
// @param FilePath string
// @return error
func CreateAuthority(a *model.SysAuthority) (err error, authority *model.SysAuthority) {
err = global.GVA_DB.Create(a).Error
return err, a
}
// @title DeleteAuthority
// @description 删除角色
// @auth (2020/04/05 20:22 )
// @param FileMd5 string
// @param FileName string
// @param FilePath string
// @return error
// 删除角色
func DeleteAuthority(a model.SysAuthority) (err error) {
err = global.GVA_DB.Where("authority_id = ?", a.AuthorityId).Find(&model.SysUser{}).Error
if err == nil {
err = errors.New("此角色有用户正在使用禁止删除")
return
}
err = global.GVA_DB.Where("parent_id = ?", a.AuthorityId).Find(&model.SysAuthority{}).Error
if err == nil {
err = errors.New("此角色存在子角色不允许删除")
return
}
db := global.GVA_DB.Preload("SysBaseMenus").Where("authority_id = ?", a.AuthorityId).First(a).Unscoped().Delete(a)
if len(a.SysBaseMenus) > 0 {
err = db.Association("SysBaseMenus").Delete(a.SysBaseMenus).Error
} else {
err = db.Error
}
ClearCasbin(0, a.AuthorityId)
return err
}
// @title GetInfoList
// @description 删除文件切片记录
// @auth (2020/04/05 20:22 )
// @param FileMd5 string
// @param FileName string
// @param FilePath string
// @return error
// 分页获取数据
func GetAuthorityInfoList(info request.PageInfo) (err error, list interface{}, total int) {
limit := info.PageSize
offset := info.PageSize * (info.Page - 1)
db := global.GVA_DB
if err != nil {
return
} else {
var authority []model.SysAuthority
err = db.Limit(limit).Offset(offset).Preload("DataAuthorityId").Where("parent_id = 0").Find(&authority).Error
if len(authority) > 0 {
for k, _ := range authority {
err = findChildrenAuthority(&authority[k])
}
}
return err, authority, total
}
}
// @title GetAuthorityInfo
// @description 获取所有角色信息
// @auth (2020/04/05 20:22 )
// @param FileMd5 string
// @param FileName string
// @param FilePath string
// @return error
func GetAuthorityInfo(a model.SysAuthority) (err error, sa model.SysAuthority) {
err = global.GVA_DB.Preload("DataAuthorityId").Where("authority_id = ?", a.AuthorityId).First(&sa).Error
return err, sa
}
// @title SetDataAuthority
// @description 设置角色资源权限
// @auth (2020/04/05 20:22 )
// @param FileMd5 string
// @param FileName string
// @param FilePath string
// @return error
func SetDataAuthority(a model.SysAuthority) error {
var s model.SysAuthority
global.GVA_DB.Preload("DataAuthorityId").First(&s, "authority_id = ?", a.AuthorityId)
err := global.GVA_DB.Model(&s).Association("DataAuthorityId").Replace(&a.DataAuthorityId).Error
return err
}
// @title SetMenuAuthority
// @description 菜单与角色绑定
// @auth (2020/04/05 20:22 )
// @param FileMd5 string
// @param FileName string
// @param FilePath string
// @return error
func SetMenuAuthority(a *model.SysAuthority) error {
var s model.SysAuthority
global.GVA_DB.Preload("SysBaseMenus").First(&s, "authority_id = ?", a.AuthorityId)
err := global.GVA_DB.Model(&s).Association("SysBaseMenus").Replace(&a.SysBaseMenus).Error
return err
}
// @title findChildrenAuthority
// @description 查询子角色
// @auth (2020/04/05 20:22 )
// @param FileMd5 string
// @param FileName string
// @param FilePath string
// @return error
func findChildrenAuthority(authority *model.SysAuthority) (err error) {
err = global.GVA_DB.Preload("DataAuthorityId").Where("parent_id = ?", authority.AuthorityId).Find(&authority.Children).Error
if len(authority.Children) > 0 {
for k, _ := range authority.Children {
err = findChildrenAuthority(&authority.Children[k])
}
}
return err
}
package service
import (
"gin-vue-admin/model"
"gin-vue-admin/utils"
"html/template"
"os"
)
// @title CreateTemp
// @description 函数的详细描述
// @auth (2020/04/05 20:22 )
// @return err error
func CreateTemp(a model.AutoCodeStruct) (err error) {
basePath := "./resource/template"
modelTmpl, err := template.ParseFiles(basePath + "/te/model.go.tpl")
if err != nil {
return err
}
apiTmpl, err := template.ParseFiles(basePath + "/te/api.go.tpl")
if err != nil {
return err
}
routerTmpl, err := template.ParseFiles(basePath + "/te/router.go.tpl")
if err != nil {
return err
}
feapiTmpl, err := template.ParseFiles(basePath + "/fe/api.js.tpl")
if err != nil {
return err
}
readmeTmpl, err := template.ParseFiles(basePath + "/readme.txt.tpl")
if err != nil {
return err
}
//自动化总目录
_autoCode := "./autoCode/"
//自动化后台代码目录
_te := "./autoCode/te/"
_dir := _te + a.PackageName
_modeldir := _te + a.PackageName + "/model"
_apidir := _te + a.PackageName + "/api"
_routerdir := _te + a.PackageName + "/router"
//自动化前台代码目录
_fe := "./autoCode/fe/"
_fe_dir := _fe + a.PackageName
_fe_apidir := _fe + a.PackageName + "/api"
err = utils.CreateDir(_autoCode, _te, _dir, _modeldir, _apidir, _routerdir, _fe, _fe_dir, _fe_apidir)
if err != nil {
return err
}
model, err := os.OpenFile(_te+a.PackageName+"/model/model.go", os.O_CREATE|os.O_WRONLY, 0755)
if err != nil {
return err
}
api, err := os.OpenFile(_te+a.PackageName+"/api/api.go", os.O_CREATE|os.O_WRONLY, 0755)
if err != nil {
return err
}
router, err := os.OpenFile(_te+a.PackageName+"/router/router.go", os.O_CREATE|os.O_WRONLY, 0755)
if err != nil {
return err
}
feapi, err := os.OpenFile(_fe+a.PackageName+"/api/api.js", os.O_CREATE|os.O_WRONLY, 0755)
if err != nil {
return err
}
readme, err := os.OpenFile(_autoCode+"readme.txt", os.O_CREATE|os.O_WRONLY, 0755)
if err != nil {
return err
}
// 生成代码
{
err = modelTmpl.Execute(model, a)
if err != nil {
return err
}
err = apiTmpl.Execute(api, a)
if err != nil {
return err
}
err = routerTmpl.Execute(router, a)
if err != nil {
return err
}
err = feapiTmpl.Execute(feapi, a)
if err != nil {
return err
}
err = readmeTmpl.Execute(readme, a)
if err != nil {
return err
}
}
_ = model.Close()
_ = api.Close()
_ = router.Close()
_ = feapi.Close()
_ = readme.Close()
fileList := []string{
_te + a.PackageName + "/model/model.go",
_te + a.PackageName + "/api/api.go",
_te + a.PackageName + "/router/router.go",
_fe + a.PackageName + "/api/api.js",
_autoCode + "readme.txt",
}
err = utils.ZipFiles("./ginvueadmin.zip", fileList, ".", ".")
if err != nil {
return err
}
err = os.RemoveAll(_autoCode)
if err != nil {
return err
}
return nil
}
package service
import (
"errors"
"gin-vue-admin/global"
"gin-vue-admin/model"
)
// @title DeleteBaseMenu
// @description 删除基础路由
// @auth (2020/04/05 20:22 )
// @param newPassword string
// @return err error
func DeleteBaseMenu(id float64) (err error) {
err = global.GVA_DB.Where("parent_id = ?", id).First(&model.SysBaseMenu{}).Error
if err != nil {
var menu model.SysBaseMenu
db := global.GVA_DB.Preload("SysAuthoritys").Where("id = ?", id).First(&menu).Delete(&menu)
if len(menu.SysAuthoritys) > 0 {
err = db.Association("SysAuthoritys").Delete(menu.SysAuthoritys).Error
} else {
err = db.Error
}
} else {
return errors.New("此菜单存在子菜单不可删除")
}
return err
}
// @title UpdateBaseMenu
// @description 更新路由
// @auth (2020/04/05 20:22 )
// @param newPassword string
// @return err error
func UpdateBaseMenu(menu model.SysBaseMenu) (err error) {
upDateMap := make(map[string]interface{})
upDateMap["parent_id"] = menu.ParentId
upDateMap["path"] = menu.Path
upDateMap["name"] = menu.Name
upDateMap["hidden"] = menu.Hidden
upDateMap["component"] = menu.Component
upDateMap["title"] = menu.Title
upDateMap["icon"] = menu.Icon
upDateMap["sort"] = menu.Sort
err = global.GVA_DB.Where("id = ?", menu.ID).Find(&model.SysBaseMenu{}).Updates(upDateMap).Error
global.GVA_LOG.Debug("菜单修改时候,关联菜单err:%v", err)
return err
}
// @title GetBaseMenuById
// @description get current menus, 返回当前选中menu
// @auth (2020/04/05 20:22 )
// @param newPassword string
// @return err error
func GetBaseMenuById(id float64) (err error, menu model.SysBaseMenu) {
err = global.GVA_DB.Where("id = ?", id).First(&menu).Error
return
}
package service
import (
"errors"
"gin-vue-admin/global"
"gin-vue-admin/model"
"gin-vue-admin/model/request"
"github.com/casbin/casbin"
"github.com/casbin/casbin/util"
gormadapter "github.com/casbin/gorm-adapter"
"strings"
)
// @title UpdateCasbin
// @description update casbin authority, 更新casbin权限
// @auth (2020/04/05 20:22 )
// @param authorityId string
// @param casbinInfos []CasbinInfo
// @return error
func UpdateCasbin(authorityId string, casbinInfos []request.CasbinInfo) error {
ClearCasbin(0, authorityId)
for _, v := range casbinInfos {
cm := model.CasbinModel{
ID: 0,
Ptype: "p",
AuthorityId: authorityId,
Path: v.Path,
Method: v.Method,
}
addflag := AddCasbin(cm)
if addflag == false {
return errors.New("存在相同api,添加失败,请联系管理员")
}
}
return nil
}
// @title AddCasbin
// @description add casbin authority, 添加权限
// @auth (2020/04/05 20:22 )
// @param cm CasbinModel
// @return bool
func AddCasbin(cm model.CasbinModel) bool {
e := Casbin()
return e.AddPolicy(cm.AuthorityId, cm.Path, cm.Method)
}
// @title UpdateCasbinApi
// @description update casbin apis, API更新随动
// @auth (2020/04/05 20:22 )
// @param oldPath string
// @param newPath string
// @return error
func UpdateCasbinApi(oldPath string, newPath string) error {
var cs []model.CasbinModel
err := global.GVA_DB.Table("casbin_rule").Where("v1 = ?", oldPath).Find(&cs).Update("v1", newPath).Error
return err
}
// @title GetPolicyPathByAuthorityId
// @description get policy path by authorityId, 获取权限列表
// @auth (2020/04/05 20:22 )
// @param authorityId string
// @return []string
func GetPolicyPathByAuthorityId(authorityId string) []string {
e := Casbin()
var pathList []string
list := e.GetFilteredPolicy(0, authorityId)
for _, v := range list {
pathList = append(pathList, v[1])
}
return pathList
}
// @title ClearCasbin
// @description 清除匹配的权限
// @auth (2020/04/05 20:22 )
// @param v int
// @param p string
// @return bool
func ClearCasbin(v int, p string) bool {
e := Casbin()
return e.RemoveFilteredPolicy(v, p)
}
// @title Casbin
// @description store to DB, 持久化到数据库 引入自定义规则
// @auth (2020/04/05 20:22 )
func Casbin() *casbin.Enforcer {
a := gormadapter.NewAdapterByDB(global.GVA_DB)
e := casbin.NewEnforcer(global.GVA_CONFIG.Casbin.ModelPath, a)
e.AddFunction("ParamsMatch", ParamsMatchFunc)
_ = e.LoadPolicy()
return e
}
// @title ParamsMatch
// @description customized rule, 自定义规则函数
// @auth (2020/04/05 20:22 )
// @param fullNameKey1 string
// @param key2 string
// @return bool
func ParamsMatch(fullNameKey1 string, key2 string) bool {
key1 := strings.Split(fullNameKey1, "?")[0]
//剥离路径后再使用casbin的keyMatch2
return util.KeyMatch2(key1, key2)
}
// @title ParamsMatchFunc
// @description customized function, 自定义规则函数
// @auth (2020/04/05 20:22 )
// @param args ...interface{}
// @return interface{}
// @return error
func ParamsMatchFunc(args ...interface{}) (interface{}, error) {
name1 := args[0].(string)
name2 := args[1].(string)
return (bool)(ParamsMatch(name1, name2)), nil
}
\ No newline at end of file
package service
import (
"errors"
"gin-vue-admin/global"
"gin-vue-admin/model"
"gin-vue-admin/model/request"
)
// @title GetMenuTree
// @description 获取动态菜单树
// @auth (2020/04/05 20:22 )
// @param authorityId string
// @return err error
// @return menus []SysMenu
func GetMenuTree(authorityId string) (err error, menus []model.SysMenu) {
sql := "SELECT authority_menu.created_at,authority_menu.updated_at,authority_menu.deleted_at,authority_menu.menu_level,authority_menu.parent_id,authority_menu.path,authority_menu.`name`,authority_menu.hidden,authority_menu.component,authority_menu.title,authority_menu.icon,authority_menu.sort,authority_menu.menu_id,authority_menu.authority_id FROM authority_menu WHERE authority_menu.authority_id = ? AND authority_menu.parent_id = ?"
err = global.GVA_DB.Raw(sql, authorityId, 0).Scan(&menus).Error
for i := 0; i < len(menus); i++ {
err = getChildrenList(&menus[i], sql)
}
return err, menus
}
// @title getChildrenList
// @description 获取子菜单
// @auth (2020/04/05 20:22 )
// @param menu *SysMenu
// @param SQLstatement string
// @return err error
func getChildrenList(menu *model.SysMenu, sql string) (err error) {
err = global.GVA_DB.Raw(sql, menu.AuthorityId, menu.MenuId).Scan(&menu.Children).Error
for i := 0; i < len(menu.Children); i++ {
err = getChildrenList(&menu.Children[i], sql)
}
return err
}
// @title GetInfoList
// @description 获取路由分页
// @auth (2020/04/05 20:22 )
// @param newPassword string
// @return err error
func GetInfoList(info request.PageInfo) (err error, list interface{}, total int) {
limit := info.PageSize
offset := info.PageSize * (info.Page - 1)
db := global.GVA_DB
if err != nil {
return
} else {
var menuList []model.SysBaseMenu
err = db.Limit(limit).Offset(offset).Where("parent_id = 0").Order("sort", true).Find(&menuList).Error
for i := 0; i < len(menuList); i++ {
err = getBaseChildrenList(&menuList[i])
}
return err, menuList, total
}
}
// @title getBaseChildrenList
// @description get children of menu, 获取菜单的子菜单
// @auth (2020/04/05 20:22 )
// @param menu *SysBaseMenu
// @return err error
func getBaseChildrenList(menu *model.SysBaseMenu) (err error) {
err = global.GVA_DB.Where("parent_id = ?", menu.ID).Order("sort", true).Find(&menu.Children).Error
for i := 0; i < len(menu.Children); i++ {
err = getBaseChildrenList(&menu.Children[i])
}
return err
}
// @title AddBaseMenu
// @description 函数的详细描述
// @auth (2020/04/05 20:22 )
// @param newPassword string
// @return err error
//增加基础路由
func AddBaseMenu(menu model.SysBaseMenu) (err error) {
findOne := global.GVA_DB.Where("name = ?", menu.Name).Find(&model.SysBaseMenu{}).Error
if findOne != nil {
err = global.GVA_DB.Create(menu).Error
} else {
err = errors.New("存在重复name,请修改name")
}
return err
}
// @title GetBaseMenuTree
// @description 获取基础路由树
// @auth (2020/04/05 20:22 )
// @return err error
// @return menus []SysBaseMenu
func GetBaseMenuTree() (err error, menus []model.SysBaseMenu) {
err = global.GVA_DB.Where(" parent_id = ?", 0).Order("sort", true).Find(&menus).Error
for i := 0; i < len(menus); i++ {
err = getBaseChildrenList(&menus[i])
}
return err, menus
}
// @title AddMenuAuthority
// @description 为角色增加menu树
// @auth (2020/04/05 20:22 )
// @param menus []SysBaseMenu
// @param authorityId string
// @return error
func AddMenuAuthority(menus []model.SysBaseMenu, authorityId string) (err error) {
var auth model.SysAuthority
auth.AuthorityId = authorityId
auth.SysBaseMenus = menus
err = SetMenuAuthority(&auth)
return err
}
// @title GetMenuAuthority
// @description 查看当前角色树
// @auth (2020/04/05 20:22 )
// @param authorityId string
// @return err error
// @return menus []SysBaseMenu
func GetMenuAuthority(authorityId string) (err error, menus []model.SysMenu) {
sql := "SELECT authority_menu.created_at,authority_menu.updated_at,authority_menu.deleted_at,authority_menu.menu_level,authority_menu.parent_id,authority_menu.path,authority_menu.`name`,authority_menu.hidden,authority_menu.component,authority_menu.title,authority_menu.icon,authority_menu.sort,authority_menu.menu_id,authority_menu.authority_id FROM authority_menu WHERE authority_menu.authority_id = ?"
err = global.GVA_DB.Raw(sql, authorityId).Scan(&menus).Error
return err, menus
}
\ No newline at end of file
package service
import (
"gin-vue-admin/config"
"gin-vue-admin/global"
"gin-vue-admin/model"
"gin-vue-admin/utils"
)
// @title GetSystemConfig
// @description 读取配置文件
// @auth (2020/04/05 20:22 )
// @return err error
// @return conf Server
func GetSystemConfig() (err error, conf config.Server) {
return nil, global.GVA_CONFIG
}
// @title SetSystemConfig
// @description set system config, 设置配置文件
// @auth (2020/04/05 20:22 )
// @return err error
func SetSystemConfig(s model.System) (err error) {
cs := utils.StructToMap(s.Config)
for k, v := range cs {
global.GVA_VP.Set(k, v)
}
err = global.GVA_VP.WriteConfig()
return err
}
\ No newline at end of file
package service
import (
"errors"
"gin-vue-admin/global"
"gin-vue-admin/model"
"gin-vue-admin/model/request"
"gin-vue-admin/utils"
uuid "github.com/satori/go.uuid"
)
// @title Register
// @description register, 用户注册
// @auth (2020/04/05 20:22 )
// @return err error
// @return userInter *SysUser
func Register(u *model.SysUser) (err error, userInter *model.SysUser) {
var user model.SysUser
//判断用户名是否注册
notRegister := global.GVA_DB.Where("username = ?", u.Username).First(&user).RecordNotFound()
//notRegister为false表明读取到了 不能注册
if !notRegister {
return errors.New("用户名已注册"), nil
} else {
// 否则 附加uuid 密码md5简单加密 注册
u.Password = utils.MD5V([]byte(u.Password))
u.UUID = uuid.NewV4()
err = global.GVA_DB.Create(u).Error
}
return err, u
}
// @title Login
// @description login, 用户登录
// @auth (2020/04/05 20:22 )
// @return err error
// @return userInter *SysUser
func Login(u *model.SysUser) (err error, userInter *model.SysUser) {
var user model.SysUser
u.Password = utils.MD5V([]byte(u.Password))
err = global.GVA_DB.Where("username = ? AND password = ?", u.Username, u.Password).First(&user).Error
if err != nil {
return err, &user
}
err = global.GVA_DB.Where("authority_id = ?", user.AuthorityId).First(&user.Authority).Error
return err, &user
}
// @title ChangePassword
// @description change the password of a certain user, 修改用户密码
// @auth (2020/04/05 20:22 )
// @param newPassword string
// @return err error
// @return userInter *SysUser
func ChangePassword(u *model.SysUser, newPassword string) (err error, userInter *model.SysUser) {
var user model.SysUser
//后期修改jwt+password模式
u.Password = utils.MD5V([]byte(u.Password))
err = global.GVA_DB.Where("username = ? AND password = ?", u.Username, u.Password).First(&user).Update("password", utils.MD5V([]byte(newPassword))).Error
return err, u
}
// @title GetInfoList
// @description get user list by pagination, 分页获取数据
// @auth (2020/04/05 20:22 )
// @param PageInfo int
// @return err error
// @return list interface{}
// @return total int
func GetUserInfoList(info request.PageInfo) (err error, list interface{}, total int) {
limit := info.PageSize
offset := info.PageSize * (info.Page - 1)
db := global.GVA_DB
if err != nil {
return
} else {
var userList []model.SysUser
err = db.Limit(limit).Offset(offset).Preload("Authority").Find(&userList).Error
return err, userList, total
}
}
// @title SetUserAuthority
// @description set the authority of a certain user, 设置一个用户的权限
// @auth (2020/04/05 20:22 )
// @param uuid UUID
// @param authorityId string
// @return err error
func SetUserAuthority(uuid uuid.UUID, authorityId string) (err error) {
err = global.GVA_DB.Where("uuid = ?", uuid).First(&model.SysUser{}).Update("authority_id", authorityId).Error
return err
}
// @title UploadHeaderImg
// @description upload avatar, 用户头像上传更新地址
// @auth (2020/04/05 20:22 )
// @param uuid UUID
// @param filePath string
// @return err error
// @return userInter *SysUser
func UploadHeaderImg(uuid uuid.UUID, filePath string) (err error, userInter *model.SysUser) {
var user model.SysUser
err = global.GVA_DB.Where("uuid = ?", uuid).First(&user).Update("header_img", filePath).First(&user).Error
return err, &user
}
package service
import (
"gin-vue-admin/global"
"gin-vue-admin/model"
)
// @title Create
// @description create a workflow, 创建工作流
// @auth (2020/04/05 20:22 )
// @return error
func Create(wk model.SysWorkflow) error {
err := global.GVA_DB.Create(&wk).Error
return err
}
......@@ -2,6 +2,11 @@ package utils
import "os"
// @title PathExists
// @description 文件目录是否存在
// @auth (2020/04/05 20:22 )
// @param path string
// @return err error
func PathExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
......@@ -12,3 +17,31 @@ func PathExists(path string) (bool, error) {
}
return false, err
}
// @title createDir
// @description 批量创建文件夹
// @auth (2020/04/05 20:22 )
// @param dirs string
// @return err error
func CreateDir(dirs ...string) (err error) {
for _, v := range dirs {
exist, err := PathExists(v)
if err != nil {
//log.L.Info(fmt.Sprintf("get dir error![%v]\n", err))
return err
}
if exist {
//log.L.Info(fmt.Sprintf("has dir![%v]\n"+_dir))
} else {
//log.L.Info(fmt.Sprintf("no dir![%v]\n"+_dir))
// 创建文件夹
err = os.Mkdir(v, os.ModePerm)
if err != nil {
//log.L.Error(fmt.Sprintf("mkdir error![%v]\n",err))
} else {
//log.L.Info("mkdir success!\n")
}
}
}
return err
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册