作者 yangfu

Merge branch 'dev' of http://gitlab.fjmaimaimai.com/mmm-go/oppmg into dev

... ... @@ -7,6 +7,8 @@ ENV APP_DIR $GOPATH/src/oppmg
# RUN CGO_ENABLED=0 go install -a std
RUN mkdir -p $APP_DIR
RUN /bin/cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
&& echo 'Asia/Shanghai' > /etc/timezone
# Set the entrypoint
#ENTRYPOINT (cd $APP_DIR && ./\src\oppmg)
ADD . $APP_DIR
... ...
机会导向项目
开发地址
http://mmm-oppmg-dev.fjmaimaimai.com
... ...
... ... @@ -20,6 +20,9 @@ type MyConfig struct {
UcenterBaseUrl string
UcenterSecret string
UcenterAppKey string
FileSavePath string
FileHost string
FileHostPath string
}
//MConfig
... ... @@ -48,6 +51,9 @@ func RestMyConfig() *MyConfig {
UcenterBaseUrl: beego.AppConfig.String("ucenter_base_url"),
UcenterSecret: beego.AppConfig.String("ucenter_secret"),
UcenterAppKey: beego.AppConfig.String("ucenter_app_key"),
FileSavePath: beego.AppConfig.String("file_save_path"),
FileHost: beego.AppConfig.String("file_host"),
FileHostPath: beego.AppConfig.String("file_host_path"),
}
return MConfig
}
... ...
... ... @@ -9,9 +9,11 @@ copyrequestbody = true
#开启应用内文档
EnableDocs = false
include "dev.conf"
include "prod.conf"
include "local.conf"
include "test.conf"
... ...
... ... @@ -31,6 +31,11 @@ ucenter_check_alt = "rsF0pL!6DwjBO735"
ucenter_base_url = "http://suplus-ucenter-dev.fjmaimaimai.com"
ucenter_app_key = "39aefef9e22744a3b2d2d3791824ae7b"
ucenter_secret = "cykbjnfqgctn"
# 上传文件保存路径
file_save_path = "/var/www/opp/file"
file_host = "http://mmm-opp-dev.fjmaimaimai.com"
file_host_path = "/file/opp"
# 审批流程修改 消息发布
message_publish = "audit_change"
#---自定义配置 结束----
\ No newline at end of file
... ...
[test]
config_name = "test"
#----beego的默认配置 开始---
#端口号
httpport = 8080
#开启应用内监控
EnableAdmin = false
AdminPort = 8088
#---beego的默认配置 结束---
#---自定义配置 开始----
##数据库连接
# sqlconn ="${MYSQL_CONN||root:sutianxia2015@tcp(115.29.205.99:3306)/opportunity?charset=utf8&loc=Asia%2FShanghai}"
mysql_user = "${MYSQL_USER||root}"
mysql_password = "${MYSQL_PASSWORD||sutianxia2015}"
mysql_host = "${MYSQL_HOST||115.29.205.99}"
mysql_port = "${MYSQL_PORT||3306}"
mysql_db_name = "${MYSQL_DB_NAME||opportunity}"
##redis相关配置
redis_add = "${REDIS_HOST||127.0.0.1}"
redis_add_port = "${REDIS_PORT||6379}"
redis_auth = ""
##log相关配置
##out_put:"console","file"
log_output = "file"
log_filename = "${aliyun_logs_access||./log/ability.log}"
log_level = "${LOG_LEVEL||debug}"
##统一用户中心相关配置
ucenter_check_alt = "rsF0pL!6DwjBO735"
ucenter_base_url = "http://suplus-ucenter-test.fjmaimaimai.com"
ucenter_app_key = "39aefef9e22744a3b2d2d3791824ae7b"
ucenter_secret = "cykbjnfqgctn"
# 上传文件保存路径
file_save_path = "/var/www/opp/file"
file_host = "http://mmm-opp-dev.fjmaimaimai.com"
file_host_path = "/file/opp"
# 审批流程修改 消息发布
message_publish = "audit_change"
#---自定义配置 结束----
\ No newline at end of file
... ...
... ... @@ -2,10 +2,15 @@ package controllers
import (
"encoding/json"
"fmt"
"oppmg/common/log"
"oppmg/protocol"
serveauth "oppmg/services/auth"
"oppmg/storage/redisdata"
"strconv"
"time"
"github.com/GeeTeam/gt3-golang-sdk/geetest"
)
type AuthController struct {
... ... @@ -67,7 +72,10 @@ func (c *AuthController) Login() {
if err != nil {
log.Error("token 信息记录redis失败")
}
msg = protocol.NewReturnResponse(logintoken, nil)
data := map[string]interface{}{
"access": logintoken,
}
msg = protocol.NewReturnResponse(data, nil)
return
}
... ... @@ -113,6 +121,72 @@ func (c *AuthController) Me() {
userid := c.GetUserId()
companyid := c.GetCompanyId()
userinfo, err := serveauth.UserBaseInfo(userid, companyid)
msg = protocol.NewReturnResponse(userinfo, err)
if err != nil {
log.Error("获取用户数据失败")
}
menus, err := serveauth.GetUserHasMenu(userid, companyid)
if err != nil {
log.Error("获取用户菜单")
}
companys, err := serveauth.UserHasCompanys(userid)
if err != nil {
log.Error("获取用户的公司")
}
data := map[string]interface{}{
"user": userinfo,
"menus": menus,
"companys": companys,
}
msg = protocol.NewReturnResponse(data, nil)
return
}
const (
captchaID = "48a6ebac4ebc6642d68c217fca33eb4d"
privateKey = "4f1c085290bec5afdc54df73535fc361"
)
func (c *AuthController) RegisterGeetest() {
geetest := geetest.NewGeetestLib(captchaID, privateKey, 2*time.Second)
status, responseBt := geetest.PreProcess("", "")
c.SetSession("geetest_status", status)
c.Ctx.Output.Body(responseBt)
return
}
func (c *AuthController) ValidateGeetest() {
type Parameter struct {
GeetestChallenge string `form:"geetest_challenge"`
GeetestValidate string `form:"geetest_validate"`
GeetestSeccode string `form:"geetest_seccode"`
}
var (
param Parameter
geetestRes bool
status int
)
err := c.ParseForm(&param)
if err != nil {
log.Error("解析表单数据失败;%s", err)
}
val := c.GetSession("geetest_status")
status, _ = strconv.Atoi(fmt.Sprint(val))
geetest := geetest.NewGeetestLib(captchaID, privateKey, 2*time.Second)
if status == 1 {
geetestRes = geetest.SuccessValidate(param.GeetestChallenge, param.GeetestValidate, param.GeetestSeccode, "", "")
} else {
geetestRes = geetest.FailbackValidate(param.GeetestChallenge, param.GeetestValidate, param.GeetestSeccode)
}
res := make(map[string]interface{})
if geetestRes {
res["code"] = 0
res["msg"] = "Success"
} else {
res["code"] = -100
res["msg"] = "Failed"
}
responseBt, _ := json.Marshal(res)
c.Ctx.Output.Body(responseBt)
return
}
... ...
... ... @@ -20,14 +20,14 @@ type BaseController struct {
//Prepare 实现beego.ControllerInterface 的接口
func (this *BaseController) Prepare() {
this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Headers", "*")
if this.Ctx.Input.Method() == "OPTIONS" {
this.Ctx.ResponseWriter.WriteHeader(204)
this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
//this.Ctx.WriteString("")
return
}
// this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
// this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Headers", "*")
// if this.Ctx.Input.Method() == "OPTIONS" {
// this.Ctx.ResponseWriter.WriteHeader(204)
// this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
// //this.Ctx.WriteString("")
// return
// }
p := this.Ctx.Input.GetData("RouterPattern")
fmt.Println("====>r:", p)
}
... ...
... ... @@ -324,7 +324,7 @@ func (c *CompanyController) UserAllowForbid() {
c.ResposeJson(msg)
}()
type Parameter struct {
UserCompanyIds []int64 `json:"ids"`
UserCompanyIds []int64 `json:"user_company_ids"`
Status int `json:"status"` // [1:执行禁用操作][2:执行启用操作]
}
var param Parameter
... ... @@ -385,17 +385,37 @@ func (c *CompanyController) InitCompany() {
msg = protocol.BadRequestParam("1")
return
}
if param.CompanyId <= 0 {
log.Error("公司id为0")
msg = protocol.BadRequestParam("1")
return
}
var (
err error
)
if ok := param.IsEnable(); ok {
if len(param.CompanyName) == 0 {
log.Error("公司名称空")
msg = protocol.BadRequestParam("1")
return
}
if len(param.AdminAccount) == 0 {
log.Error("人员账号空")
msg = protocol.BadRequestParam("1")
return
}
if len(param.AdminName) == 0 {
log.Error("人员名称空")
msg = protocol.BadRequestParam("1")
return
}
err = servecompany.InitCompanyInfo(param)
} else if ok := param.IsForbid(); ok {
err = servecompany.ForbidCompany(param.CompanyId)
} else {
err = protocol.NewErrWithMessage("1")
}
msg = protocol.NewReturnResponse(nil, err)
return
}
... ... @@ -420,6 +440,42 @@ func (c *CompanyController) GetCompanyForUCenter() {
return
}
//获取用户详情
//@router /user/info
func (c *CompanyController) UserDetail() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
UserCompanyId int64 `json:"user_company_id"`
}
var param Parameter
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
log.Error("json 解析失败 err:%s", err)
msg = protocol.BadRequestParam("1")
return
}
userdata, _ := servecompany.GetUserData(param.UserCompanyId)
departs := servecompany.GetUserDepartment(param.UserCompanyId)
positions := servecompany.GetUserPosition(param.UserCompanyId)
roles := servecompany.GetUserRole(param.UserCompanyId)
type ResponseUserDetail struct {
protocol.UserInfoBase
Departs []protocol.DepartmentBase `json:"departs"`
Positions []protocol.PositionBase `json:"positions"`
Roles []protocol.RoleBase `json:"roles"`
}
data := ResponseUserDetail{
UserInfoBase: userdata,
Departs: departs,
Positions: positions,
Roles: roles,
}
msg = protocol.NewReturnResponse(data, nil)
return
}
//DepartmentUser 获取部门下成员
//@router /department/user [post]
func (c *CompanyController) DepartmentUser() {
... ... @@ -469,15 +525,6 @@ func (c *CompanyController) CurrentCompanyInfo() {
defer func() {
c.ResposeJson(msg)
}()
// type Parameter struct {
// Logo string `json:"string"`
// }
// var param Parameter
// if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
// log.Error("json 解析失败 err:%s", err)
// msg = protocol.BadRequestParam("1")
// return
// }
companyid := c.GetCompanyId()
companybase, err := servecompany.CompanyBaseInfo(companyid)
msg = protocol.NewReturnResponse(companybase, err)
... ...
package controllers
import (
"fmt"
"io"
"mime/multipart"
"oppmg/common/config"
"oppmg/common/log"
"oppmg/protocol"
"oppmg/utils"
"os"
"path"
"path/filepath"
"time"
)
//UploadController 文件上传
type UploadController struct {
BaseController
}
type ResponseUploadImage struct {
Urls []string `json:"url"`
}
//UploadImage 图片上传
//@router /image
func (c *UploadController) UploadImage() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
filehead, err := c.GetFiles("file")
if err != nil {
log.Error("获取上传文件失败:%s", err)
}
var rsp ResponseUploadImage
for i := range filehead {
hostpath, err := saveFile(filehead[i], "image")
if err != nil {
msg = protocol.BadRequestParam("1")
return
}
rsp.Urls = append(rsp.Urls, hostpath)
}
msg = protocol.NewReturnResponse(rsp, nil)
return
}
func saveFile(fileData *multipart.FileHeader, fileType string) (hostpath string, err error) {
savepath := filepath.Join(config.MConfig.FileSavePath, fileType)
os.MkdirAll(savepath, 0777)
file, err := fileData.Open()
defer file.Close()
if err != nil {
log.Error("文件获取失败%s", err)
return "", err
}
subfix := path.Ext(fileData.Filename)
mfileName := fmt.Sprint(utils.GenerateIDBySonyflake())
mfileName = fmt.Sprintf("%d_%s%s", time.Now().Unix(), mfileName, subfix)
dst, err := os.Create(filepath.Join(savepath, mfileName))
defer dst.Close()
if err != nil {
log.Error("目录访问失败:%s", err)
return "", err
}
if _, err := io.Copy(dst, file); err != nil {
log.Error("文件保存失败:%s", err)
return "", err
}
hostpath = config.MConfig.FileHost + filepath.Join(config.MConfig.FileHostPath, fileType, mfileName)
return hostpath, nil
}
... ...
#!/bin/bash
export PATH=/root/local/bin:$PATH
kubectl -n mmm-suplus-test get pods | grep -q opp
kubectl -n mmm-suplus-test get pods | grep -q mmm-oppmg
if [ "$?" == "1" ];then
kubectl create -f /tmp/test/opp/opp.yaml --record
kubectl -n mmm-suplus-test get svc | grep -q opp
kubectl create -f /tmp/test/mmm-go-oppmg/oppmg.yaml --record
kubectl -n mmm-suplus-test get svc | grep -q mmm-oppmg
if [ "$?" == "0" ];then
echo "opp service install success!"
echo "mmm-oppmg service install success!"
else
echo "opp service install fail!"
echo "mmm-oppmg service install fail!"
fi
kubectl -n mmm-suplus-test get pods | grep -q opp
kubectl -n mmm-suplus-test get pods | grep -q mmm-oppmg
if [ "$?" == "0" ];then
echo "opp deployment install success!"
echo "mmm-oppmg deployment install success!"
else
echo "opp deployment install fail!"
echo "mmm-oppmg deployment install fail!"
fi
else
kubectl delete -f /tmp/test/opp/opp.yaml
kubectl -n mmm-suplus-test get svc | grep -q opp
kubectl delete -f /tmp/test/mmm-go-oppmg/oppmg.yaml
kubectl -n mmm-suplus-test get svc | grep -q mmm-oppmg
while [ "$?" == "0" ]
do
kubectl -n mmm-suplus-test get svc | grep -q opp
kubectl -n mmm-suplus-test get svc | grep -q mmm-oppmg
done
kubectl -n mmm-suplus-test get pods | grep -q opp
kubectl -n mmm-suplus-test get pods | grep -q mmm-oppmg
while [ "$?" == "0" ]
do
kubectl -n mmm-suplus-test get pods | grep -q opp
kubectl -n mmm-suplus-test get pods | grep -q mmm-oppmg
done
kubectl create -f /tmp/test/opp/opp.yaml --record
kubectl -n mmm-suplus-test get svc | grep -q opp
kubectl create -f /tmp/test/mmm-go-oppmg/oppmg.yaml --record
kubectl -n mmm-suplus-test get svc | grep -q mmm-oppmg
if [ "$?" == "0" ];then
echo "opp service update success!"
echo "mmm-oppmg service update success!"
else
echo "opp service update fail!"
echo "mmm-oppmg service update fail!"
fi
kubectl -n mmm-suplus-test get pods | grep -q opp
kubectl -n mmm-suplus-test get pods | grep -q mmm-oppmg
if [ "$?" == "0" ];then
echo "opp deployment update success!"
echo "mmm-oppmg deployment update success!"
else
echo "opp deployment update fail!"
echo "mmm-oppmg deployment update fail!"
fi
fi
\ No newline at end of file
... ...
apiVersion: v1
kind: Service
metadata:
name: opp
name: mmm-oppmg
namespace: mmm-suplus-test
labels:
k8s-app: opp
k8s-app: mmm-oppmg
spec:
ports:
- name: "http"
port: 80
targetPort: 8082
- name: "http"
port: 80
targetPort: 8080
selector:
k8s-app: opp
k8s-app: mmm-oppmg
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: opp
name: mmm-oppmg
namespace: mmm-suplus-test
labels:
k8s-app: opp
k8s-app: mmm-oppmg
spec:
replicas: 1
template:
metadata:
labels:
k8s-app: opp
k8s-app: mmm-oppmg
spec:
affinity:
nodeAffinity:
... ... @@ -43,54 +43,60 @@ spec:
- cn-hangzhou.i-bp1euf5u1ph9kbhtndhb
- cn-hangzhou.i-bp1hyp5oips9cdwxxgxy
containers:
- name: opp
image: 192.168.0.243:5000/mmm/opp:test
imagePullPolicy: Always
ports:
- containerPort: 8082
volumeMounts:
- mountPath: /opt/logs
name: accesslogs
env:
- name: ENTERPRISE_SERVICE_HOST
valueFrom:
configMapKeyRef:
name: suplus-config
key: service.enterprise
- name: MYSQL_HOST
valueFrom:
configMapKeyRef:
name: suplus-config
key: mysql.host
- name: MYSQL_PORT
valueFrom:
configMapKeyRef:
name: suplus-config
key: mysql.port
- name: MYSQL_USER
valueFrom:
configMapKeyRef:
name: suplus-config
key: mysql.user
- name: MYSQL_PASSWORD
valueFrom:
configMapKeyRef:
name: suplus-config
key: mysql.password
- name: MYSQL_DB_NAME
value: "opp_test"
- name: LOG_LEVEL
value: "debug"
- name: ERROR_BASE_CODE
value: "9"
- name: ERROR_BASE_CODE_MULTIPLE
value: "1000"
- name: RUN_MODE
value: "prod"
- name: aliyun_logs_suplus
value: "stdout"
- name: aliyun_logs_access
value: "/opt/logs/app.log"
- name: mmm-oppmg
image: 192.168.0.243:5000/mmm/mmm-oppmg:dev
imagePullPolicy: Always
volumeMounts:
- mountPath: /opt/logs
name: accesslogs
- mountPath: /var/www/oppmg/file
name: mmmjihuitest2-pvc1
ports:
- containerPort: 8080
env:
- name: MYSQL_HOST
valueFrom:
configMapKeyRef:
name: suplus-config
key: mysql.host
- name: MYSQL_PORT
valueFrom:
configMapKeyRef:
name: suplus-config
key: mysql.port
- name: REDIS_HOST
valueFrom:
configMapKeyRef:
name: suplus-config
key: redis.ip
- name: REDIS_PORT
valueFrom:
configMapKeyRef:
name: suplus-config
key: redis.port
- name: MYSQL_USER
valueFrom:
configMapKeyRef:
name: suplus-config
key: mysql.user
- name: MYSQL_PASSWORD
valueFrom:
configMapKeyRef:
name: suplus-config
key: mysql.password
- name: MYSQL_DB_NAME
value: "opportunity_test"
- name: RUN_MODE
value: "test"
- name: LOG_LEVEL
value: "debug"
- name: aliyun_logs_suplusfile
value: "stdout"
- name: aliyun_logs_access
value: " /opt/logs/app.log"
volumes:
- name: accesslogs
emptyDir: {}
\ No newline at end of file
- name: accesslogs
emptyDir: {}
- name: mmmjihuitest2-pvc1
persistentVolumeClaim:
claimName: mmmjihuitest2-pvc
... ...
... ... @@ -4,6 +4,7 @@ go 1.13
require (
github.com/360EntSecGroup-Skylar/excelize/v2 v2.0.2
github.com/GeeTeam/gt3-golang-sdk v0.0.0-20190704102600-e89c6d964c8f
github.com/astaxie/beego v1.11.1
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/go-redis/redis v6.15.6+incompatible
... ...
github.com/360EntSecGroup-Skylar/excelize/v2 v2.0.2 h1:StMrA6UQ5Cm6206DxXGuV/NMqSIOIDoMXMYt8JPe1lE=
github.com/360EntSecGroup-Skylar/excelize/v2 v2.0.2/go.mod h1:EfRHD2k+Kd7ijnqlwOrH1IifwgWB9yYJ0pdXtBZmlpU=
github.com/GeeTeam/gt3-golang-sdk v0.0.0-20190704102600-e89c6d964c8f h1:FpIAcTBZpoM5uD2+zKbTyT+6Oz0efWw4ZWnr8FtdQ+g=
github.com/GeeTeam/gt3-golang-sdk v0.0.0-20190704102600-e89c6d964c8f/go.mod h1:vqCh/LExdPmL5SULXE/9DHbuE4t3iLkzRYoNGxEvg/o=
github.com/Knetic/govaluate v3.0.0+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0=
github.com/astaxie/beego v1.11.1 h1:6DESefxW5oMcRLFRKi53/6exzup/IR6N4EzzS1n6CnQ=
github.com/astaxie/beego v1.11.1/go.mod h1:i69hVzgauOPSw5qeyF4GVZhn7Od0yG5bbCGzmhbWxgQ=
... ...
... ... @@ -12,10 +12,14 @@ import (
_ "github.com/go-sql-driver/mysql"
)
func main() {
func init() {
beego.BConfig.WebConfig.Session.SessionOn = true
common.ResetCommonConfig()
log.Debug("加载配置%s", config.MConfig.ConfigName)
orm.RegisterDataBase("default", "mysql", config.MConfig.SqlConn)
}
func main() {
// orm.Debug = true
// if beego.BConfig.RunMode == "dev" {
// beego.BConfig.WebConfig.DirectoryIndex = true
... ...
... ... @@ -6,6 +6,7 @@ import (
"oppmg/protocol"
serveauth "oppmg/services/auth"
"oppmg/storage/redisdata"
"strings"
"github.com/astaxie/beego"
... ... @@ -38,11 +39,17 @@ var AuthToken = func(ctx *context.Context) {
mtoken *serveauth.MyToken
)
accesstoken := ctx.Input.Header(protocol.HeaderAccessToken)
// refreshToken := ctx.Input.Header(protocol.HeaderRefreshToken)
mtoken, err = serveauth.ValidJWTToken(accesstoken)
//解出需要的jwt串 例:头【Authorization】:Bearer 123token456
s := strings.Split(accesstoken, "\u0020")
// strings.TrimSpace()
if len(s) > 0 {
accesstoken = s[len(s)-1]
}
fmt.Println("===>", accesstoken)
if accesstoken == "123456" && beego.BConfig.RunMode != "prod" {
return
}
mtoken, err = serveauth.ValidJWTToken(accesstoken)
if err == nil {
storetoken, err = redisdata.GetLoginToken(mtoken.UID)
if err != nil {
... ... @@ -84,7 +91,7 @@ var AllowOption = func(ctx *context.Context) {
AllowHeaders: []string{"Origin", "Accept", "Content-Type", "Authorization",
"x-mmm-cid", "x-mmm-uid", "x-mmm-accesstoken", "x-mmm-refreshtoken", "x-requested-with"}, //允许的头部信息
ExposeHeaders: []string{"Content-Length"}, //允许暴露的头信息
AllowCredentials: false, //不允许共享AuthTuffic证书
AllowCredentials: true, //不允许共享AuthTuffic证书
AllowAllOrigins: true, //允许的请求来源
})
f(ctx)
... ...
... ... @@ -13,6 +13,7 @@ type UserCompany struct {
Id int64 `orm:"column(id);auto" description:"唯一标识"`
CompanyId int64 `orm:"column(company_id)" description:"表company.id 公司编号"`
UserId int64 `orm:"column(user_id)" description:"表user.id 用户编号"`
NickName string `orm:"column(nick_name)"`
ChanceTotal int `orm:"column(chance_total)" description:"发表机会数"`
CommentTotal int `orm:"column(comment_total)" description:"发表评论总数"`
CreateAt time.Time `orm:"column(create_at);type(timestamp)" description:"创建时间"`
... ... @@ -53,6 +54,15 @@ func init() {
orm.RegisterModel(new(UserCompany))
}
func GetUserCompanyById(id int64) (v *UserCompany, err error) {
o := orm.NewOrm()
v = &UserCompany{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// AddUserCompany insert a new UserCompany into database and returns
// last inserted Id on success.
func AddUserCompany(m *UserCompany, o orm.Ormer) (id int64, err error) {
... ... @@ -66,16 +76,19 @@ func AddUserCompany(m *UserCompany, o orm.Ormer) (id int64, err error) {
// UpdateUserCompany updates UserCompany by Id and returns error if
// the record to be updated doesn't exist
func UpdateUserCompanyById(m *UserCompany) (err error) {
o := orm.NewOrm()
v := UserCompany{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
func UpdateUserCompanyById(m *UserCompany, col []string, om ...orm.Ormer) (err error) {
var o orm.Ormer
if len(om) > 0 {
o = om[0]
} else {
o = orm.NewOrm()
}
var num int64
m.UpdateAt = time.Now()
if num, err = o.Update(m, col...); err == nil {
fmt.Println("Number of records updated in database:", num)
}
return
}
... ...
... ... @@ -8,8 +8,8 @@ import (
)
type UserDepartment struct {
Id int64 `orm:"column(id);auto" description:"主键"`
UserId int64 `orm:"column(user_id)" description:"用户id"`
Id int64 `orm:"column(id);auto" description:"主键"`
//UserId int64 `orm:"column(user_id)" description:"用户id"`
CompanyId int64 `orm:"column(company_id)" description:"公司id"`
DepartmentId int64 `orm:"column(department_id)" description:"部门id"`
CreateTime time.Time `orm:"column(create_time);type(timestamp);null" description:"创建时间"`
... ...
... ... @@ -8,8 +8,8 @@ import (
)
type UserPosition struct {
Id int64 `orm:"column(id)" description:"唯一键值"`
UserId int64 `orm:"column(user_id)" description:"表user.id 用户编号"`
Id int64 `orm:"column(id)" description:"唯一键值"`
//UserId int64 `orm:"column(user_id)" description:"表user.id 用户编号"`
PositionId int64 `orm:"column(position_id)" description:"表position.id 职位编号"`
CreateAt time.Time `orm:"column(create_at);type(timestamp);null" description:"创建时间"`
CompanyId int64 `orm:"column(company_id)" description:"表company.id 公司编号"`
... ...
... ... @@ -9,7 +9,6 @@ import (
type UserRole struct {
Id int `orm:"column(id)"`
RoleId int64 `orm:"column(role_id)"`
UserId int64 `orm:"column(user_id)"`
EnableStatus int8 `orm:"column(enable_status)" description:"是否有效"`
CompanyId int64 `orm:"column(company_id)" description:"表company.id 公司编号"`
UserCompanyId int64 `orm:"column(user_company_id)"`
... ...
... ... @@ -90,7 +90,7 @@ type Template struct {
Code string `json:"code" valid:"Required; MaxSize(6)"`
ChanceTypeId int `json:"chanceTypeId" valid:"Required;"` //机会类型编号
Name string `json:"name" valid:"Required;"`
Doc string `json:"doc" valid:"Required;"`
Doc string `json:"doc"`
Icon string `json:"icon" valid:"Required;"`
InputList []*InputElement `json:"inputList" valid:"Required;"`
}
... ...
... ... @@ -55,7 +55,7 @@ type ResponseMeInfo struct {
Companyid int64 `json:"company_id"`
Companyname string `json:"company_name"`
Logo string `json:"logo"`
Companys []MeCompany `json:"companys"`
Companys []MeCompany `json:"-"`
// Menu
}
... ...
... ... @@ -43,7 +43,7 @@ type PositionBase struct {
//DepartUserBase 下拉选择列表-部门下的人员
type DepartUserBase struct {
UserCompanyId int64 `json:"id" orm:"column(user_company_id)"`
Name string `json:"name" orm:"-"`
NickName string `json:"name" orm:"column(nick_name)"`
}
//部门和人员混合
... ... @@ -51,3 +51,9 @@ type DepartAndUser struct {
Departments []DepartmentBase `json:"departments"`
Members []DepartmentMember `json:"members"`
}
type UserInfoBase struct {
UserCompanyId int64 `json:"user_company_id"`
Name string `json:"name"`
Phone string `json:"phone"`
}
... ...
... ... @@ -89,7 +89,7 @@ type RequestUserAdd struct {
//RequestUserEdit 编辑用户
type RequestUserEdit struct {
ID int64 `json:"id"`
UserCompanyID int64 `json:"user_company_id"`
RequestUserAdd
}
... ... @@ -123,9 +123,9 @@ type ResponseCompanyBase struct {
//CenterCompanyInfo 统一用户中心调用的公司数据
type CenterCompanyInfo struct {
CompanyId int64 `json:"company_id"` //总后台的公司id
CompanyName string `json:"company_name"` //
AdminId int64 `json:"admin_id"` //统一用户中心的用户id
CompanyId int64 `json:"company_id"` //总后台的公司id
CompanyName string `json:"company_name"` //
// AdminId int64 `json:"admin_id"` //统一用户中心的用户id
AdminAccount string `json:"admin_account"`
AdminName string `json:"admin_name"`
Status int8 `json:"status"` //公司的状态 【1:启用】【2:禁用】
... ...
package protocol
var NullData = struct{}{}
//CustomErrParse 解析自定义错误结构体
type CustomErrParse interface {
ParseToMessage() *ResponseMessage
... ... @@ -37,7 +39,7 @@ func NewMessage(code string) *ResponseMessage {
rsp := &ResponseMessage{
Errno: transformCode(ecode.Errno),
Errmsg: ecode.Errmsg,
Data: nil,
Data: NullData,
}
return rsp
}
... ... @@ -89,8 +91,12 @@ func SearchErr(code string) ErrorCode {
//NewReturnResponse 控制层响应返回
func NewReturnResponse(data interface{}, eRR error) (msg *ResponseMessage) {
// var msg *ResponseMessage
if data == nil {
data = NullData
}
if eRR == nil {
msg = NewMessage("0")
msg.Data = data
return msg
}
... ... @@ -108,6 +114,9 @@ func BadRequestParam(code string) *ResponseMessage {
//NewPageDataResponse 控制层分页数据响应返回
func NewPageDataResponse(data interface{}, eRR error) (msg *ResponseMessage) {
if data == nil {
data = NullData
}
if eRR != nil {
if x, ok := eRR.(CustomErrParse); ok {
return x.ParseToMessage()
... ...
... ... @@ -2,7 +2,7 @@ package protocol
var errmessge ErrorMap = map[string]string{
//操作
"0": "成功",
"0": "ok",
"1": "网络连接无响应",
//角色相关
"10001": "请先删除该分组下的其他角色",
... ...
... ... @@ -46,10 +46,11 @@ func init() {
beego.NSRouter("/edit", &controllers.CompanyController{}, "post:UserEdit"),
beego.NSRouter("/delete", &controllers.CompanyController{}, "post:UserDelete"),
beego.NSRouter("/allow_forbid", &controllers.CompanyController{}, "post:UserAllowForbid"),
beego.NSRouter("/info", &controllers.CompanyController{}, "post:UserDetail"),
),
beego.NSNamespace("/auth",
beego.NSRouter("/change_company", &controllers.AuthController{}, "post:ChangeCompany"),
beego.NSRouter("/refresh_token", &controllers.AuthController{}, "post:RefreshToken"),
//beego.NSRouter("/refresh_token", &controllers.AuthController{}, "post:RefreshToken"),
beego.NSRouter("/me", &controllers.AuthController{}, "post:Me"),
),
beego.NSNamespace("/bulletin",
... ... @@ -80,12 +81,17 @@ func init() {
beego.NSRouter("/deleteCategory", &controllers.TemplateController{}, "post:TemplateDeleteCategory"),
beego.NSRouter("/sortCategory", &controllers.TemplateController{}, "post:CategoryEditSort"),
),
beego.NSNamespace("/upload",
beego.NSRouter("/image", &controllers.UploadController{}, "post:UploadImage"),
),
)
nsAuth := beego.NewNamespace("/auth",
beego.NSBefore(middleware.AllowOption),
beego.NSBefore(middleware.LogRequestData),
beego.NSRouter("/login", &controllers.AuthController{}, "post:Login"),
beego.NSRouter("/startCaptcha", &controllers.AuthController{}, "post:RegisterGeetest"),
beego.NSRouter("/verifyCaptcha", &controllers.AuthController{}, "post:ValidateGeetest"),
)
nsUcenter := beego.NewNamespace("/ucenter",
beego.NSBefore(middleware.LogRequestData),
... ... @@ -96,7 +102,6 @@ func init() {
beego.AddNamespace(nsV1)
beego.AddNamespace(nsAuth)
beego.AddNamespace(nsUcenter)
nsTest := beego.NewNamespace("/test",
beego.NSCond(func(ctx *context.Context) bool {
if beego.BConfig.RunMode != "prod" {
... ... @@ -108,4 +113,5 @@ func init() {
)
beego.AddNamespace(nsTest)
beego.SetStaticPath("/log", beego.AppConfig.String("log_filename"))
beego.SetStaticPath("/file/opp", beego.AppConfig.String("file_save_path"))
}
... ...
... ... @@ -3,7 +3,6 @@ package auth
import (
"crypto/sha1"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"oppmg/common/log"
... ... @@ -201,51 +200,31 @@ func LoginAuthByUCenter(account, password string) (protocol.LoginAuthToken, erro
log.Debug("no company")
return logintoken, protocol.NewErrWithMessage("10022")
}
companyid = companys[0].Id
// var uclientReturn *ucenter.ResponseLogin
// uclientReturn, err = requestUCenterLogin(account, password)
// if err != nil {
// return logintoken, protocol.NewErrWithMessage("10021")
// }
// //更新用户数据
// _ = uclientReturn
// userdata.Accid = uclientReturn.Data.Accid
// userdata.Icon = uclientReturn.Data.Avatar
// userdata.ImToken = uclientReturn.Data.Imtoken
// userdata.NickName = uclientReturn.Data.NickName
// userdata.CsAccount = uclientReturn.Data.CustomerAccount
// userdata.LastLoginTime = time.Now()
// err = models.UpdateUserById(userdata, []string{"Accid", "Icon", "ImToken", "NickName", "CsAccount", "LastLoginTime"})
// if err != nil {
// log.Error("更新用户数据失败:%s", err)
// }
logintoken, _ = GenerateAuthToken(userdata.Id, companyid)
return logintoken, err
}
func requestUCenterLogin(account, password string) (*ucenter.ResponseLogin, error) {
var uclientReturn *ucenter.ResponseLogin
param := ucenter.RequesLogin{
Type: 1,
Phone: account,
Password: password,
//获取上一次登录的公司
uAuth, err := models.GetUserAuthByUser(userdata.Id)
if err == nil {
companyid = uAuth.CurrentCompanyId
} else {
companyid = companys[0].Id
}
uclient := ucenter.NewUCenterClient()
btBody, err := uclient.Call(param)
var uclientReturn *ucenter.ResponseLogin
uclientReturn, err = ucenter.RequestUCenterLogin(account, password)
if err != nil {
log.Error("统一用户中心请求失败 err:%s", err)
return nil, protocol.NewErrWithMessage("1")
return logintoken, protocol.NewErrWithMessage("10021")
}
err = json.Unmarshal(btBody, &uclientReturn)
//更新用户数据
userdata.Accid = uclientReturn.Data.Accid
userdata.Icon = uclientReturn.Data.Avatar
userdata.ImToken = uclientReturn.Data.Imtoken
userdata.NickName = uclientReturn.Data.NickName
userdata.CsAccount = uclientReturn.Data.CustomerAccount
userdata.LastLoginTime = time.Now()
err = models.UpdateUserById(userdata, []string{"Accid", "Icon", "ImToken", "NickName", "CsAccount", "LastLoginTime"})
if err != nil {
log.Error("解析统一用户中心响应失败 err:%s", err)
return nil, protocol.NewErrWithMessage("1")
}
if !(uclientReturn.Code == ucenter.ResponseCode0 &&
uclientReturn.Msg == ucenter.ResponseMsgOk) {
return nil, protocol.NewErrWithMessage("10021")
log.Error("更新用户数据失败:%s", err)
}
return uclientReturn, nil
logintoken, _ = GenerateAuthToken(userdata.Id, companyid)
return logintoken, err
}
type companybase struct {
... ... @@ -286,9 +265,9 @@ func getUserCompanyReal(userid int64) ([]companybase, error) {
func UserBaseInfo(userid, companyid int64) (protocol.ResponseMeInfo, error) {
var (
err error
userinfo *models.User
companylist []companybase
err error
userinfo *models.User
meInfo protocol.ResponseMeInfo
currentCompany *models.Company
)
... ... @@ -302,11 +281,7 @@ func UserBaseInfo(userid, companyid int64) (protocol.ResponseMeInfo, error) {
log.Error("GetCompanyById(%d) err:%s", companyid, err)
return meInfo, protocol.NewErrWithMessage("1", err)
}
companylist, err = getUserCompanyReal(userid)
if err != nil {
log.Error("getUserCompanyReal(%d) err:%s", userid, err)
return meInfo, protocol.NewErrWithMessage("1", err)
}
meInfo = protocol.ResponseMeInfo{
NickName: userinfo.NickName,
Icon: userinfo.Icon,
... ... @@ -314,12 +289,42 @@ func UserBaseInfo(userid, companyid int64) (protocol.ResponseMeInfo, error) {
Companyname: currentCompany.Name,
Logo: currentCompany.Logo,
}
return meInfo, nil
}
func UserHasCompanys(userid int64) ([]protocol.MeCompany, error) {
var (
companylist []companybase
err error
mecompanys []protocol.MeCompany
)
companylist, err = getUserCompanyReal(userid)
if err != nil {
log.Error("getUserCompanyReal(%d) err:%s", userid, err)
return nil, protocol.NewErrWithMessage("1", err)
}
for _, v := range companylist {
t := protocol.MeCompany{
Id: v.Id,
Name: v.Name,
}
meInfo.Companys = append(meInfo.Companys, t)
mecompanys = append(mecompanys, t)
}
return meInfo, nil
return mecompanys, nil
}
func GetUserHasMenu(userid, companyid int64) ([]protocol.PermissionItem, error) {
const datasql string = `SELECT id,name,icon,parent_id,senior_status,sort,code
FROM menu WHERE enabled=1 ORDER BY sort `
var (
list []protocol.PermissionItem
err error
)
err = utils.ExecuteQueryAll(&list, datasql)
if err != nil {
log.Error("EXECUTE SQL err:%s", err)
return nil, protocol.NewErrWithMessage("1")
}
return list, nil
}
... ...
package company
import (
"fmt"
"oppmg/common/log"
"oppmg/models"
"oppmg/protocol"
"oppmg/services/ucenter"
"time"
"github.com/astaxie/beego/orm"
)
// type CenterCompanyInfo struct {
// CompanyId int64
// CompanyName string
// AdminId int64
// AdminAccount string
// AdminName string
// }
// func GetCenterCompanyInfo(companyid int64) (CenterCompanyInfo, error) {
// //TODO 调用统一用户中心的数据
// data := CenterCompanyInfo{
// CompanyId: 9999 + companyid,
// CompanyName: "调试用公司数据",
// AdminId: 9999 + companyid,
// AdminAccount: "调试用自己修改",
// AdminName: "调试用自己修改",
// }
// return data, nil
// }
//InitCompanyInfo 初始化公司
//@uCompanyid 从统一用户中心获取的公司id companyid,
func InitCompanyInfo(centerCompany protocol.CenterCompanyInfo) error {
// var (
// centerCompany CenterCompanyInfo
... ... @@ -43,8 +21,7 @@ func InitCompanyInfo(centerCompany protocol.CenterCompanyInfo) error {
// return protocol.NewErrWithMessage("10051")
// }
var (
newDeparment *models.Department
//newUserDepart = &models.UserDepartment{}
newDeparment *models.Department
newRoleGroup *models.Role
newRole *models.Role
newUser *models.User
... ... @@ -160,7 +137,7 @@ func initAdminUser(centerCompany protocol.CenterCompanyInfo, o orm.Ormer) (*mode
newUser = &models.User{}
)
err = o.QueryTable(&models.User{}).
Filter("user_center_id", centerCompany.AdminId).
Filter("phone", centerCompany.AdminAccount).
Filter("delete_at", 0).
One(newUser)
if err == nil {
... ... @@ -178,16 +155,21 @@ func initAdminUser(centerCompany protocol.CenterCompanyInfo, o orm.Ormer) (*mode
return nil, err
}
} else if err == orm.ErrNoRows {
ucenterUser, err := ucenter.RequestUCenterAddUser(centerCompany.AdminAccount, centerCompany.AdminName, "")
if err != nil {
log.Error("获取统一用户中心数据失败 :%s", err)
}
//添加用户
newUser = &models.User{
Phone: centerCompany.AdminAccount,
UserCenterId: centerCompany.AdminId,
NickName: centerCompany.AdminName,
Icon: ucenterUser.Data.Avatar,
Accid: ucenterUser.Data.Accid,
UserCenterId: ucenterUser.Data.Id,
CsAccount: ucenterUser.Data.CustomerAccount,
}
id, err := models.AddUser(newUser, o)
fmt.Println("-=====>user_id=", id)
_, err = models.AddUser(newUser, o)
if err != nil {
log.Error("添加用户数据失败:%s", err)
return nil, err
}
... ... @@ -290,9 +272,9 @@ func initUserDedaprtmet(newDepartment *models.Department, newUserCompany *models
//添加部门
newUserDepartment = &models.UserDepartment{
UserCompanyId: newUserCompany.Id,
UserId: newUserCompany.UserId,
CompanyId: newUserCompany.CompanyId,
DepartmentId: newDepartment.Id,
//UserId: newUserCompany.UserId,
CompanyId: newUserCompany.CompanyId,
DepartmentId: newDepartment.Id,
}
_, err = models.AddUserDepartment(newUserDepartment, o)
if err != nil {
... ... @@ -394,7 +376,6 @@ func initUserRole(newUserCompany *models.UserCompany, newRole *models.Role, o or
RoleId: newRole.Id,
UserCompanyId: newUserCompany.Id,
CompanyId: newUserCompany.CompanyId,
UserId: newUserCompany.UserId,
}
_, err = models.AddUserRole(newUserRole, o)
if err != nil {
... ...
... ... @@ -386,33 +386,16 @@ func GetDepartmentUser(companyid int64, departmentid int64) ([]protocol.DepartUs
log.Error("deparment.CompanyId err")
return nil, protocol.NewErrWithMessage("1")
}
const dataSql string = `SELECT b.user_id,b.id AS user_company_id FROM user_department AS a
JOIN user_company AS b ON a.user_company_id = b.id
WHERE a.department_id=? AND b.delete_at=0 `
type UsercompanyId struct {
UserCompanyId int64 `orm:"column(user_company_id)"`
UserId int64 `orm:"column(user_id)"`
}
const dataSql string = `SELECT b.nick_name,a.user_company_id FROM user_department AS a
JOIN user_company AS b ON a.user_company_id = b.id
WHERE a.department_id=? AND b.delete_at=0 AND a.enable_status = 1 `
var (
usercompanyData []UsercompanyId
returnData []protocol.DepartUserBase
returnData []protocol.DepartUserBase
)
err = utils.ExecuteQueryAll(&usercompanyData, dataSql, department.Id)
err = utils.ExecuteQueryAll(&returnData, dataSql, department.Id)
if err != nil {
log.Error("EXECUTE SQL err:%s", err)
return nil, protocol.NewErrWithMessage("1")
}
for _, v := range usercompanyData {
udata, err := models.GetUserById(v.UserId)
if err != nil {
log.Error("获取user数据失败:%s", err)
continue
}
d := protocol.DepartUserBase{
UserCompanyId: v.UserCompanyId,
Name: udata.NickName,
}
returnData = append(returnData, d)
}
return returnData, nil
}
... ...
... ... @@ -15,11 +15,10 @@ import (
func UserAdd(param protocol.RequestUserAdd) error {
var (
userm *models.User
err error
err error
)
//校验用户
err = validCompanyUser(param.CompanyId, param.Phone)
//校验用户是否存在
err = existCompanyUser(param.CompanyId, param.Phone)
if err != nil {
return err
}
... ... @@ -27,48 +26,55 @@ func UserAdd(param protocol.RequestUserAdd) error {
err = validCompanyRole(param.CompanyId, param.Roles)
if err != nil {
log.Error(err.Error())
return protocol.NewErrWithMessage("10031")
return err
}
//校验部门
err = validCompanyDepart(param.CompanyId, param.Departments)
if err != nil {
log.Error(err.Error())
return protocol.NewErrWithMessage("10032")
return err
}
//校验职位
err = validCompanyPosition(param.CompanyId, param.Positions)
if err != nil {
log.Error(err.Error())
return protocol.NewErrWithMessage("10033")
}
userm = &models.User{
NickName: param.Name,
Phone: param.Phone,
return err
}
var (
userId int64
userCompanyid int64
)
o := orm.NewOrm()
o.Begin()
err = registUser(userm, param.CompanyId, o)
//添加用户
userId, err = addNewUser(param.Name, param.Phone, o)
if err != nil {
o.Rollback()
log.Error("registUser err:%s", err)
log.Error("addNewUser err:%s", err)
return protocol.NewErrWithMessage("1")
}
//添加用户公司关系
userCompanyid, err = addUserCompany(userId, param.CompanyId, param.Name, o)
if err != nil {
log.Error("addUserCompany err:%s", err)
return protocol.NewErrWithMessage("1")
}
//添加角色
err = editUserRole(userm.Id, param.CompanyId, param.Roles, o)
err = editUserRole(userCompanyid, userId, param.CompanyId, param.Roles, o)
if err != nil {
o.Rollback()
log.Error("editUserRole err:%s", err)
return protocol.NewErrWithMessage("1")
}
//添加部门
err = editUserDepart(userm.Id, param.CompanyId, param.Departments, o)
err = editUserDepart(userCompanyid, userId, param.CompanyId, param.Departments, o)
if err != nil {
o.Rollback()
log.Error("editUserDepart err:%s", err)
return protocol.NewErrWithMessage("1")
}
//添加职位
err = editUserDepart(userm.Id, param.CompanyId, param.Positions, o)
err = editUserPosition(userCompanyid, userId, param.CompanyId, param.Positions, o)
if err != nil {
o.Rollback()
log.Error("editUserDepart err:%s", err)
... ... @@ -141,7 +147,7 @@ func validCompanyPosition(companyid int64, positionid []int64) error {
return nil
}
func validCompanyUser(companyid int64, phone string) error {
func existCompanyUser(companyid int64, phone string) error {
userdata, err := models.GetUserByPhone(phone)
if err == orm.ErrNoRows {
return nil
... ... @@ -159,56 +165,93 @@ func validCompanyUser(companyid int64, phone string) error {
}
//registUser 注册用户
func registUser(userIn *models.User, companyid int64, o orm.Ormer) error {
// func registUser(userIn *models.User, companyid int64, o orm.Ormer) error {
// var (
// err error
// usrData *models.User
// )
// usrData, err = models.GetUserByPhone(userIn.Phone)
// if err != nil && err != orm.ErrNoRows {
// return err
// }
// if err == orm.ErrNoRows {
// //用户不存在 添加用户
// _, err := models.AddUser(userIn, o)
// if err != nil {
// return err
// }
// }
// if err == nil {
// // 用户存在,更新用户
// usrData.NickName = userIn.NickName
// err = models.UpdateUserById(usrData, []string{"NickName"}, o)
// if err != nil {
// return err
// }
// }
// musercompany := &models.UserCompany{
// CompanyId: companyid,
// UserId: userIn.Id,
// }
// _, err = models.AddUserCompany(musercompany, o)
// if err != nil {
// return err
// }
// return nil
// }
func addNewUser(name string, phone string, o orm.Ormer) (userid int64, err error) {
var (
err error
usrData *models.User
)
usrData, err = models.GetUserByPhone(userIn.Phone)
usrData, err = models.GetUserByPhone(phone)
if err != nil && err != orm.ErrNoRows {
return err
return 0, err
}
if err == orm.ErrNoRows {
//用户不存在 添加用户
_, err := models.AddUser(userIn, o)
usrData = &models.User{
Phone: phone,
NickName: name,
}
_, err := models.AddUser(usrData, o)
if err != nil {
return err
return 0, err
}
return usrData.Id, nil
}
if err == nil {
// 用户存在,更新用户
usrData.NickName = userIn.NickName
err = models.UpdateUserById(usrData, []string{"NickName"}, o)
if err != nil {
return err
}
// 用户存在,
return usrData.Id, nil
}
musercompany := &models.UserCompany{
CompanyId: companyid,
UserId: userIn.Id,
return 0, err
}
func addUserCompany(userId int64, companyId int64, nickname string, o orm.Ormer) (id int64, err error) {
m := &models.UserCompany{
UserId: userId,
CompanyId: companyId,
NickName: nickname,
}
// ok := models.ExistUserCompany(usrData.Id, companyid)
// if !ok {
_, err = models.AddUserCompany(musercompany, o)
id, err = models.AddUserCompany(m, o)
if err != nil {
return err
return 0, err
}
// }
// err = models.EnableUserCompany(usrData.Id, companyid)
return nil
return id, err
}
func editUserDepart(userid int64, companyid int64, departids []int64, o orm.Ormer) error {
func editUserDepart(usercompanyid int64, userid int64, companyid int64, departids []int64, o orm.Ormer) error {
var (
oldDepartIds []int64
err error
delDepartIds []int64
addDepartIds []int64
)
dataSql := `SELECT department_id FROM user_department WHERE enable_status=1 AND company_id=? AND user_id=?`
dataSql2 := `UPDATE user_department SET enable_status = 2 WHERE company_id = ? AND user_id=? AND department_id=?`
datasql3 := `INSERT INTO user_department (user_id,department_id,company_id,enable_status,create_at) VALUES (?,?,?,?,?)`
err = utils.ExecuteQueryAllWithOrmer(o, &oldDepartIds, dataSql, companyid, userid)
dataSql := `SELECT department_id FROM user_department WHERE enable_status=1 AND user_company_id=?`
dataSql2 := `UPDATE user_department SET enable_status = 2 WHERE user_company_id=? AND department_id=?`
datasql3 := `INSERT INTO user_department (user_company_id,department_id,company_id,enable_status,create_time) VALUES (?,?,?,?,?)`
err = utils.ExecuteQueryAllWithOrmer(o, &oldDepartIds, dataSql, usercompanyid)
if err != nil {
e := fmt.Errorf("Execute SQL err:%s", err)
log.Error(e.Error())
... ... @@ -217,7 +260,7 @@ func editUserDepart(userid int64, companyid int64, departids []int64, o orm.Orme
delDepartIds = utils.ArrayInt64Diff(oldDepartIds, departids)
addDepartIds = utils.ArrayInt64Diff(departids, oldDepartIds)
for _, v := range delDepartIds {
err = utils.ExecuteSQLWithOrmer(o, dataSql2, companyid, userid, v)
err = utils.ExecuteSQLWithOrmer(o, dataSql2, usercompanyid, v)
if err != nil {
e := fmt.Errorf("Execute SQL err:%s", err)
log.Error(e.Error())
... ... @@ -226,7 +269,7 @@ func editUserDepart(userid int64, companyid int64, departids []int64, o orm.Orme
}
nowTime := time.Now().String()
for _, v := range addDepartIds {
err = utils.ExecuteSQLWithOrmer(o, datasql3, userid, v, companyid, models.USER_POSITION_ENABLE_YES, nowTime)
err = utils.ExecuteSQLWithOrmer(o, datasql3, usercompanyid, v, companyid, models.USER_POSITION_ENABLE_YES, nowTime)
if err != nil {
e := fmt.Errorf("Execute SQL err:%s", err)
log.Error(e.Error())
... ... @@ -236,17 +279,17 @@ func editUserDepart(userid int64, companyid int64, departids []int64, o orm.Orme
return nil
}
func editUserPosition(userid int64, companyid int64, positionids []int64, o orm.Ormer) error {
func editUserPosition(usercompanyid int64, userid int64, companyid int64, positionids []int64, o orm.Ormer) error {
var (
oldPositionIds []int64
err error
delPositionIds []int64
addPositionIds []int64
)
dataSql := `SELECT position_id FROM user_position WHERE enable_status=1 AND company_id=? AND user_id=?`
dataSql2 := `UPDATE user_position SET enable_status = 2 WHERE company_id = ? AND user_id=? AND position_id=?`
datasql3 := `INSERT INTO user_position (user_id,position_id,company_id,enable_status,create_at) VALUES (?,?,?,?,?)`
err = utils.ExecuteQueryAllWithOrmer(o, &oldPositionIds, dataSql, companyid, userid)
dataSql := `SELECT position_id FROM user_position WHERE enable_status=1 AND user_company_id=?`
dataSql2 := `UPDATE user_position SET enable_status = 2 WHERE user_company_id=? AND position_id=?`
datasql3 := `INSERT INTO user_position (user_company_id,position_id,company_id,enable_status,create_at) VALUES (?,?,?,?,?)`
err = utils.ExecuteQueryAllWithOrmer(o, &oldPositionIds, dataSql, usercompanyid)
if err != nil {
e := fmt.Errorf("Execute SQL err:%s", err)
log.Error(e.Error())
... ... @@ -255,7 +298,7 @@ func editUserPosition(userid int64, companyid int64, positionids []int64, o orm.
delPositionIds = utils.ArrayInt64Diff(oldPositionIds, positionids)
addPositionIds = utils.ArrayInt64Diff(positionids, oldPositionIds)
for _, v := range delPositionIds {
err = utils.ExecuteSQLWithOrmer(o, dataSql2, companyid, userid, v)
err = utils.ExecuteSQLWithOrmer(o, dataSql2, usercompanyid, v)
if err != nil {
e := fmt.Errorf("Execute SQL err:%s", err)
log.Error(e.Error())
... ... @@ -264,7 +307,7 @@ func editUserPosition(userid int64, companyid int64, positionids []int64, o orm.
}
nowTime := time.Now().String()
for _, v := range addPositionIds {
err = utils.ExecuteSQLWithOrmer(o, datasql3, userid, v, companyid, models.USER_POSITION_ENABLE_YES, nowTime)
err = utils.ExecuteSQLWithOrmer(o, datasql3, usercompanyid, v, companyid, models.USER_POSITION_ENABLE_YES, nowTime)
if err != nil {
e := fmt.Errorf("Execute SQL err:%s", err)
log.Error(e.Error())
... ... @@ -273,17 +316,17 @@ func editUserPosition(userid int64, companyid int64, positionids []int64, o orm.
}
return nil
}
func editUserRole(userid int64, companyid int64, roleids []int64, o orm.Ormer) error {
func editUserRole(usercompanyid int64, userid int64, companyid int64, roleids []int64, o orm.Ormer) error {
var (
oldRoleIds []int64
err error
delRoleIds []int64
addRoleIds []int64
)
dataSql := `SELECT role_id FROM user_role WHERE enable_status=1 AND company_id=? AND user_id=?`
dataSql2 := `UPDATE user_role SET enable_status = 2 WHERE company_id =? AND user_id=? AND role_id=?`
datasql3 := `INSERT INTO user_role (user_id,role_id,company_id,enable_status) VALUES (?,?,?,?)`
err = utils.ExecuteQueryAllWithOrmer(o, &oldRoleIds, dataSql, companyid, userid)
dataSql := `SELECT role_id FROM user_role WHERE enable_status=1 AND user_company_id=?`
dataSql2 := `UPDATE user_role SET enable_status = 2 WHERE user_company_id=? AND role_id=?`
datasql3 := `INSERT INTO user_role (user_company_id,role_id,company_id,enable_status) VALUES (?,?,?,?)`
err = utils.ExecuteQueryAllWithOrmer(o, &oldRoleIds, dataSql, usercompanyid)
if err != nil {
e := fmt.Errorf("Execute SQL err:%s", err)
log.Error(e.Error())
... ... @@ -292,7 +335,7 @@ func editUserRole(userid int64, companyid int64, roleids []int64, o orm.Ormer) e
delRoleIds = utils.ArrayInt64Diff(oldRoleIds, roleids)
addRoleIds = utils.ArrayInt64Diff(roleids, oldRoleIds)
for _, v := range delRoleIds {
err = utils.ExecuteSQLWithOrmer(o, dataSql2, companyid, userid, v)
err = utils.ExecuteSQLWithOrmer(o, dataSql2, usercompanyid, v)
if err != nil {
e := fmt.Errorf("Execute SQL err:%s", err)
log.Error(e.Error())
... ... @@ -300,7 +343,7 @@ func editUserRole(userid int64, companyid int64, roleids []int64, o orm.Ormer) e
}
}
for _, v := range addRoleIds {
err = utils.ExecuteSQLWithOrmer(o, datasql3, userid, v, companyid, models.USER_POSITION_ENABLE_YES)
err = utils.ExecuteSQLWithOrmer(o, datasql3, usercompanyid, v, companyid, models.USER_POSITION_ENABLE_YES)
if err != nil {
e := fmt.Errorf("Execute SQL err:%s", err)
log.Error(e.Error())
... ... @@ -310,12 +353,38 @@ func editUserRole(userid int64, companyid int64, roleids []int64, o orm.Ormer) e
return nil
}
func editUserCompany(userCompanyid int64, userid int64, nickname string, o orm.Ormer) error {
m := &models.UserCompany{
Id: userCompanyid,
NickName: nickname,
UserId: userid,
}
err := models.UpdateUserCompanyById(m, []string{"NickName", "UserId"}, o)
return err
}
//校验user和公司的关系是否正确
func validUserCompany(userCompanyid int64, companyid int64) (*models.UserCompany, error) {
ucompany, err := models.GetUserCompanyById(userCompanyid)
if err != nil {
log.Error("GetUserCompanyById err;%s", err)
return nil, protocol.NewErrWithMessage("1")
}
if ucompany.CompanyId != companyid {
log.Error("用户与公司不关联")
return nil, protocol.NewErrWithMessage("1")
}
return ucompany, nil
}
func UserEdit(param protocol.RequestUserEdit) error {
var (
userm *models.User
err error
err error
ucompany *models.UserCompany
)
err = validCompanyUser(param.CompanyId, param.Phone)
//校验公司和用户的关联
ucompany, err = validUserCompany(param.UserCompanyID, param.CompanyId)
if err != nil {
return err
}
... ... @@ -323,50 +392,64 @@ func UserEdit(param protocol.RequestUserEdit) error {
err = validCompanyRole(param.CompanyId, param.Roles)
if err != nil {
log.Error(err.Error())
return protocol.NewErrWithMessage("10031")
return err
}
//校验部门
err = validCompanyDepart(param.CompanyId, param.Departments)
if err != nil {
log.Error(err.Error())
return protocol.NewErrWithMessage("10032")
return err
}
//校验职位
err = validCompanyPosition(param.CompanyId, param.Positions)
if err != nil {
log.Error(err.Error())
return protocol.NewErrWithMessage("10033")
return err
}
userm = &models.User{
Id: param.ID,
NickName: param.Name,
Phone: param.Phone,
//检查用户手机号是否生变更
var (
usrData *models.User
)
usrData, err = models.GetUserById(ucompany.UserId)
if err != nil {
log.Error("获取用户数据失败:%s", err)
return protocol.NewErrWithMessage("1")
}
o := orm.NewOrm()
o.Begin()
// err = registUser(userm, param.CompanyId, o)
// if err != nil {
// o.Rollback()
// log.Error("registUser err:%s", err)
// return protocol.NewErrWithMessage("1")
// }
// TODO 用户数据更新
if usrData.Phone != param.Phone {
//手机号变更
uid, err := addNewUser(param.Name, param.Phone, o)
if err != nil {
o.Rollback()
log.Error("手机号变更,新增用户失败;%s", err)
return protocol.NewErrWithMessage("1")
}
ucompany.UserId = uid
}
//用户数据更新
err = editUserCompany(param.UserCompanyID, ucompany.UserId, param.Name, o)
if err != nil {
o.Rollback()
log.Error("editUserCompany err:%s", err)
return protocol.NewErrWithMessage("1")
}
//添加角色
err = editUserRole(userm.Id, param.CompanyId, param.Roles, o)
err = editUserRole(param.UserCompanyID, ucompany.UserId, param.CompanyId, param.Roles, o)
if err != nil {
o.Rollback()
log.Error("editUserRole err:%s", err)
return protocol.NewErrWithMessage("1")
}
//添加部门
err = editUserDepart(userm.Id, param.CompanyId, param.Departments, o)
err = editUserDepart(param.UserCompanyID, ucompany.UserId, param.CompanyId, param.Departments, o)
if err != nil {
o.Rollback()
log.Error("editUserDepart err:%s", err)
return protocol.NewErrWithMessage("1")
}
//添加职位
err = editUserDepart(userm.Id, param.CompanyId, param.Positions, o)
err = editUserPosition(param.UserCompanyID, ucompany.UserId, param.CompanyId, param.Positions, o)
if err != nil {
o.Rollback()
log.Error("editUserDepart err:%s", err)
... ... @@ -415,13 +498,12 @@ func UserDelete(userCompanyids []int64, companyid int64) error {
log.Error(e.Error())
}
}
return nil
}
func UserList(param protocol.RequestUserList) (protocol.ResponseUserList, error) {
datasql := `SELECT a.id as user_company_id,a.company_id,a.user_id,a.enable, b.phone,b.nick_name
datasql := `SELECT a.id as user_company_id,a.enable, b.phone,a.nick_name
FROM user_company AS a
LEFT JOIN user AS b ON a.user_id = b.id
WHERE a.company_id=? AND a.delete_at = 0 `
... ... @@ -532,6 +614,30 @@ func GetUserRole(usercompanyid int64) []protocol.RoleBase {
return data
}
func GetUserData(usercompanyid int64) (protocol.UserInfoBase, error) {
var (
ucompany *models.UserCompany
err error
uinfo protocol.UserInfoBase
)
ucompany, err = models.GetUserCompanyById(usercompanyid)
if err != nil {
log.Error("获取GetUserCompanyById失败 :%s", err)
return uinfo, err
}
userdata, err := models.GetUserById(ucompany.UserId)
if err != nil {
log.Error("获取GetUserById 失败:%s", err)
return uinfo, err
}
uinfo = protocol.UserInfoBase{
UserCompanyId: ucompany.Id,
Name: ucompany.NickName,
Phone: userdata.Phone,
}
return uinfo, nil
}
//禁用用户
func UserForbid(userCompanyids []int64, companyid int64) error {
if len(userCompanyids) == 0 {
... ...
... ... @@ -154,5 +154,4 @@ func RoleMenuEdit(companyid int64, roleId int64, menuids []int64) error {
}
o.Commit()
return nil
}
... ...
package ucenter
import (
"encoding/json"
"oppmg/common/log"
"oppmg/protocol"
)
func RequestUCenterLogin(account, password string) (*ResponseLogin, error) {
var uclientReturn *ResponseLogin
param := RequesLogin{
Type: 1,
Phone: account,
Password: password,
}
uclient := NewUCenterClient()
btBody, err := uclient.Call(param)
if err != nil {
log.Error("统一用户中心请求失败 err:%s", err)
return nil, protocol.NewErrWithMessage("1")
}
err = json.Unmarshal(btBody, &uclientReturn)
if err != nil {
log.Error("解析统一用户中心响应失败 err:%s", err)
return nil, protocol.NewErrWithMessage("1")
}
if !(uclientReturn.Code == ResponseCode0 &&
uclientReturn.Msg == ResponseMsgOk) {
return nil, protocol.NewErrWithMessage("10021")
}
return uclientReturn, nil
}
func RequestUCenterAddUser(phone string, nickname string, avatar string) (*ResponseAddUser, error) {
var ucenterReturn *ResponseAddUser
param := RequestAddUser{
Phone: phone,
Nickname: nickname,
Avatar: avatar,
Password: "9d1f5048afd96b39a3dae71a99f2c77a30112d29", //默认密码:fmt.Sprintf("%x", sha1.Sum([]byte("mmm1234554321")))
RegIm: 1,
}
uclient := NewUCenterClient()
btBody, err := uclient.Call(param)
if err != nil {
log.Error("统一用户中心请求失败 err:%s", err)
return nil, protocol.NewErrWithMessage("1")
}
err = json.Unmarshal(btBody, &ucenterReturn)
if err != nil {
log.Error("解析统一用户中心响应失败 err:%s", err)
return nil, protocol.NewErrWithMessage("1")
}
if !(ucenterReturn.Code == ResponseCode0 &&
ucenterReturn.Msg == ResponseMsgOk) {
return nil, protocol.NewErrWithMessage("10021")
}
return ucenterReturn, nil
}
... ...
... ... @@ -57,7 +57,7 @@ type ResponseLogin struct {
type RequestAddUser struct {
Phone string `json:"phone"`
RegIm bool `json:"regIm"`
RegIm int8 `json:"regIm"`
Nickname string `json:"nickname"`
Avatar string `json:"avatar"`
Password string `json:"password"`
... ... @@ -86,6 +86,19 @@ func (r RequestAddUser) Valid() error {
return nil
}
type ResponseAddUser struct {
CommResponse
Data struct {
Id int64 `json:"id"`
Phone string `json:"phone"`
Nickname string `json:"nickname"`
Avatar string `json:"avatar"`
Token string `json:"token"`
Accid int64 `json:"accid"`
CustomerAccount int64 `json:"customerAccount"`
} `json:"data"`
}
type RequestCheckCompany struct {
CompanyId int64 `json:"company_id"`
}
... ...
package geetest
import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
)
type GeetestLib struct {
CaptchaID string
PrivateKey string
Client *http.Client
}
type FailbackRegisterRespnse struct {
Success int `json:"success"`
GT string `json:"gt"`
Challenge string `json:"challenge"`
NewCaptcha int `json:"new_captcha"`
}
const (
geetestHost = "http://api.geetest.com"
registerURL = geetestHost + "/register.php"
validateURL = geetestHost + "/validate.php"
)
func MD5Encode(input string) string {
md5Instant := md5.New()
md5Instant.Write([]byte(input))
return hex.EncodeToString(md5Instant.Sum(nil))
}
// 初始化 GeetestLib
func NewGeetestLib(capthcaID string, privateKey string, timeOut time.Duration) (geetest GeetestLib){
client := &http.Client{Timeout: timeOut}
geetest = GeetestLib{capthcaID, privateKey, client}
return
}
func (g *GeetestLib) getFailBackRegisterResponse(success int, challenge string) []byte {
if challenge == "" {
challenge = hex.EncodeToString(md5.New().Sum(nil))
}
response := FailbackRegisterRespnse{
success,
g.CaptchaID,
challenge,
1,
}
res, _ := json.Marshal(response)
return res
}
func (g *GeetestLib) do(req *http.Request) (body []byte, err error) {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
var resp *http.Response
if resp, err = g.Client.Do(req); err != nil {
return
}
defer resp.Body.Close()
if resp.StatusCode >= http.StatusInternalServerError {
err = errors.New("http status code 5xx")
return
}
if body, err = ioutil.ReadAll(resp.Body); err != nil {
return
}
return
}
func (g *GeetestLib) PreProcess(userID string, userIP string) (int8, []byte) {
params := url.Values{}
params.Add("gt", g.CaptchaID)
params.Add("new_captcha", "1")
if userID != "" {
params.Add("user_id", userID)
}
if userIP != "" {
params.Add("ip_adress", userIP)
}
req, _ := http.NewRequest("GET", registerURL+"?"+params.Encode(), nil)
body, err := g.do(req)
if err != nil {
return 0, g.getFailBackRegisterResponse(0, "")
}
challenge := string(body)
if len(challenge) != 32 {
return 0, g.getFailBackRegisterResponse(0, "")
} else {
challenge = MD5Encode(challenge + g.PrivateKey)
return 1, g.getFailBackRegisterResponse(1, challenge)
}
}
func (g *GeetestLib) checkParas(challenge string, validate string, seccode string) bool {
if challenge == "" || validate == "" || seccode == "" {
return false
}
return true
}
func (g *GeetestLib) checkSuccessRes(challenge string, validate string) bool {
return MD5Encode(g.PrivateKey+"geetest"+challenge) == validate
}
func (g *GeetestLib) checkFailbackRes(challenge string, validate string) bool {
return MD5Encode(challenge) == validate
}
func (g *GeetestLib) SuccessValidate(challenge string, validate string, seccode string, userID string, userIP string) bool {
if !g.checkParas(challenge, validate, seccode) {
return false
}
if !g.checkSuccessRes(challenge, validate) {
return false
}
params := url.Values{}
params.Add("seccode", seccode)
params.Add("challenge", challenge)
params.Add("captchaid", g.CaptchaID)
params.Add("sdk", "golang_v1.0.0")
if userID != "" {
params.Add("user_id", userID)
}
if userIP != "" {
params.Add("ip_adress", userIP)
}
req, _ := http.NewRequest("POST", validateURL, strings.NewReader(params.Encode()))
body, err := g.do(req)
if err != nil {
return false
}
res := string(body)
return res == MD5Encode(seccode)
}
func (g *GeetestLib) FailbackValidate(challenge string, validate string, seccode string) bool {
if !g.checkParas(challenge, validate, seccode) {
return false
}
if !g.checkFailbackRes(challenge, validate) {
return false
}
return true
}
... ...
# github.com/360EntSecGroup-Skylar/excelize/v2 v2.0.2
github.com/360EntSecGroup-Skylar/excelize/v2
# github.com/GeeTeam/gt3-golang-sdk v0.0.0-20190704102600-e89c6d964c8f
github.com/GeeTeam/gt3-golang-sdk/geetest
# github.com/astaxie/beego v1.11.1
github.com/astaxie/beego
github.com/astaxie/beego/config
... ...