作者 yangfu

branch fix bug

Squashed commit of the following:

commit 65f30f27951df5823526895d94c89ab0b8b49871
Author: yangfu <785409885@qq.com>
Date:   Wed Nov 18 15:14:17 2020 +0800

    1.操作日志修改
    2.客户端公共接口

commit 5602dfb1b9961cce87a9e08480e281d3fdad2771
Author: yangfu <785409885@qq.com>
Date:   Mon Nov 16 14:24:19 2020 +0800

    1.修复功能异常

commit 779c973def3e3c1ac9b0aa02e289aa3a24600ede
Author: yangfu <785409885@qq.com>
Date:   Wed Nov 11 16:00:19 2020 +0800

    1.token修改  2.查询操作不使用事务
... ... @@ -9,6 +9,7 @@ require (
github.com/go-pg/pg/v10 v10.0.0-beta.2
//github.com/tal-tech/go-zero v1.0.11
github.com/linmadan/egglib-go v0.0.0-20191217144343-ca4539f95bf9
github.com/stretchr/testify v1.5.1
//github.com/opentracing/opentracing-go v1.1.1-0.20190913142402-a7454ce5950e
//github.com/openzipkin-contrib/zipkin-go-opentracing v0.4.5
//github.com/openzipkin/zipkin-go v0.2.5
... ...
... ... @@ -50,10 +50,12 @@ func (svr *AuthService) Login(header *protocol.RequestHeader, request *protocolx
err = protocol.NewCustomMessage(1, "该账号已被禁用!")
return
}
token, _ := common.GenerateToken(fmt.Sprintf("%v", user.Id), user.Passwd, common.WithExpire(domain.TokenExpire), common.WithAddData(map[string]interface{}{"UserName": user.Name}))
token, _ := common.GenerateToken(fmt.Sprintf("%v", user.Id), user.Passwd, common.WithExpire(domain.TokenExpire), common.WithAddData(map[string]interface{}{"UserName": user.Name, "Phone": user.Phone}))
refreshToken, _ := common.GenerateToken(fmt.Sprintf("%v", user.Id), user.Passwd, common.WithExpire(domain.RefreshTokenExpire), common.WithAddData(map[string]interface{}{"UserName": user.Name, "Phone": user.Phone}))
rsp.Access = map[string]interface{}{
"accessToken": token, //"Bearer " + token,
"expiresIn": domain.TokenExpire,
"accessToken": token,
"refreshToken": refreshToken,
"expiresIn": domain.TokenExpire,
}
cache.Delete(cachex.UserRoleAccessCacheKey(user.Id))
... ... @@ -81,6 +83,37 @@ func (svr *AuthService) Logout(header *protocol.RequestHeader, request *protocol
return
}
func (svr *AuthService) Refresh(header *protocol.RequestHeader, request *protocolx.RefreshRequest) (rsp interface{}, err error) {
var (
//transactionContext, _ = factory.CreateTransactionContext(nil)
)
//transactionContext.SetTransactionClose()
rsp = &protocolx.RefreshResponse{}
if err = request.ValidateCommand(); err != nil {
err = protocol.NewCustomMessage(2, err.Error())
return
}
//if err = transactionContext.StartTransaction(); err != nil {
// log.Error(err)
// return nil, err
//}
//defer func() {
// transactionContext.RollbackTransaction()
//}()
claim, e := common.ParseJWTToken(request.RefreshToken)
if e != nil {
log.Error(e)
err = protocol.NewCustomMessage(-2, "权限过期,请重新登录")
return
}
log.Debug(claim.Username, claim.Password, time.Unix(claim.ExpiresAt, 0))
rsp, err = svr.Login(header, &protocolx.LoginRequest{UserName: (claim.AddData["Phone"]).(string), Password: claim.Password})
//err = transactionContext.CommitTransaction()
return
}
func (svr *AuthService) Profile(header *protocol.RequestHeader, request *protocolx.ProfileRequest) (rsp interface{}, err error) {
var (
transactionContext, _ = factory.CreateTransactionContext(nil)
... ... @@ -187,16 +220,20 @@ func (svr *AuthService) ChangePassword(header *protocol.RequestHeader, request *
transactionContext.RollbackTransaction()
}()
if claim, e := common.ParseJWTToken(header.Token); e == nil && len(request.Phone) == 0 {
request.Phone = claim.AddData["Phone"].(string)
}
var user *domain.Users
if user, err = UserRepository.FindOne(map[string]interface{}{"phone": request.Phone}); err != nil {
err = protocol.NewCustomMessage(1, "用户不存在")
return
}
if user.Passwd != request.OldPwd {
err = protocol.NewCustomMessage(1, "旧密码输入有误")
return
}
user.Passwd = request.NewPwd
//if user.Passwd != request.OldPwd {
// err = protocol.NewCustomMessage(1, "旧密码输入有误")
// return
//}
user.Passwd = request.Password
if _, err = UserRepository.Save(user); err != nil {
return
}
... ...
... ... @@ -2,6 +2,7 @@ package project_module_files
import (
"bytes"
"fmt"
"github.com/tiptok/gocomm/common"
"github.com/tiptok/gocomm/pkg/log"
"gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/application/factory"
... ... @@ -11,6 +12,7 @@ import (
"gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/protocol"
protocolx "gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/protocol/project_module_files"
"path/filepath"
"strconv"
"strings"
"time"
)
... ... @@ -238,7 +240,7 @@ func (svr *ProjectModuleFilesService) ListProjectModuleFiles(header *protocol.Re
}
rsp = map[string]interface{}{
"total": total,
"list": utils.LoadCustomField(projectModuleFiles, "Id", "FileType", "FileName", "ParentId", "Path", "CodeBlock"),
"list": utils.LoadCustomField(projectModuleFiles, "Id", "FileType", "FileName", "ParentId", "Path", "CodeBlock", "Tag"),
}
if request.StructType == "tree" {
rsp = map[string]interface{}{
... ... @@ -321,6 +323,51 @@ func (svr *ProjectModuleFilesService) Import(header *protocol.RequestHeader, req
return
}
// ReviseTag
// 修订标签
func (svr *ProjectModuleFilesService) ReviseTag(header *protocol.RequestHeader, request *protocolx.ReviseTagRequest) (rsp interface{}, err error) {
var (
transactionContext, _ = factory.CreateTransactionContext(nil)
)
rsp = &protocolx.ReviseTagResponse{}
if err = request.ValidateCommand(); err != nil {
err = protocol.NewCustomMessage(2, err.Error())
return
}
if err = transactionContext.StartTransaction(); err != nil {
log.Error(err)
return nil, err
}
defer func() {
transactionContext.RollbackTransaction()
}()
var ProjectModuleFilesRepository, _ = factory.CreateProjectModuleFilesRepository(transactionContext)
var projectModuleFiles *domain.ProjectModuleFiles
if projectModuleFiles, err = ProjectModuleFilesRepository.FindOne(map[string]interface{}{"id": request.Id}); err != nil {
return
}
var lastTag string
// 为传入tag,自动生成一个tag
if len(request.Tag) == 0 {
if lastProjectModuleFiles, e := ProjectModuleFilesRepository.FindOne(map[string]interface{}{
"projectModuleId": projectModuleFiles.ProjectModuleId,
"projectModuleVersionId": projectModuleFiles.ProjectModuleVersionId, "path": projectModuleFiles.Path, "orderByTag": "DESC"}); e == nil {
lastTag = lastProjectModuleFiles.Tag
}
}
lastTag = makeTag(lastTag)
projectModuleFiles.Tag = lastTag
projectModuleFiles.Id = 0
if rsp, err = ProjectModuleFilesRepository.Save(projectModuleFiles); err != nil {
return
}
err = transactionContext.CommitTransaction()
return
}
func (svr *ProjectModuleFilesService) save(request *domain.ProjectModuleFiles, ProjectModuleFilesRepository domain.ProjectModuleFilesRepository) (rsp *domain.ProjectModuleFiles, err error) {
if request.ParentId > 0 {
if pfile, e := ProjectModuleFilesRepository.FindOne(map[string]interface{}{"id": request.ParentId, "projectModuleId": request.ProjectModuleId, "projectModuleVersionId": request.ProjectModuleVersionId}); e != nil {
... ... @@ -416,3 +463,27 @@ func NewProjectModuleFilesService(options map[string]interface{}) *ProjectModule
svr := &ProjectModuleFilesService{}
return svr
}
func makeTag(lastTag string) string {
if len(lastTag) == 0 {
return "v0.1"
}
rspTag := lastTag + common.RandomString(1)
if strings.Index(lastTag, "v") < 0 {
return rspTag
}
lastTag = lastTag[1:]
rspTag = "v"
splitTag := strings.Split(lastTag, ".")
for i, v := range splitTag {
version, _ := strconv.Atoi(v)
if version > 0 {
return fmt.Sprintf("%v%v", rspTag, version+1)
}
rspTag += v
if i+1 != len(splitTag) {
rspTag += "."
}
}
return rspTag + common.RandomString(1)
}
... ...
package project_module_files
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestMakeTag(t *testing.T) {
input := []struct {
InTag string
ExceptTag string
}{
{"", "v0.1"},
{"v1", "v2"},
{"v0.1", "v0.2"},
{"v0.0.1", "v0.0.2"},
{"v1.1", "v2"},
{"v0.1.1", "v0.2"},
{"v9", "v10"},
}
for _, v := range input {
assert.Equal(t, v.ExceptTag, makeTag(v.InTag))
}
}
... ...
... ... @@ -65,6 +65,9 @@ func (svr *ProjectModuleVersionService) CreateProjectModuleVersion(header *proto
if err = ProjectModuleDao.DuplicateVersion(srcVersion.ProjectModuleId, srcVersion.Id, currentPMVersionId); err != nil {
return
}
if err = ProjectModuleDao.FixParentIdByPath(srcVersion.ProjectModuleId, currentPMVersionId); err != nil {
return
}
err = transactionContext.CommitTransaction()
return
}
... ...
package domain
const TokenExpire = 24 * 3600
const TokenExpire = 24 * 3600 * 2
const RefreshTokenExpire = 24 * 3600 * 14
... ...
... ... @@ -35,6 +35,8 @@ type ProjectModuleFiles struct {
UpdateTime time.Time `json:"-"`
// 当前文件相对路径 a/b/c
Path string `json:"path"`
// 标签
Tag string `json:"tag"`
}
type ProjectModuleFilesRepository interface {
... ...
... ... @@ -17,6 +17,13 @@ select ?,?,file_type,file_name,file_key,code_block,parent_id,sort,remark,now(),n
return err
}
func (dao *ProjectModuleDao) FixParentIdByPath(srcProjectId, curVersionId int64) error {
tx := dao.transactionContext.PgTx
_, err := tx.Exec(`update project_module_files A set parent_id =coalesce((select id from project_module_files B where B.project_module_id=? and B.project_module_version_id=? and B.path=substr(A.path,0,"position"(A.path,A.file_name)-1) limit 1),0) where project_module_id=? and project_module_version_id=?`,
srcProjectId, curVersionId, srcProjectId, curVersionId)
return err
}
func NewProjectModuleDao(transactionContext *transaction.TransactionContext) (*ProjectModuleDao, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
... ...
... ... @@ -31,4 +31,6 @@ type ProjectModuleFiles struct {
UpdateTime time.Time
// 当前文件相对路径 a/b/c
Path string
// 标签
Tag string `pg:",use_zero"`
}
... ...
... ... @@ -56,6 +56,8 @@ func (repository *ProjectModuleFilesRepository) FindOne(queryOptions map[string]
query.SetWhere("parent_id = ?", "parentId")
query.SetWhere("file_key = ?", "fileKey")
query.SetWhere("path = ?", "path")
query.SetOrder("tag", "orderByTag")
if err := query.First(); err != nil {
return nil, fmt.Errorf("query row not found")
}
... ...
... ... @@ -57,6 +57,31 @@ func (controller *AuthController) Logout() {
msg = protocol.NewResponseMessageData(data, err)
}
// Refresh
// 权限刷新
func (controller *AuthController) Refresh() {
var (
msg *protocol.ResponseMessage
svr = auth.NewAuthService(nil)
request = &protocolx.RefreshRequest{}
)
defer func() {
controller.Resp(msg)
}()
if err := controller.JsonUnmarshal(request); err != nil {
msg = protocol.NewResponseMessage(2, err.Error())
return
}
header := controller.GetRequestHeader(controller.Ctx)
data, err := svr.Refresh(header, request)
if err != nil {
log.Error(err)
}
msg = protocol.NewResponseMessageData(data, err)
}
// Profile
// 获取当前用户数据
func (controller *AuthController) Profile() {
... ...
... ... @@ -7,6 +7,7 @@ import (
"github.com/astaxie/beego/context"
"github.com/tiptok/gocomm/common"
"gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/protocol"
"strings"
)
type BaseController struct {
... ... @@ -38,7 +39,7 @@ func (controller BaseController) BodyKeys(firstCaseToUpper bool) []string {
}
func (controller *BaseController) Resp(msg *protocol.ResponseMessage) {
if msg.Errno != 0 {
if msg.Errno > 0 {
msg.Errno = -1
}
controller.Data["json"] = msg
... ... @@ -65,6 +66,10 @@ func (controller *BaseController) GetRequestHeader(ctx *context.Context) *protoc
if v := ctx.Input.GetData("x-mmm-uname"); v != nil {
h.UserName = v.(string)
}
h.Token = ctx.Input.Header("Authorization")
if len(h.Token) > 0 && len(strings.Split(h.Token, " ")) > 1 {
h.Token = strings.Split(h.Token, " ")[1]
}
h.BodyKeys = controller.BodyKeys(true)
return h
}
... ...
... ... @@ -165,6 +165,31 @@ func (controller *ProjectModuleFilesController) Import() {
msg = protocol.NewResponseMessageData(data, err)
}
// ReviseTag
// 修订标签
func (controller *ProjectModuleFilesController) ReviseTag() {
var (
msg *protocol.ResponseMessage
svr = project_module_files.NewProjectModuleFilesService(nil)
request = &protocolx.ReviseTagRequest{}
)
defer func() {
controller.Resp(msg)
}()
if err := controller.JsonUnmarshal(request); err != nil {
msg = protocol.NewResponseMessage(2, err.Error())
return
}
header := controller.GetRequestHeader(controller.Ctx)
data, err := svr.ReviseTag(header, request)
if err != nil {
log.Error(err)
}
msg = protocol.NewResponseMessageData(data, err)
}
//获取排序键值
func getSortFileKeys(files map[string][]*multipart.FileHeader) (keys []string) {
for k, _ := range files {
... ...
... ... @@ -50,6 +50,7 @@ func CheckAuthorization(ctx *context.Context) {
userId, _ := strconv.Atoi(claim.Username)
ctx.Input.SetData("x-mmm-id", userId)
ctx.Input.SetData("x-mmm-uname", claim.AddData["UserName"])
//ctx.Input.SetData("x-mmm-phone", claim.AddData["Phone"])
return
}
... ...
... ... @@ -8,6 +8,7 @@ import (
func init() {
beego.Router("/v1/auth/login", &controllers.AuthController{}, "post:Login")
beego.Router("/v1/auth/logout", &controllers.AuthController{}, "post:Logout")
beego.Router("/v1/auth/refresh", &controllers.AuthController{}, "post:Refresh")
beego.Router("/v1/auth/profile", &controllers.AuthController{}, "post:Profile")
beego.Router("/v1/auth/captcha-init", &controllers.AuthController{}, "post:CaptchaInit")
beego.Router("/v1/auth/changePassword", &controllers.AuthController{}, "post:ChangePassword")
... ...
... ... @@ -13,6 +13,7 @@ func init() {
beego.Router("/v1/project_module_files/", &controllers.ProjectModuleFilesController{}, "GET:ListProjectModuleFiles")
beego.Router("/v1/project_module_files/import", &controllers.ProjectModuleFilesController{}, "post:Import")
beego.Router("/v1/project_module_files/revise", &controllers.ProjectModuleFilesController{}, "post:ReviseTag")
beego.Router("/v1/client/project_module_files/", &controllers.ProjectModuleFilesController{}, "GET:ListProjectModuleFiles")
}
... ...
package auth
import (
"errors"
"fmt"
"github.com/astaxie/beego/validation"
)
type ChangePasswordRequest struct {
Phone string `json:"phone" valid:"Required"`
OldPwd string `json:"oldPassword" valid:"Required"`
NewPwd string `json:"newPassword" valid:"Required"`
Phone string `json:"phone" valid:"Required"`
//OldPwd string `json:"oldPassword" valid:"Required"`
//NewPwd string `json:"newPassword" valid:"Required"`
Password string `json:"pwd"`
}
func (ChangePasswordRequest *ChangePasswordRequest) ValidateCommand() error {
... ... @@ -18,9 +18,9 @@ func (ChangePasswordRequest *ChangePasswordRequest) ValidateCommand() error {
if err != nil {
return err
}
if ChangePasswordRequest.OldPwd == ChangePasswordRequest.NewPwd {
return errors.New("新旧密码不能相同")
}
//if ChangePasswordRequest.OldPwd == ChangePasswordRequest.NewPwd {
// return errors.New("新旧密码不能相同")
//}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
... ...
package auth
import (
"fmt"
"github.com/astaxie/beego/validation"
)
type RefreshRequest struct {
RefreshToken string `json:"refreshToken" valid:"Required"`
}
func (RefreshRequest *RefreshRequest) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(RefreshRequest)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package auth
import (
"fmt"
"github.com/astaxie/beego/validation"
)
type RefreshResponse struct {
}
func (RefreshResponse *RefreshResponse) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(RefreshResponse)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
... ... @@ -11,7 +11,7 @@ type UpdateClientVersionRequest struct {
// 提交人
Commiter int64 `json:"commiter,omitempty"`
// 项目名称
ProjectName int64 `json:"projectName,omitempty"`
ProjectName string `json:"projectName,omitempty"`
// 版本号
Version string `json:"version,omitempty"`
// 标题
... ...
package project_module_files
import (
"fmt"
"github.com/astaxie/beego/validation"
)
type ReviseTagRequest struct {
Id int64 `json:"id" valid:"Required"`
Tag string `json:"tag"`
}
func (PatchTagRequest *ReviseTagRequest) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(PatchTagRequest)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package project_module_files
import (
"fmt"
"github.com/astaxie/beego/validation"
)
type ReviseTagResponse struct {
}
func (PatchTagResponse *ReviseTagResponse) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(PatchTagResponse)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
... ... @@ -133,5 +133,6 @@ var errmessge ErrorMap = map[int]string{
type RequestHeader struct {
UserId int64 //UserId 唯一标识
UserName string
Token string
BodyKeys []string
}
... ...