From 1b1ceefa272046cc6cc51cd75f067d1472e52171 Mon Sep 17 00:00:00 2001 From: pixelqm <303176530@qq.com> Date: Sun, 8 Sep 2019 11:13:43 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E8=8E=B7=E5=8F=96=E8=B7=AF?= =?UTF-8?q?=E7=94=B1=E6=A0=91=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- QMPlusServer/controller/api/menu.go | 27 ++++ QMPlusServer/controller/api/user.go | 90 +++++++++-- QMPlusServer/controller/servers/paging.go | 16 ++ .../{api => servers}/reportformat.go | 2 +- .../controller/{support => servers}/upload.go | 2 +- QMPlusServer/docs/docs.go | 145 +++++++++++++++--- QMPlusServer/docs/swagger.json | 141 +++++++++++++++-- QMPlusServer/docs/swagger.yaml | 96 ++++++++++-- QMPlusServer/init/initRouter/initRouter.go | 2 + QMPlusServer/init/registTable/registTable.go | 2 +- QMPlusServer/main.go | 7 + QMPlusServer/middleware/jwt.go | 24 +-- QMPlusServer/model/dbModel/authority.go | 18 +++ QMPlusServer/model/dbModel/menu.go | 40 +++++ QMPlusServer/model/dbModel/user.go | 30 +++- .../model/modelInterface/interface.go | 14 +- QMPlusServer/router/base.go | 14 ++ QMPlusServer/router/menu.go | 14 ++ QMPlusServer/router/user.go | 6 +- 19 files changed, 588 insertions(+), 102 deletions(-) create mode 100644 QMPlusServer/controller/api/menu.go create mode 100644 QMPlusServer/controller/servers/paging.go rename QMPlusServer/controller/{api => servers}/reportformat.go (93%) rename QMPlusServer/controller/{support => servers}/upload.go (98%) create mode 100644 QMPlusServer/model/dbModel/authority.go create mode 100644 QMPlusServer/model/dbModel/menu.go create mode 100644 QMPlusServer/router/base.go create mode 100644 QMPlusServer/router/menu.go diff --git a/QMPlusServer/controller/api/menu.go b/QMPlusServer/controller/api/menu.go new file mode 100644 index 00000000..7cfc2a49 --- /dev/null +++ b/QMPlusServer/controller/api/menu.go @@ -0,0 +1,27 @@ +package api + +import ( + "fmt" + "github.com/gin-gonic/gin" + "main/controller/servers" + "main/middleware" + "main/model/dbModel" +) + +// @Tags Menu +// @Summary 获取用户动态路由 +// @Security ApiKeyAuth +// @Produce application/json +// @Param data body api.RegistAndLoginStuct true "可以什么都不填" +// @Success 200 {string} json "{"success":true,"data":{},"msg":"返回成功"}" +// @Router /menu/getMenu [post] +func GetMenu(c *gin.Context) { + claims, _ := c.Get("claims") + waitUse := claims.(*middleware.CustomClaims) + err, menus := new(dbModel.Menu).GetMenuTree(waitUse.AuthorityId) + if err != nil { + servers.ReportFormat(c, false, fmt.Sprintf("获取失败:%v", err), gin.H{"menus": menus}) + } else { + servers.ReportFormat(c, true, "获取成功", gin.H{"menus": menus}) + } +} diff --git a/QMPlusServer/controller/api/user.go b/QMPlusServer/controller/api/user.go index 66d2d88c..0a987580 100644 --- a/QMPlusServer/controller/api/user.go +++ b/QMPlusServer/controller/api/user.go @@ -2,10 +2,14 @@ package api import ( "fmt" + "github.com/dgrijalva/jwt-go" "github.com/gin-gonic/gin" - "main/controller/support" + "main/controller/servers" + "main/middleware" "main/model/dbModel" + "main/model/modelInterface" "mime/multipart" + "time" ) var ( @@ -18,12 +22,12 @@ type RegistAndLoginStuct struct { PassWord string `json:"passWord"` } -// @Tags User +// @Tags Base // @Summary 用户注册账号 // @Produce application/json // @Param data body api.RegistAndLoginStuct true "用户注册接口" // @Success 200 {string} json "{"success":true,"data":{},"msg":"注册成功"}" -// @Router /user/regist [post] +// @Router /base/regist [post] func Regist(c *gin.Context) { var R RegistAndLoginStuct _ = c.BindJSON(&R) @@ -31,30 +35,54 @@ func Regist(c *gin.Context) { U := &dbModel.User{UserName: R.UserName, PassWord: R.PassWord} err, user := U.Regist() if err != nil { - ReportFormat(c, false, fmt.Sprintf("%v", err), gin.H{ + servers.ReportFormat(c, false, fmt.Sprintf("%v", err), gin.H{ "user": user, }) } else { - ReportFormat(c, false, "创建成功", gin.H{ + servers.ReportFormat(c, false, "创建成功", gin.H{ "user": user, }) } } -// @Tags User +// @Tags Base // @Summary 用户登录 // @Produce application/json // @Param data body api.RegistAndLoginStuct true "用户登录接口" // @Success 200 {string} json "{"success":true,"data":{},"msg":"登陆成功"}" -// @Router /user/login [post] +// @Router /base/login [post] func Login(c *gin.Context) { var L RegistAndLoginStuct _ = c.BindJSON(&L) U := &dbModel.User{UserName: L.UserName, PassWord: L.PassWord} if err, user := U.Login(); err != nil { - ReportFormat(c, false, "用户名密码错误", gin.H{"user": user}) + servers.ReportFormat(c, false, "用户名密码错误", gin.H{"user": user}) + } else { + tokenNext(c, *user) + } +} + +//登录以后签发jwt +func tokenNext(c *gin.Context, user dbModel.User) { + j := &middleware.JWT{ + []byte("qmPlus"), // 唯一签名 + } + clams := middleware.CustomClaims{ + UUID: user.UUID, + ID: user.ID, + NickName: user.NickName, + AuthorityId: user.AuthorityId, + StandardClaims: jwt.StandardClaims{ + NotBefore: int64(time.Now().Unix() - 1000), // 签名生效时间 + ExpiresAt: int64(time.Now().Unix() + 3600*7), // 过期时间 一周 + Issuer: "qmPlus", //签名的发行者 + }, + } + token, err := j.CreateToken(clams) + if err != nil { + servers.ReportFormat(c, false, "获取token失败", gin.H{}) } else { - ReportFormat(c, true, "登录成功", gin.H{"user": user}) + servers.ReportFormat(c, true, "登录成功", gin.H{"user": user, "token": token}) } } @@ -66,6 +94,7 @@ type ChangePassWordStutrc struct { // @Tags User // @Summary 用户修改密码 +// @Security ApiKeyAuth // @Produce application/json // @Param data body api.ChangePassWordStutrc true "用户修改密码" // @Success 200 {string} json "{"success":true,"data":{},"msg":"修改成功"}" @@ -75,9 +104,9 @@ func ChangePassWord(c *gin.Context) { _ = c.BindJSON(¶ms) U := &dbModel.User{UserName: params.UserName, PassWord: params.PassWord} if err, _ := U.ChangePassWord(params.NewPassWord); err != nil { - ReportFormat(c, false, "修改失败,请检查用户名密码", gin.H{}) + servers.ReportFormat(c, false, "修改失败,请检查用户名密码", gin.H{}) } else { - ReportFormat(c, true, "修改成功", gin.H{}) + servers.ReportFormat(c, true, "修改成功", gin.H{}) } } @@ -87,6 +116,7 @@ type UserHeaderImg struct { // @Tags User // @Summary 用户上传头像 +// @Security ApiKeyAuth // @accept multipart/form-data // @Produce application/json // @Param headerImg formData file true "用户上传头像" @@ -94,26 +124,54 @@ type UserHeaderImg struct { // @Success 200 {string} json "{"success":true,"data":{},"msg":"上传成功"}" // @Router /user/uploadHeaderImg [post] func UploadHeaderImg(c *gin.Context) { + claims, _ := c.Get("claims") //获取头像文件 + // 这里我们通过断言获取 claims内的所有内容 + waitUse := claims.(*middleware.CustomClaims) + fmt.Println(waitUse.NickName) _, header, err := c.Request.FormFile("headerImg") //便于找到用户 以后从jwt中取 userName := c.PostForm("userName") if err != nil { - ReportFormat(c, false, fmt.Sprintf("上传文件失败,%v", err), gin.H{}) + servers.ReportFormat(c, false, fmt.Sprintf("上传文件失败,%v", err), gin.H{}) } else { //文件上传后拿到文件路径 - err, filePath := support.Upload(header, USER_HEADER_BUCKET, USER_HEADER_IMG_PATH) + err, filePath := servers.Upload(header, USER_HEADER_BUCKET, USER_HEADER_IMG_PATH) if err != nil { - ReportFormat(c, false, fmt.Sprintf("接收返回值失败,%v", err), gin.H{}) + servers.ReportFormat(c, false, fmt.Sprintf("接收返回值失败,%v", err), gin.H{}) } else { //修改数据库后得到修改后的user并且返回供前端使用 err, user := new(dbModel.User).UploadHeaderImg(userName, filePath) if err != nil { - ReportFormat(c, false, fmt.Sprintf("修改数据库链接失败,%v", err), gin.H{}) + servers.ReportFormat(c, false, fmt.Sprintf("修改数据库链接失败,%v", err), gin.H{}) } else { - ReportFormat(c, true, "上传成功", gin.H{"user": user}) + servers.ReportFormat(c, true, "上传成功", gin.H{"user": user}) } } } } + +// @Tags User +// @Summary 分页获取用户列表 +// @Security ApiKeyAuth +// @accept application/json +// @Produce application/json +// @Param data body modelInterface.PageInfo true "分页获取用户列表" +// @Success 200 {string} json "{"success":true,"data":{},"msg":"获取成功"}" +// @Router /user/getInfoList [post] +func GetInfoList(c *gin.Context) { + var pageInfo modelInterface.PageInfo + _ = c.BindJSON(&pageInfo) + err, list, total := new(dbModel.User).GetInfoList(pageInfo) + if err != nil { + servers.ReportFormat(c, false, fmt.Sprintf("获取数据失败,%v", err), gin.H{}) + } else { + servers.ReportFormat(c, true, "获取数据成功", gin.H{ + "userList": list, + "total": total, + "page": pageInfo.Page, + "pageSize": pageInfo.PageSize, + }) + } +} diff --git a/QMPlusServer/controller/servers/paging.go b/QMPlusServer/controller/servers/paging.go new file mode 100644 index 00000000..47a5dc98 --- /dev/null +++ b/QMPlusServer/controller/servers/paging.go @@ -0,0 +1,16 @@ +package servers + +import ( + "github.com/jinzhu/gorm" + "main/init/qmsql" + "main/model/modelInterface" +) + +//获取分页功能 接收实现了分页接口的结构体 返回搜索完成的结果 许需要自行scan 或者fand +func PagingServer(paging modelInterface.Paging, info modelInterface.PageInfo) (err error, db *gorm.DB, total int) { + limit := info.PageSize + offset := info.PageSize * (info.Page - 1) + err = qmsql.DEFAULTDB.Model(paging).Count(&total).Error + db = qmsql.DEFAULTDB.Limit(limit).Offset(offset) + return err, db, total +} diff --git a/QMPlusServer/controller/api/reportformat.go b/QMPlusServer/controller/servers/reportformat.go similarity index 93% rename from QMPlusServer/controller/api/reportformat.go rename to QMPlusServer/controller/servers/reportformat.go index 52746847..2b935fea 100644 --- a/QMPlusServer/controller/api/reportformat.go +++ b/QMPlusServer/controller/servers/reportformat.go @@ -1,4 +1,4 @@ -package api +package servers import ( "github.com/gin-gonic/gin" diff --git a/QMPlusServer/controller/support/upload.go b/QMPlusServer/controller/servers/upload.go similarity index 98% rename from QMPlusServer/controller/support/upload.go rename to QMPlusServer/controller/servers/upload.go index ddb05676..2c632239 100644 --- a/QMPlusServer/controller/support/upload.go +++ b/QMPlusServer/controller/servers/upload.go @@ -1,4 +1,4 @@ -package support +package servers import ( "context" diff --git a/QMPlusServer/docs/docs.go b/QMPlusServer/docs/docs.go index afcd9e37..b42d701e 100644 --- a/QMPlusServer/docs/docs.go +++ b/QMPlusServer/docs/docs.go @@ -1,6 +1,6 @@ // GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // This file was generated by swaggo/swag at -// 2019-09-05 23:15:39.7963441 +0800 CST m=+0.062832501 +// 2019-09-07 22:49:45.2497438 +0800 CST m=+0.040919801 package docs @@ -26,30 +26,30 @@ var doc = `{ "host": "{{.Host}}", "basePath": "{{.BasePath}}", "paths": { - "/user/changePassWord": { + "/base/login": { "post": { "produces": [ "application/json" ], "tags": [ - "User" + "Base" ], - "summary": "用户修改密码", + "summary": "用户登录", "parameters": [ { - "description": "用户修改密码", + "description": "用户登录接口", "name": "data", "in": "body", "required": true, "schema": { "type": "object", - "$ref": "#/definitions/api.ChangePassWordStutrc" + "$ref": "#/definitions/api.RegistAndLoginStuct" } } ], "responses": { "200": { - "description": "{\"success\":true,\"data\":{},\"msg\":\"修改成功\"}", + "description": "{\"success\":true,\"data\":{},\"msg\":\"登陆成功\"}", "schema": { "type": "string" } @@ -57,18 +57,18 @@ var doc = `{ } } }, - "/user/login": { + "/base/regist": { "post": { "produces": [ "application/json" ], "tags": [ - "User" + "Base" ], - "summary": "用户登录", + "summary": "用户注册账号", "parameters": [ { - "description": "用户登录接口", + "description": "用户注册接口", "name": "data", "in": "body", "required": true, @@ -80,7 +80,7 @@ var doc = `{ ], "responses": { "200": { - "description": "{\"success\":true,\"data\":{},\"msg\":\"登陆成功\"}", + "description": "{\"success\":true,\"data\":{},\"msg\":\"注册成功\"}", "schema": { "type": "string" } @@ -88,18 +88,23 @@ var doc = `{ } } }, - "/user/regist": { + "/menu/getMenu": { "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], "produces": [ "application/json" ], "tags": [ - "User" + "Menu" ], - "summary": "用户注册账号", + "summary": "获取用户动态路由", "parameters": [ { - "description": "用户注册接口", + "description": "可以什么都不填", "name": "data", "in": "body", "required": true, @@ -111,7 +116,82 @@ var doc = `{ ], "responses": { "200": { - "description": "{\"success\":true,\"data\":{},\"msg\":\"注册成功\"}", + "description": "{\"success\":true,\"data\":{},\"msg\":\"返回成功\"}", + "schema": { + "type": "string" + } + } + } + } + }, + "/user/changePassWord": { + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "用户修改密码", + "parameters": [ + { + "description": "用户修改密码", + "name": "data", + "in": "body", + "required": true, + "schema": { + "type": "object", + "$ref": "#/definitions/api.ChangePassWordStutrc" + } + } + ], + "responses": { + "200": { + "description": "{\"success\":true,\"data\":{},\"msg\":\"修改成功\"}", + "schema": { + "type": "string" + } + } + } + } + }, + "/user/getInfoList": { + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "分页获取用户列表", + "parameters": [ + { + "description": "分页获取用户列表", + "name": "data", + "in": "body", + "required": true, + "schema": { + "type": "object", + "$ref": "#/definitions/modelInterface.PageInfo" + } + } + ], + "responses": { + "200": { + "description": "{\"success\":true,\"data\":{},\"msg\":\"获取成功\"}", "schema": { "type": "string" } @@ -121,6 +201,11 @@ var doc = `{ }, "/user/uploadHeaderImg": { "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], "consumes": [ "multipart/form-data" ], @@ -183,6 +268,24 @@ var doc = `{ "type": "string" } } + }, + "modelInterface.PageInfo": { + "type": "object", + "properties": { + "page": { + "type": "integer" + }, + "pageSize": { + "type": "integer" + } + } + } + }, + "securityDefinitions": { + "ApiKeyAuth": { + "type": "apiKey", + "name": "x-token", + "in": "header" } } }` @@ -198,12 +301,12 @@ type swaggerInfo struct { // SwaggerInfo holds exported Swagger Info so clients can modify it var SwaggerInfo = swaggerInfo{ - Version: "", + Version: "0.0.1", Host: "", - BasePath: "", + BasePath: "/", Schemes: []string{}, - Title: "", - Description: "", + Title: "Swagger Example API", + Description: "This is a sample Server pets", } type s struct{} diff --git a/QMPlusServer/docs/swagger.json b/QMPlusServer/docs/swagger.json index 8a6ea823..1cf47955 100644 --- a/QMPlusServer/docs/swagger.json +++ b/QMPlusServer/docs/swagger.json @@ -1,34 +1,38 @@ { "swagger": "2.0", "info": { + "description": "This is a sample Server pets", + "title": "Swagger Example API", "contact": {}, - "license": {} + "license": {}, + "version": "0.0.1" }, + "basePath": "/", "paths": { - "/user/changePassWord": { + "/base/login": { "post": { "produces": [ "application/json" ], "tags": [ - "User" + "Base" ], - "summary": "用户修改密码", + "summary": "用户登录", "parameters": [ { - "description": "用户修改密码", + "description": "用户登录接口", "name": "data", "in": "body", "required": true, "schema": { "type": "object", - "$ref": "#/definitions/api.ChangePassWordStutrc" + "$ref": "#/definitions/api.RegistAndLoginStuct" } } ], "responses": { "200": { - "description": "{\"success\":true,\"data\":{},\"msg\":\"修改成功\"}", + "description": "{\"success\":true,\"data\":{},\"msg\":\"登陆成功\"}", "schema": { "type": "string" } @@ -36,18 +40,18 @@ } } }, - "/user/login": { + "/base/regist": { "post": { "produces": [ "application/json" ], "tags": [ - "User" + "Base" ], - "summary": "用户登录", + "summary": "用户注册账号", "parameters": [ { - "description": "用户登录接口", + "description": "用户注册接口", "name": "data", "in": "body", "required": true, @@ -59,7 +63,7 @@ ], "responses": { "200": { - "description": "{\"success\":true,\"data\":{},\"msg\":\"登陆成功\"}", + "description": "{\"success\":true,\"data\":{},\"msg\":\"注册成功\"}", "schema": { "type": "string" } @@ -67,18 +71,23 @@ } } }, - "/user/regist": { + "/menu/getMenu": { "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], "produces": [ "application/json" ], "tags": [ - "User" + "Menu" ], - "summary": "用户注册账号", + "summary": "获取用户动态路由", "parameters": [ { - "description": "用户注册接口", + "description": "可以什么都不填", "name": "data", "in": "body", "required": true, @@ -90,7 +99,82 @@ ], "responses": { "200": { - "description": "{\"success\":true,\"data\":{},\"msg\":\"注册成功\"}", + "description": "{\"success\":true,\"data\":{},\"msg\":\"返回成功\"}", + "schema": { + "type": "string" + } + } + } + } + }, + "/user/changePassWord": { + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "用户修改密码", + "parameters": [ + { + "description": "用户修改密码", + "name": "data", + "in": "body", + "required": true, + "schema": { + "type": "object", + "$ref": "#/definitions/api.ChangePassWordStutrc" + } + } + ], + "responses": { + "200": { + "description": "{\"success\":true,\"data\":{},\"msg\":\"修改成功\"}", + "schema": { + "type": "string" + } + } + } + } + }, + "/user/getInfoList": { + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "分页获取用户列表", + "parameters": [ + { + "description": "分页获取用户列表", + "name": "data", + "in": "body", + "required": true, + "schema": { + "type": "object", + "$ref": "#/definitions/modelInterface.PageInfo" + } + } + ], + "responses": { + "200": { + "description": "{\"success\":true,\"data\":{},\"msg\":\"获取成功\"}", "schema": { "type": "string" } @@ -100,6 +184,11 @@ }, "/user/uploadHeaderImg": { "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], "consumes": [ "multipart/form-data" ], @@ -162,6 +251,24 @@ "type": "string" } } + }, + "modelInterface.PageInfo": { + "type": "object", + "properties": { + "page": { + "type": "integer" + }, + "pageSize": { + "type": "integer" + } + } + } + }, + "securityDefinitions": { + "ApiKeyAuth": { + "type": "apiKey", + "name": "x-token", + "in": "header" } } } \ No newline at end of file diff --git a/QMPlusServer/docs/swagger.yaml b/QMPlusServer/docs/swagger.yaml index f180d470..22e43ef8 100644 --- a/QMPlusServer/docs/swagger.yaml +++ b/QMPlusServer/docs/swagger.yaml @@ -1,3 +1,4 @@ +basePath: / definitions: api.ChangePassWordStutrc: properties: @@ -15,34 +16,44 @@ definitions: userName: type: string type: object + modelInterface.PageInfo: + properties: + page: + type: integer + pageSize: + type: integer + type: object info: contact: {} + description: This is a sample Server pets license: {} + title: Swagger Example API + version: 0.0.1 paths: - /user/changePassWord: + /base/login: post: parameters: - - description: 用户修改密码 + - description: 用户登录接口 in: body name: data required: true schema: - $ref: '#/definitions/api.ChangePassWordStutrc' + $ref: '#/definitions/api.RegistAndLoginStuct' type: object produces: - application/json responses: "200": - description: '{"success":true,"data":{},"msg":"修改成功"}' + description: '{"success":true,"data":{},"msg":"登陆成功"}' schema: type: string - summary: 用户修改密码 + summary: 用户登录 tags: - - User - /user/login: + - Base + /base/regist: post: parameters: - - description: 用户登录接口 + - description: 用户注册接口 in: body name: data required: true @@ -53,16 +64,16 @@ paths: - application/json responses: "200": - description: '{"success":true,"data":{},"msg":"登陆成功"}' + description: '{"success":true,"data":{},"msg":"注册成功"}' schema: type: string - summary: 用户登录 + summary: 用户注册账号 tags: - - User - /user/regist: + - Base + /menu/getMenu: post: parameters: - - description: 用户注册接口 + - description: 可以什么都不填 in: body name: data required: true @@ -73,10 +84,58 @@ paths: - application/json responses: "200": - description: '{"success":true,"data":{},"msg":"注册成功"}' + description: '{"success":true,"data":{},"msg":"返回成功"}' schema: type: string - summary: 用户注册账号 + security: + - ApiKeyAuth: [] + summary: 获取用户动态路由 + tags: + - Menu + /user/changePassWord: + post: + parameters: + - description: 用户修改密码 + in: body + name: data + required: true + schema: + $ref: '#/definitions/api.ChangePassWordStutrc' + type: object + produces: + - application/json + responses: + "200": + description: '{"success":true,"data":{},"msg":"修改成功"}' + schema: + type: string + security: + - ApiKeyAuth: [] + summary: 用户修改密码 + tags: + - User + /user/getInfoList: + post: + consumes: + - application/json + parameters: + - description: 分页获取用户列表 + in: body + name: data + required: true + schema: + $ref: '#/definitions/modelInterface.PageInfo' + type: object + produces: + - application/json + responses: + "200": + description: '{"success":true,"data":{},"msg":"获取成功"}' + schema: + type: string + security: + - ApiKeyAuth: [] + summary: 分页获取用户列表 tags: - User /user/uploadHeaderImg: @@ -101,7 +160,14 @@ paths: description: '{"success":true,"data":{},"msg":"上传成功"}' schema: type: string + security: + - ApiKeyAuth: [] summary: 用户上传头像 tags: - User +securityDefinitions: + ApiKeyAuth: + in: header + name: x-token + type: apiKey swagger: "2.0" diff --git a/QMPlusServer/init/initRouter/initRouter.go b/QMPlusServer/init/initRouter/initRouter.go index 9297d8e9..f49bd3a3 100644 --- a/QMPlusServer/init/initRouter/initRouter.go +++ b/QMPlusServer/init/initRouter/initRouter.go @@ -14,5 +14,7 @@ func InitRouter() *gin.Engine { Router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) //Router.Use(middleware.Logger()) router.InitUserRouter(Router) + router.InitBaseRouter(Router) + router.InitMenuRouter(Router) return Router } diff --git a/QMPlusServer/init/registTable/registTable.go b/QMPlusServer/init/registTable/registTable.go index 7ffaa83f..bff8b9e1 100644 --- a/QMPlusServer/init/registTable/registTable.go +++ b/QMPlusServer/init/registTable/registTable.go @@ -7,5 +7,5 @@ import ( //注册数据库表专用 func RegistTable(db *gorm.DB) { - db.AutoMigrate(dbModel.User{}) + db.AutoMigrate(dbModel.User{}, dbModel.Authority{}, dbModel.Menu{}) } diff --git a/QMPlusServer/main.go b/QMPlusServer/main.go index 2b744763..2925090b 100644 --- a/QMPlusServer/main.go +++ b/QMPlusServer/main.go @@ -10,6 +10,13 @@ import ( "time" ) +// @title Swagger Example API +// @version 0.0.1 +// @description This is a sample Server pets +// @securityDefinitions.apikey ApiKeyAuth +// @in header +// @name x-token +// @BasePath / func main() { qmlog.InitLog() registTable.RegistTable(qmsql.InitMysql(config.Dbconfig.Admin)) diff --git a/QMPlusServer/middleware/jwt.go b/QMPlusServer/middleware/jwt.go index 9fb1ccf9..c037cd30 100644 --- a/QMPlusServer/middleware/jwt.go +++ b/QMPlusServer/middleware/jwt.go @@ -5,19 +5,16 @@ import ( "github.com/dgrijalva/jwt-go" "github.com/gin-gonic/gin" uuid "github.com/satori/go.uuid" - "net/http" + "main/controller/servers" "time" ) func JWTAuth() gin.HandlerFunc { return func(c *gin.Context) { + // 我们这里jwt鉴权取头部信息 x-token 登录时回返回token信息 这里前端需要把token存储到cookie或者本地localSstorage中 不过需要跟后端协商过期时间 可以约定刷新令牌或者重新登录 token := c.Request.Header.Get("x-token") if token == "" { - c.JSON(http.StatusOK, gin.H{ - "success": false, - "msg": "未登录或非法访问", - "data": gin.H{}, - }) + servers.ReportFormat(c, false, "未登录或非法访问", gin.H{}) c.Abort() return } @@ -26,17 +23,11 @@ func JWTAuth() gin.HandlerFunc { claims, err := j.ParseToken(token) if err != nil { if err == TokenExpired { - c.JSON(http.StatusOK, gin.H{ - "success": false, - "msg": "授权已过期", - }) + servers.ReportFormat(c, false, "授权已过期", gin.H{}) c.Abort() return } - c.JSON(http.StatusOK, gin.H{ - "success": false, - "msg": err.Error(), - }) + servers.ReportFormat(c, false, err.Error(), gin.H{}) c.Abort() return } @@ -53,13 +44,14 @@ var ( TokenNotValidYet error = errors.New("Token not active yet") TokenMalformed error = errors.New("That's not even a token") TokenInvalid error = errors.New("Couldn't handle this token:") - SignKey string = "newtrekWang" + SignKey string = "qmPlus" ) type CustomClaims struct { UUID uuid.UUID ID uint - AuthorityID uint + NickName string + AuthorityId float64 jwt.StandardClaims } diff --git a/QMPlusServer/model/dbModel/authority.go b/QMPlusServer/model/dbModel/authority.go new file mode 100644 index 00000000..211849a3 --- /dev/null +++ b/QMPlusServer/model/dbModel/authority.go @@ -0,0 +1,18 @@ +package dbModel + +import ( + "github.com/jinzhu/gorm" + "main/init/qmsql" +) + +type Authority struct { + gorm.Model `json:"-"` + AuthorityId uint `json:"authorityId"` + AuthorityName string `json:"authorityName"` + Menus []Menu `json:"_"` +} + +func (a *Authority) CreateAuthority() (err error, authority *Authority) { + err = qmsql.DEFAULTDB.Create(a).Error + return err, a +} diff --git a/QMPlusServer/model/dbModel/menu.go b/QMPlusServer/model/dbModel/menu.go new file mode 100644 index 00000000..15415234 --- /dev/null +++ b/QMPlusServer/model/dbModel/menu.go @@ -0,0 +1,40 @@ +package dbModel + +import ( + "github.com/jinzhu/gorm" + "main/init/qmsql" +) + +type Menu struct { + gorm.Model `json:"-"` + MenuLevel uint `json:"-"` + AuthorityId uint `json:"-"` + ParentId uint `json:"parentId"` + Path string `json:"path"` + Name string `json:"name"` + Hidden bool `json:"hidden"` + Component string `json:"component"` + Meta `json:"meta"` + Children []Menu `json:"children"` +} + +type Meta struct { + Title string `json:"title"` + Icon string `json:"icon"` +} + +func (m *Menu) GetMenuTree(authorityId float64) (err error, menus []Menu) { + err = qmsql.DEFAULTDB.Where("authority_id = ? AND parent_id = ?", authorityId, 0).Find(&menus).Error + for i := 0; i < len(menus); i++ { + err = getChildrenList(&menus[i]) + } + return err, menus +} + +func getChildrenList(menu *Menu) (err error) { + err = qmsql.DEFAULTDB.Where("authority_id = ? AND parent_id = ?", menu.AuthorityId, menu.ID).Find(&menu.Children).Error + for i := 0; i < len(menu.Children); i++ { + err = getChildrenList(&menu.Children[i]) + } + return err +} diff --git a/QMPlusServer/model/dbModel/user.go b/QMPlusServer/model/dbModel/user.go index dd1047e5..ae551799 100644 --- a/QMPlusServer/model/dbModel/user.go +++ b/QMPlusServer/model/dbModel/user.go @@ -4,17 +4,21 @@ import ( "github.com/jinzhu/gorm" "github.com/pkg/errors" uuid "github.com/satori/go.uuid" + "main/controller/servers" "main/init/qmsql" + "main/model/modelInterface" "main/tools" ) type User struct { - gorm.Model `json:"-"` - UUID uuid.UUID `json:"uuid"` - 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'"` + gorm.Model `json:"-"` + UUID uuid.UUID `json:"uuid"` + 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'"` + Authority Authority `json:"authority" form:"ForeignKey:AuthorityId;AssociationForeignKey:AuthorityId"` + AuthorityId float64 `json:"authorityId" gorm:"default:888"` //Propertie // 多余属性自行添加 //PropertieId uint // 自动关联 Propertie 的Id 附加属性过多 建议创建一对一关系 } @@ -60,6 +64,7 @@ func (u *User) Login() (err error, userInter *User) { var user User u.PassWord = tools.MD5V(u.PassWord) err = qmsql.DEFAULTDB.Where("user_name = ? AND pass_word = ?", u.UserName, u.PassWord).First(&user).Error + err = qmsql.DEFAULTDB.Model(&user).Related(&user.Authority).Error return err, &user } @@ -69,3 +74,16 @@ func (u *User) UploadHeaderImg(userName string, filePath string) (err error, use err = qmsql.DEFAULTDB.Where("user_name = ?", userName).First(&user).Update("header_img", filePath).First(&user).Error return err, &user } + +// 分页获取数据 需要分页实现这个接口即可 +func (u *User) GetInfoList(info modelInterface.PageInfo) (err error, list interface{}, total int) { + // 封装分页方法 调用即可 传入 当前的结构体和分页信息 + err, db, total := servers.PagingServer(u, info) + if err != nil { + return + } else { + var userList []User + err = db.Find(&userList).Error + return err, userList, total + } +} diff --git a/QMPlusServer/model/modelInterface/interface.go b/QMPlusServer/model/modelInterface/interface.go index 11c1cbe4..af7f88bb 100644 --- a/QMPlusServer/model/modelInterface/interface.go +++ b/QMPlusServer/model/modelInterface/interface.go @@ -2,9 +2,13 @@ package modelInterface // 因为我也不确定项目要不要多人维护 所以定义了CURD接口 作为接口参考 // 由于很多接口使用Restful模式 暂时不用泛型 有需要可以iss提供示例 -type CURD interface { - Create() (error, CURD) - Updata() (error, CURD) - Read() (error, CURD) - Delete() (error, CURD) + +type PageInfo struct { + Page int + PageSize int +} + +//分页接口 +type Paging interface { + GetInfoList(PageInfo) (err error, list interface{}, total int) } diff --git a/QMPlusServer/router/base.go b/QMPlusServer/router/base.go new file mode 100644 index 00000000..e2c92710 --- /dev/null +++ b/QMPlusServer/router/base.go @@ -0,0 +1,14 @@ +package router + +import ( + "github.com/gin-gonic/gin" + "main/controller/api" +) + +func InitBaseRouter(Router *gin.Engine) { + UserRouter := Router.Group("base") + { + UserRouter.POST("regist", api.Regist) + UserRouter.POST("login", api.Login) + } +} diff --git a/QMPlusServer/router/menu.go b/QMPlusServer/router/menu.go new file mode 100644 index 00000000..bd071e2c --- /dev/null +++ b/QMPlusServer/router/menu.go @@ -0,0 +1,14 @@ +package router + +import ( + "github.com/gin-gonic/gin" + "main/controller/api" + "main/middleware" +) + +func InitMenuRouter(Router *gin.Engine) { + MenuRouter := Router.Group("menu").Use(middleware.JWTAuth()) + { + MenuRouter.POST("getMenu", api.GetMenu) + } +} diff --git a/QMPlusServer/router/user.go b/QMPlusServer/router/user.go index 3cda13b4..d1c5c23c 100644 --- a/QMPlusServer/router/user.go +++ b/QMPlusServer/router/user.go @@ -3,14 +3,14 @@ package router import ( "github.com/gin-gonic/gin" "main/controller/api" + "main/middleware" ) func InitUserRouter(Router *gin.Engine) { - UserRouter := Router.Group("user") + UserRouter := Router.Group("user").Use(middleware.JWTAuth()) { - UserRouter.POST("regist", api.Regist) - UserRouter.POST("login", api.Login) UserRouter.POST("changePassWord", api.ChangePassWord) UserRouter.POST("uploadHeaderImg", api.UploadHeaderImg) + UserRouter.POST("getInfoList", api.GetInfoList) } } -- GitLab