作者 yangfu

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

... ... @@ -29,8 +29,8 @@ log_level = "${LOG_LEVEL||debug}"
##统一用户中心相关配置
ucenter_check_alt = "rsF0pL!6DwjBO735"
ucenter_base_url = "http://suplus-ucenter-dev.fjmaimaimai.com"
ucenter_app_key = "0692f2b7e8d6dbd8526579864b87e3bfbc5d5c31"
ucenter_secret = "0692f2b7e8d6dbd8526579864b87e3bfbc5d5c31"
ucenter_app_key = "39aefef9e22744a3b2d2d3791824ae7b"
ucenter_secret = "cykbjnfqgctn"
# 审批流程修改 消息发布
message_publish = "audit_change"
#---自定义配置 结束----
\ No newline at end of file
... ...
... ... @@ -59,8 +59,15 @@ func (c *AuthController) Login() {
msg = protocol.NewReturnResponse(nil, err)
return
}
err = serveauth.ResetLoginToken(logintoken)
if err != nil {
log.Error("token 信息记录数据库失败")
}
err = serveauth.ResetLoginTokenRedis(logintoken)
msg = protocol.NewReturnResponse(logintoken, err)
if err != nil {
log.Error("token 信息记录redis失败")
}
msg = protocol.NewReturnResponse(logintoken, nil)
return
}
... ...
... ... @@ -18,20 +18,6 @@ type BaseController struct {
beego.Controller
}
func (this *BaseController) Options() {
this.AllowCross() //允许跨域
this.Ctx.ResponseWriter.WriteHeader(204)
this.Data["json"] = map[string]interface{}{}
this.ServeJSON()
}
func (this *BaseController) AllowCross() {
this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Headers", "*")
//this.Ctx.WriteString("")
}
//Prepare 实现beego.ControllerInterface 的接口
func (this *BaseController) Prepare() {
this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
... ... @@ -48,7 +34,7 @@ func (this *BaseController) Prepare() {
func (this *BaseController) GetAppHead() (appHead protocol.BaseHeader) {
appHead.AccessToken = this.Ctx.Input.Header(protocol.HeaderAccessToken)
appHead.RefreshToken = this.Ctx.Input.Header(protocol.HeaderRefreshToken)
//appHead.RefreshToken = this.Ctx.Input.Header(protocol.HeaderRefreshToken)
return
}
... ...
... ... @@ -23,10 +23,19 @@ func (c *CommonController) SelectorDepartment() {
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
DepartmentId int64 `json:"department_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
}
companyid := c.GetCompanyId()
departs := servecommon.SelectorDepartment(companyid)
msg = protocol.NewReturnResponse(departs, nil)
departs := servecommon.SelectorDepartment(companyid, param.DepartmentId)
data := protocol.ResponseListData{List: departs}
msg = protocol.NewReturnResponse(data, nil)
return
}
... ... @@ -87,3 +96,23 @@ func (c *CommonController) SelectorPosition() {
msg = protocol.NewReturnResponse(departs, nil)
return
}
func (c *CommonController) SelectorUserAndDepart() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
DepartmentId int64 `json:"department_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
}
companyid := c.GetCompanyId()
departs, err := servecommon.SelectorUserAndDepartment(param.DepartmentId, companyid)
msg = protocol.NewReturnResponse(departs, err)
return
}
... ...
... ... @@ -226,6 +226,37 @@ func (c *RbacController) RoleHasMenu() {
return
}
//TODO
func (c *RbacController) GetRoleMenuAll() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
log.Info("====>")
list, err := serverbac.GetRoleHasMenuAll(1, 1)
msg = protocol.NewReturnResponse(list, err)
return
}
//RoleMenuEdit 设置角色的菜单
//@router /role/menu/edit
func (c *RbacController) RoleMenuEdit() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
RoleId int64 `json:"role_id"`
MenuIds []int64 `json:"menu_ids"`
}
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()
err := serverbac.RoleMenuEdit(companyid, param.RoleId, param.MenuIds)
msg = protocol.NewReturnResponse(nil, err)
return
}
... ...
... ... @@ -19,7 +19,7 @@ var LogRequestData = func(ctx *context.Context) {
log.Info("====>Recv Request:%s", ctx.Input.URI())
hmap := map[string]string{
protocol.HeaderAccessToken: ctx.Input.Header(protocol.HeaderAccessToken),
protocol.HeaderRefreshToken: ctx.Input.Header(protocol.HeaderRefreshToken),
//protocol.HeaderRefreshToken: ctx.Input.Header(protocol.HeaderRefreshToken),
}
if ctx.Input.RequestBody != nil {
log.Info("====>Recv data from client:\nHeadData: %v \nBodyData: %s", hmap, string(ctx.Input.RequestBody))
... ... @@ -38,7 +38,7 @@ var AuthToken = func(ctx *context.Context) {
mtoken *serveauth.MyToken
)
accesstoken := ctx.Input.Header(protocol.HeaderAccessToken)
refreshToken := ctx.Input.Header(protocol.HeaderRefreshToken)
// refreshToken := ctx.Input.Header(protocol.HeaderRefreshToken)
mtoken, err = serveauth.ValidJWTToken(accesstoken)
if accesstoken == "123456" && beego.BConfig.RunMode != "prod" {
return
... ... @@ -47,14 +47,14 @@ var AuthToken = func(ctx *context.Context) {
storetoken, err = redisdata.GetLoginToken(mtoken.UID)
if err != nil {
log.Error("redisdata.GetLoginToken err:%s", err)
msg = protocol.NewMesage("10024")
msg = protocol.NewMessage("10024")
ctx.Output.JSON(msg, false, false)
return
}
if beego.BConfig.RunMode == "prod" {
//校验是否是单客户端操作
if storetoken.AccessToken != accesstoken {
msg = protocol.NewMesage("10025")
msg = protocol.NewMessage("10025")
ctx.Output.JSON(msg, false, false)
return
}
... ... @@ -64,14 +64,12 @@ var AuthToken = func(ctx *context.Context) {
return
}
if ok := serveauth.IsJwtErrorExpired(err); ok {
//token过期,刷新
logintoken, err := serveauth.RefreshLoginToken(refreshToken)
msg = protocol.NewReturnResponse(logintoken, err)
msg := protocol.NewMessage("10024")
ctx.Output.JSON(msg, false, false)
return
}
log.Error("token 校验失败")
msg = protocol.NewMesage("1")
log.Error("token 校验失败:%s", err)
msg = protocol.NewMessage("10024")
ctx.Output.JSON(msg, false, false)
return
}
... ... @@ -90,8 +88,8 @@ var AllowOption = func(ctx *context.Context) {
AllowAllOrigins: true, //允许的请求来源
})
f(ctx)
ctx.Output.Body([]byte("{}"))
ctx.Output.SetStatus(204)
ctx.Output.Body(nil)
return
}
... ...
... ... @@ -38,3 +38,14 @@ func GetMenuById(id int) (v *Menu, err error) {
}
return nil, err
}
func GetMenuByIds(ids []int64) (v []*Menu, err error) {
o := orm.NewOrm()
_, err = o.QueryTable(&Menu{}).
Filter("id__in", ids).
All(&v)
if err == orm.ErrNoRows {
return v, nil
}
return v, nil
}
... ...
... ... @@ -7,8 +7,9 @@ import (
type RoleMenu struct {
Id int64 `orm:"column(id);auto" description:"主键"`
RoleId int64 `orm:"column(role_id);null" description:"role.id"`
MenuId int64 `orm:"column(menu_id);null" description:"menu.id"`
MenuId int `orm:"column(menu_id);null" description:"menu.id"`
Opption string `orm:"column(opption);size(500);null" description:"配置"`
Code string `orm:"column(code)"`
}
func (t *RoleMenu) TableName() string {
... ... @@ -19,14 +20,6 @@ func init() {
orm.RegisterModel(new(RoleMenu))
}
// AddRoleMenu insert a new RoleMenu into database and returns
// last inserted Id on success.
func AddRoleMenu(m *RoleMenu) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
func GetRoleMenuByRole(roleid int64) ([]RoleMenu, error) {
var (
list []RoleMenu
... ...
... ... @@ -16,6 +16,7 @@ type User struct {
CsAccount int64 `orm:"column(cs_account)" description:"客服有话说ID"`
IsKefu int8 `orm:"column(is_kefu)" description:"是否是客服 0:否 1:是"`
ImToken string `orm:"column(im_token);size(128)" description:"网易云token"`
Accid int64 `orm:"column(accid)" description:"网易云id"`
LastLoginTime time.Time `orm:"column(last_login_time);type(timestamp)" description:"最后一次登录时间"`
CreateAt time.Time `orm:"column(create_at);type(timestamp);auto_now_add" description:"创建时间"`
EnableStatus int8 `orm:"column(enable_status)" description:"是否有效"`
... ...
... ... @@ -133,7 +133,7 @@ type TemplateItem struct {
type VisibleObject struct {
Id string `json:"id"`
Name string `json:"name",omitempty`
Name string `json:"name,omitempty"`
Type int `json:"type"` //1:部门 2:指定人员
}
... ...
... ... @@ -2,7 +2,8 @@ package protocol
//指定的请求头字段
const (
HeaderAccessToken string = "x-mmm-accesstoken"
// HeaderAccessToken string = "x-mmm-accesstoken"
HeaderAccessToken string = "Authorization"
HeaderRefreshToken string = "x-mmm-refreshtoken"
)
... ...
... ... @@ -13,11 +13,15 @@ type ResponsePageInfo struct {
// ListData interface{} `json:"lists"`
}
type ResponseListData struct {
List interface{} `json:"lists"`
}
// DepartmentBase下拉选择列表-部门
type DepartmentBase struct {
Id int64 `json:"id" orm:"column(id)"`
Name string `json:"name" orm:"column(name)"`
ParentId int64 `json:"parent_id" orm:"column(parent_id)"`
ParentId int64 `json:"parentId" orm:"column(parent_id)"`
}
//RoleBase 下拉选择列表-角色
... ... @@ -33,7 +37,7 @@ type RoleBase struct {
type PositionBase struct {
Id int64 `json:"id" orm:"column(id)"`
Name string `json:"name" orm:"column(name)"`
ParentId int64 `json:"parent_id" orm:"column(parent_id)"`
ParentId int64 `json:"parentId" orm:"column(parent_id)"`
}
//DepartUserBase 下拉选择列表-部门下的人员
... ... @@ -41,3 +45,9 @@ type DepartUserBase struct {
UserCompanyId int64 `json:"id" orm:"column(user_company_id)"`
Name string `json:"name" orm:"-"`
}
//部门和人员混合
type DepartAndUser struct {
Departments []DepartmentBase `json:"departments"`
Members []DepartmentMember `json:"members"`
}
... ...
... ... @@ -17,11 +17,6 @@ type DepartmentManager struct {
Name string `json:"name"`
}
type DepartmentMember struct {
Id int64 `json:"id"`
Name string `json:"name"`
}
//RequestDepartmentEdit 编辑
type RequestDepartmentEdit struct {
ID int64 `json:"id"`
... ... @@ -35,12 +30,17 @@ type RequestDepartmentDelete struct {
CompanyID int64 `json:"company_id"` //公司
}
type DepartmentMember struct {
Id int64 `json:"id"`
Name string `json:"name"`
}
//ResponseDepartmentInfo ...
type ResponseDepartmentInfo struct {
ID int64 `json:"id"`
CompanyID int64 `json:"company_id"` //公司
Name string `json:"name"` //部门名字
ParantID int64 `json:"parant_id"` //父级部门Id
ParantID int64 `json:"parantId"` //父级部门Id
Manages []DepartmentManager `json:"manages"` //部门管理员
Members []DepartmentMember `json:"members"` //部门成员
Member int64 `json:"member"` //成员数
... ...
... ... @@ -32,7 +32,7 @@ type ResponseMessage struct {
Data interface{} `json:"data"`
}
func NewMesage(code string) *ResponseMessage {
func NewMessage(code string) *ResponseMessage {
ecode := SearchErr(code)
rsp := &ResponseMessage{
Errno: transformCode(ecode.Errno),
... ... @@ -79,7 +79,7 @@ func (e ErrWithMessage) Unwrap() error {
//ParseToMessage 实现CustomErrParse的接口
func (e ErrWithMessage) ParseToMessage() *ResponseMessage {
return NewMesage(e.Errno)
return NewMessage(e.Errno)
}
func SearchErr(code string) ErrorCode {
... ... @@ -90,7 +90,7 @@ func SearchErr(code string) ErrorCode {
func NewReturnResponse(data interface{}, eRR error) (msg *ResponseMessage) {
// var msg *ResponseMessage
if eRR == nil {
msg = NewMesage("0")
msg = NewMessage("0")
msg.Data = data
return msg
}
... ... @@ -98,12 +98,12 @@ func NewReturnResponse(data interface{}, eRR error) (msg *ResponseMessage) {
return x.ParseToMessage()
}
return NewMesage("1")
return NewMessage("1")
}
//BadRequestParam 控制层响应返回
func BadRequestParam(code string) *ResponseMessage {
return NewMesage(code)
return NewMessage(code)
}
//NewPageDataResponse 控制层分页数据响应返回
... ... @@ -112,9 +112,9 @@ func NewPageDataResponse(data interface{}, eRR error) (msg *ResponseMessage) {
if x, ok := eRR.(CustomErrParse); ok {
return x.ParseToMessage()
}
return NewMesage("1")
return NewMessage("1")
}
msg = NewMesage("0")
msg = NewMessage("0")
msg.Data = map[string]interface{}{
"gridResult": data,
}
... ...
... ... @@ -6,7 +6,7 @@ import (
)
func Test_Err(t *testing.T) {
errmsg := NewMesage("0")
errmsg := NewMessage("0")
bt1, _ := json.Marshal(errmsg)
t.Log(string(bt1))
normalmsg := NewErrWithMessage("0")
... ...
... ... @@ -7,6 +7,7 @@ var errmessge ErrorMap = map[string]string{
//角色相关
"10001": "请先删除该分组下的其他角色",
"10002": "请先删除该角色下的人员",
"10003": "无效角色",
//职位相关
"10011": "该职位已被使用无法删除",
//安全认证相关
... ... @@ -15,7 +16,7 @@ var errmessge ErrorMap = map[string]string{
"10023": "用户无使用权限",
"10024": "登录凭证失效",
"10025": "该账号已在其他地方登录",
"10026": "登录凭证过期",
// "10026": "登录凭证过期",
"10027": "无操作权限",
//用户相关
"10031": "无效角色",
... ...
package routers
import (
"encoding/json"
)
//PermissionBase 路由对应的权限
type PermissionBase struct {
CodeName string //模块标识
ActionName string
MethodMap map[string]func()
}
func (p PermissionBase) ValidMapping(actionName string, fn func()) {
p.MethodMap[actionName] = fn
// MethodMap map[string]func()
}
var routerPermission = map[string]PermissionBase{
... ... @@ -18,22 +18,61 @@ var routerPermission = map[string]PermissionBase{
"/v1/department/delete": PermissionBase{CodeName: "OPPMG_DEPARTMENT", ActionName: "delete"},
}
//PermissionWithPosition 职位管理相关
// type PermissionWithPosition struct {
// PermissionBase
// }
var permissionObject = map[string]interface{}{
"": 0,
}
//模块编号
const (
MENU_DEPARTMENT string = "OPPMG_DEPARTMENT" //公司部门管理模块
MENU_POSITION string = "OPPMG_POSITION" //公司职务管理
MENU_RBAC string = "OPPMG_RBAC" //员工角色/权限设置
MENU_USER string = "OPPMG_USER" //公司员工管理
MENU_ENTERPRISE_BASIC string = "OPPMG_ENTERPRISE_BASIC" //企业基础设置(大节点)
MENU_SYSTEM_FUNCTION string = "OPPMG_SYSTEM_FUNCTION" //系统功能(大节点)
MENU_CONMPANY string = "OPPMG_CONMPANY" //企业信息维护
MENU_CHANCE_TEMP string = "OPPMG_CHANCE_TEMP" //机会模板管理
MENU_SORCE string = "OPPMG_SORCE" //评分模式
MENU_CHANCE string = "OPPMG_CHANCE" //机会管理
)
//GetCode 模块标识
// func (c *PermissionWithPosition) GetCodeName() string {
// return "OPPMG_DEPARTMENT"
// }
type PermissionContentObject interface {
StringUnmarshal(string) error
ObjectMarshal() (string, error)
}
//Valid 权限校验
// func (c PermissionWithPosition) Valid(userCompanyID int64) bool {
// return true
// }
type PermissionContentBase struct {
Check int8 `json:"check"`
}
//PermissionWithDepart 部门管理相关
// type PermissionWithDepart struct {
// Check int8 `json:"check"`
// }
func NewPermissionContentBase() PermissionContentObject {
return &PermissionContentBase{}
}
func (p *PermissionContentBase) StringUnmarshal(s string) error {
err := json.Unmarshal([]byte(s), p)
return err
}
func (p *PermissionContentBase) ObjectMarshal() (string, error) {
bt, err := json.Marshal(p)
if err != nil {
return "", err
}
return string(bt), err
}
type CodeToObject func() PermissionContentObject
var CodePermissionObject = map[string]CodeToObject{
MENU_DEPARTMENT: NewPermissionContentBase, //公司部门管理模块
MENU_POSITION: NewPermissionContentBase, //公司职务管理
MENU_RBAC: NewPermissionContentBase, //员工角色/权限设置
MENU_USER: NewPermissionContentBase, //公司员工管理
MENU_ENTERPRISE_BASIC: NewPermissionContentBase, //企业基础设置(大节点)
MENU_SYSTEM_FUNCTION: NewPermissionContentBase, //系统功能(大节点)
MENU_CONMPANY: NewPermissionContentBase, //企业信息维护
MENU_CHANCE_TEMP: NewPermissionContentBase, //机会模板管理
MENU_SORCE: NewPermissionContentBase, //评分模式
MENU_CHANCE: NewPermissionContentBase, //机会管理
}
... ...
... ... @@ -3,6 +3,8 @@ package routers
import (
"oppmg/controllers"
"github.com/astaxie/beego/context"
"oppmg/middleware"
"github.com/astaxie/beego"
... ... @@ -36,6 +38,7 @@ func init() {
beego.NSRouter("/role/list", &controllers.RbacController{}, "post:RoleList"),
beego.NSRouter("/menu/list", &controllers.RbacController{}, "post:MenuList"),
beego.NSRouter("/role/menu", &controllers.RbacController{}, "post:RoleHasMenu"),
beego.NSRouter("/role/menu/edit", &controllers.RbacController{}, "post:RoleMenuEdit"),
),
beego.NSNamespace("/user",
beego.NSRouter("/list", &controllers.CompanyController{}, "post:UserList"),
... ... @@ -62,6 +65,7 @@ func init() {
beego.NSRouter("/department", &controllers.CommonController{}, "post:SelectorDepartment"),
beego.NSRouter("/role", &controllers.CommonController{}, "post:SelectorRole"),
beego.NSRouter("/position", &controllers.CommonController{}, "post:SelectorPosition"),
beego.NSRouter("/user_and_department", &controllers.CommonController{}, "post:SelectorUserAndDepart"),
),
beego.NSNamespace("/template",
beego.NSRouter("/add", &controllers.TemplateController{}, "post:TemplateAdd"),
... ... @@ -88,9 +92,20 @@ func init() {
beego.NSRouter("/company", &controllers.CompanyController{}, "post:InitCompany"),
beego.NSRouter("/company/info", &controllers.CompanyController{}, "post:GetCompanyForUCenter"),
)
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" {
return true
}
return false
}),
beego.NSRouter("/te", &controllers.RbacController{}, "get:GetRoleMenuAll"),
)
beego.AddNamespace(nsTest)
beego.SetStaticPath("/log", beego.AppConfig.String("log_filename"))
}
... ...
... ... @@ -3,11 +3,13 @@ package auth
import (
"crypto/sha1"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"oppmg/common/log"
"oppmg/models"
"oppmg/protocol"
"oppmg/services/ucenter"
"oppmg/storage/redisdata"
"oppmg/utils"
"strings"
... ... @@ -79,7 +81,7 @@ func ResetLoginToken(loginToken protocol.LoginAuthToken) error {
uAuth.RefreshToken = loginToken.RefreshToken
uAuth.RefreshTokenExp = time.Unix(loginToken.RefreshExpires, 0)
uAuth.UpdateAt = nowTime
upCol := []string{"CurrentCompanyId", "AccessToken", "RefreshToken", "RefreshTokenExp", "UpdateAt"}
upCol := []string{"CurrentCompanyId", "AccessTokenExp", "RefreshTokenExp", "AccessToken", "RefreshToken", "RefreshTokenExp", "UpdateAt"}
if err = models.UpdateUserAuthById(uAuth, upCol); err != nil {
e := fmt.Errorf("UpdateUserAuthById err:%s", err)
log.Error(e.Error())
... ... @@ -189,7 +191,7 @@ func LoginAuthByUCenter(account, password string) (protocol.LoginAuthToken, erro
}
if ok := userdata.IsEnable(); !ok {
log.Debug("userdata.IsEnable()==false")
return logintoken, protocol.NewErrWithMessage("10021")
return logintoken, protocol.NewErrWithMessage("10022")
}
if companys, err = getUserCompanyReal(userdata.Id); err != nil {
log.Error("getUserCompanyReal err:%s", err)
... ... @@ -197,33 +199,55 @@ func LoginAuthByUCenter(account, password string) (protocol.LoginAuthToken, erro
}
if len(companys) == 0 {
log.Debug("no company")
return logintoken, protocol.NewErrWithMessage("10021")
return logintoken, protocol.NewErrWithMessage("10022")
}
companyid = companys[0].Id
// var uclientReturn ucenter.ResponseLogin
// param := ucenter.RequesLogin{
// Phone: account,
// Password: password,
// }
// uclient := ucenter.NewUCenterClient()
// btBody, err := uclient.Call(param)
// var uclientReturn *ucenter.ResponseLogin
// uclientReturn, err = requestUCenterLogin(account, password)
// if err != nil {
// log.Error("统一用户中心请求失败 err:%s", err)
// return logintoken, protocol.NewErrWithMessage("1")
// return logintoken, protocol.NewErrWithMessage("10021")
// }
// err = json.Unmarshal(btBody, &uclientReturn)
// //更新用户数据
// _ = 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 logintoken, protocol.NewErrWithMessage("1")
// }
// if !(uclientReturn.Code == ucenter.ResponseCode0 &&
// uclientReturn.Msg == ucenter.ResponseMsgOk) {
// return logintoken, protocol.NewErrWithMessage("10021")
// 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,
}
uclient := ucenter.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 == ucenter.ResponseCode0 &&
uclientReturn.Msg == ucenter.ResponseMsgOk) {
return nil, protocol.NewErrWithMessage("10021")
}
return uclientReturn, nil
}
type companybase struct {
Id int64 `orm:"column(id)"`
Name string `orm:"coumn(name)"`
... ...
... ... @@ -68,9 +68,9 @@ func GenerateAuthToken(uid int64, companyid int64) (protocol.LoginAuthToken, err
var (
authToken protocol.LoginAuthToken
accesstoken string //主token,请求用
expiresIn int64 = 60 * 30 //主token过期时间,30分钟
expiresIn int64 = 60 * 60 * 2 //主token过期时间,30分钟
refreshtoken string //副token,刷新主token用
refreshExpires int64 = 60 * 30 * 2 //副token 过期时间 ,60分钟
refreshExpires int64 = 60 * 60 * 2 //副token 过期时间 ,60分钟
err error
nowtime = time.Now()
)
... ...
... ... @@ -8,13 +8,21 @@ import (
"oppmg/utils"
)
func SelectorDepartment(companyid int64) []protocol.DepartmentBase {
const dataSql string = `SELECT id,name,parent_id FROM department WHERE company_id = ? AND delete_at = 0`
func SelectorDepartment(companyid int64, departmentid int64) []protocol.DepartmentBase {
var (
err error
departs []protocol.DepartmentBase
cond []interface{}
where string
)
err = utils.ExecuteQueryAll(&departs, dataSql, companyid)
dataSql := `SELECT id,name,parent_id FROM department WHERE company_id = ? AND delete_at = 0 `
cond = append(cond, companyid)
if departmentid >= 0 {
cond = append(cond, departmentid)
where += ` And parent_id=? `
}
err = utils.ExecuteQueryAll(&departs, dataSql+where, cond...)
if err != nil {
e := fmt.Errorf("EXECUTE SQL err:%s", err)
log.Error(e.Error())
... ... @@ -105,3 +113,43 @@ func SelectorPosition(companyid int64) []protocol.PositionBase {
return positions
}
func SelectorUserAndDepartment(departid int64, companyId int64) (*protocol.DepartAndUser, error) {
var (
mDepart *models.Department
departsUser protocol.DepartAndUser
departbase []protocol.DepartmentBase
departMember []protocol.DepartmentMember
err error
where string
cond []interface{}
)
if departid > 0 {
mDepart, err = models.GetDepartmentById(departid)
if err != nil {
log.Error("GetDepartmentById err:%s", err)
return nil, protocol.NewErrWithMessage("1")
}
if mDepart.CompanyId != companyId {
log.Error("companyid err")
return nil, protocol.NewErrWithMessage("1")
}
departMember = mDepart.GetMembers()
departsUser.Members = departMember
}
datasql0 := `SELECT id, company_id,name,parent_id ` +
` FROM department WHERE company_id = ? AND delete_at = 0 `
cond = append(cond, companyId)
if departid >= 0 {
cond = append(cond, departid)
where += ` AND parent_id =? `
}
err = utils.ExecuteQueryAll(&departbase, datasql0+where, cond...)
if err != nil {
e := fmt.Errorf("EXECUTE SQL err:%s", err)
log.Error(e.Error())
return nil, protocol.NewErrWithMessage("1", err)
}
departsUser.Departments = departbase
return &departsUser, nil
}
... ...
... ... @@ -380,7 +380,7 @@ func GetDepartmentUser(companyid int64, departmentid int64) ([]protocol.DepartUs
department, err = models.GetDepartmentById(departmentid)
if err != nil {
log.Error("获取部门失败:%s", err)
return nil, protocol.NewErrWithMessage("1")
return nil, nil
}
if department.CompanyId != companyid {
log.Error("deparment.CompanyId err")
... ...
package rbac
import (
"oppmg/common/log"
"oppmg/models"
"oppmg/protocol"
"oppmg/utils"
"github.com/astaxie/beego/orm"
)
//获取全部的权限菜单
func GetMenuAll() ([]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
}
//
func GetRoleHasMenu(roleid int64, companyid int64) (*protocol.ResponseRoleMenus, error) {
var (
roleData *models.Role
err error
)
roleData, err = models.GetRoleById(roleid)
if err != nil {
log.Error("获取角色数据失败:%s", err)
return nil, err
}
if roleData.Types != models.ROLETYPES_ROLE {
log.Error("角色类型错误")
return nil, protocol.NewErrWithMessage("1")
}
if roleData.CompanyId != companyid {
log.Error("角色的公司id不匹配")
return nil, protocol.NewErrWithMessage("1")
}
var (
rolemenu []models.RoleMenu
ids []int64
)
rolemenu, err = models.GetRoleMenuByRole(roleid)
if err != nil {
log.Error("获取角色下的菜单数据失败:%s", err)
return nil, protocol.NewErrWithMessage("1")
}
for _, v := range rolemenu {
ids = append(ids, int64(v.MenuId))
}
data := &protocol.ResponseRoleMenus{
RoleId: roleData.Id,
RoleName: roleData.Name,
MenuId: ids,
}
return data, nil
}
func GetRoleHasMenuAll(roleid int64, companyid int64) (map[string]PermissionContentObject, error) {
var (
roleData *models.Role
err error
)
roleData, err = models.GetRoleById(roleid)
if err != nil {
log.Error("获取角色数据失败:%s", err)
return nil, err
}
if roleData.Types != models.ROLETYPES_ROLE {
log.Error("角色类型错误")
return nil, protocol.NewErrWithMessage("1")
}
if roleData.CompanyId != companyid {
log.Error("角色的公司id不匹配")
return nil, protocol.NewErrWithMessage("1")
}
var (
rolemenu []models.RoleMenu
returnList = make(map[string]PermissionContentObject)
)
rolemenu, err = models.GetRoleMenuByRole(roleid)
if err != nil {
log.Error("获取角色下的菜单数据失败:%s", err)
return nil, protocol.NewErrWithMessage("1")
}
for _, v := range rolemenu {
if fn, ok := CodePermissionObject[v.Code]; ok {
obj := fn()
err := obj.StringUnmarshal(v.Opption)
if err != nil {
log.Error("解析权限规则失败", err)
continue
}
returnList[v.Code] = obj
}
}
return returnList, nil
}
func RoleMenuEdit(companyid int64, roleId int64, menuids []int64) error {
roleMenus, err := GetRoleHasMenu(companyid, roleId)
if err != nil {
return err
}
var (
oldMenuIds []int64
addMenuIds []int64
delMenuIds []int64
addMenu []*models.Menu
)
oldMenuIds = roleMenus.MenuId
addMenuIds = utils.ArrayInt64Diff(menuids, oldMenuIds)
delMenuIds = utils.ArrayInt64Diff(oldMenuIds, menuids)
if len(addMenuIds) > 0 {
addMenu, err = models.GetMenuByIds(addMenuIds)
if err != nil {
log.Error("获取菜单数据失败:%s", err)
return protocol.NewErrWithMessage("1")
}
}
o := orm.NewOrm()
o.Begin()
if len(delMenuIds) > 0 {
_, err = o.QueryTable(&models.RoleMenu{}).
Filter("role_id", roleId).
Filter("menu_id__in", delMenuIds).
Delete()
if err != nil {
log.Error("删除角色和菜单关系失败:%s", err)
o.Rollback()
return protocol.NewErrWithMessage("1")
}
}
for _, v := range addMenu {
m := models.RoleMenu{
RoleId: roleId,
MenuId: v.Id,
Code: v.Code,
Opption: "{}",
}
if _, err = o.Insert(&m); err != nil {
log.Error("添加角色和菜单关系失败:%s", err)
o.Rollback()
return protocol.NewErrWithMessage("1")
}
}
o.Commit()
return nil
}
... ...
package rbac
import (
"oppmg/common/log"
"oppmg/models"
"oppmg/protocol"
"oppmg/utils"
"encoding/json"
)
//获取全部的权限菜单
func GetMenuAll() ([]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
//PermissionBase 路由对应的权限
type PermissionBase struct {
CodeName string //模块标识
ActionName string
// MethodMap map[string]func()
}
//
func GetRoleHasMenu(roleid int64, companyid int64) (*protocol.ResponseRoleMenus, error) {
var (
roleData *models.Role
err error
)
roleData, err = models.GetRoleById(roleid)
if err != nil {
log.Error("获取角色数据失败:%s", err)
return nil, err
}
if roleData.Types != models.ROLETYPES_ROLE {
log.Error("角色类型错误")
return nil, protocol.NewErrWithMessage("1")
}
if roleData.CompanyId != companyid {
log.Error("角色的公司id不匹配")
return nil, protocol.NewErrWithMessage("1")
}
var (
rolemenu []models.RoleMenu
ids []int64
)
rolemenu, err = models.GetRoleMenuByRole(roleid)
var routerPermission = map[string]PermissionBase{
"/v1/department/list": PermissionBase{CodeName: "OPPMG_DEPARTMENT", ActionName: "check"},
"/v1/department/add": PermissionBase{CodeName: "OPPMG_DEPARTMENT", ActionName: "add"},
"/v1/department/edit": PermissionBase{CodeName: "OPPMG_DEPARTMENT", ActionName: "edit"},
"/v1/department/delete": PermissionBase{CodeName: "OPPMG_DEPARTMENT", ActionName: "delete"},
}
var permissionObject = map[string]interface{}{
"": 0,
}
//模块编号
const (
MENU_DEPARTMENT string = "OPPMG_DEPARTMENT" //公司部门管理模块
MENU_POSITION string = "OPPMG_POSITION" //公司职务管理
MENU_RBAC string = "OPPMG_RBAC" //员工角色/权限设置
MENU_USER string = "OPPMG_USER" //公司员工管理
MENU_ENTERPRISE_BASIC string = "OPPMG_ENTERPRISE_BASIC" //企业基础设置(大节点)
MENU_SYSTEM_FUNCTION string = "OPPMG_SYSTEM_FUNCTION" //系统功能(大节点)
MENU_CONMPANY string = "OPPMG_CONMPANY" //企业信息维护
MENU_CHANCE_TEMP string = "OPPMG_CHANCE_TEMP" //机会模板管理
MENU_SORCE string = "OPPMG_SORCE" //评分模式
MENU_CHANCE string = "OPPMG_CHANCE" //机会管理
)
type PermissionContentObject interface {
StringUnmarshal(string) error
ObjectMarshal() (string, error)
}
type PermissionContentBase struct {
Check int8 `json:"check"`
}
func NewPermissionContentBase() PermissionContentObject {
return &PermissionContentBase{}
}
func (p *PermissionContentBase) StringUnmarshal(s string) error {
err := json.Unmarshal([]byte(s), p)
return err
}
func (p *PermissionContentBase) ObjectMarshal() (string, error) {
bt, err := json.Marshal(p)
if err != nil {
log.Error("获取角色下的菜单数据失败:%s", err)
return nil, protocol.NewErrWithMessage("1")
}
for _, v := range rolemenu {
ids = append(ids, v.MenuId)
return "", err
}
data := &protocol.ResponseRoleMenus{
RoleId: roleData.Id,
RoleName: roleData.Name,
MenuId: ids,
}
return data, nil
return string(bt), err
}
func RoleMenuEdit(companyid int64, roleid int64, menuids []int64) {
type CodeToObject func() PermissionContentObject
var CodePermissionObject = map[string]CodeToObject{
MENU_DEPARTMENT: NewPermissionContentBase, //公司部门管理模块
MENU_POSITION: NewPermissionContentBase, //公司职务管理
MENU_RBAC: NewPermissionContentBase, //员工角色/权限设置
MENU_USER: NewPermissionContentBase, //公司员工管理
MENU_ENTERPRISE_BASIC: NewPermissionContentBase, //企业基础设置(大节点)
MENU_SYSTEM_FUNCTION: NewPermissionContentBase, //系统功能(大节点)
MENU_CONMPANY: NewPermissionContentBase, //企业信息维护
MENU_CHANCE_TEMP: NewPermissionContentBase, //机会模板管理
MENU_SORCE: NewPermissionContentBase, //评分模式
MENU_CHANCE: NewPermissionContentBase, //机会管理
}
... ...
... ... @@ -158,11 +158,6 @@ func RoleGroupDelete(param protocol.RequestRoleDelete) error {
return nil
}
//CanSetRole 操作员是否可以操作角色
func CanSetRole(adminId int64, groupId int64) bool {
return false
}
func GetRoleList(companyId int64) ([]protocol.RoleGroup, error) {
var (
roleGroups []protocol.RoleGroup
... ... @@ -213,19 +208,3 @@ func getRoleGroupByCompany(companyid int64) ([]protocol.RoleInfo, error) {
err = utils.ExecuteQueryAll(&roles, datasql, companyid, models.ROLETYPES_GROUP)
return roles, err
}
func GetRoleGroup() error {
return nil
}
func RoleHasPermission() error {
return nil
}
func PermissionHasRole() error {
return nil
}
func RolsHasUser() error {
return nil
}
... ...
... ... @@ -14,6 +14,7 @@ type CommResponse struct {
//RequesLogin 用户登录
type RequesLogin struct {
Type int8 `json:"type"`
Password string `json:"password"`
Phone string `json:"phone"`
}
... ... @@ -27,7 +28,7 @@ func (r RequesLogin) Format() []byte {
//Format 实现IUCenterParam接口
func (r RequesLogin) GetPath() (string, string) {
return "/auth/login", "POST"
return "/auth/serverLogin", "POST"
}
//Format 实现IUCenterParam接口
... ... @@ -48,6 +49,9 @@ type ResponseLogin struct {
Phone string `json:"phone"`
NickName string `json:"nickname"` //昵称
Avatar string `json:"avatar"` //头像
Imtoken string `json:"imtoken"` //网易云imtoken
Accid int64 `json:"accid"`
CustomerAccount int64 `json:"customerAccount"` //客服id
} `json:"data"`
}
... ...
... ... @@ -55,7 +55,7 @@ func buildCheckSum(nowTime string) string {
//httpDo post发送json
func (client UCenterClient) httpDo(path string, mathod string, posts []byte) ([]byte, error) {
httpclient := http.Client{
Timeout: 5 * time.Second, //请求超时时间5秒
Timeout: 10 * time.Second, //请求超时时间5秒
}
reqURL := client.baseUrl + path
req, err := http.NewRequest(mathod, reqURL, bytes.NewReader(posts))
... ... @@ -64,7 +64,9 @@ func (client UCenterClient) httpDo(path string, mathod string, posts []byte) ([]
}
req.Header = client.buildHeader()
resp, err := httpclient.Do(req)
log.Info("====>Send To UCenter:%s", string(posts))
// log.Info("====>Send Header:%v", req.Header)
if err != nil {
return nil, err
}
... ...
... ... @@ -9,5 +9,4 @@ type RedisLoginToken struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
CurrentCompany int64 `json:"current_company"`
IsOk bool `json:"-"`
}
... ...
... ... @@ -23,7 +23,6 @@ func SetLoginToken(param protocol.LoginAuthToken, userid int64, companyid int64)
AccessToken: param.AccessToken,
RefreshToken: param.RefreshToken,
CurrentCompany: companyid,
IsOk: true,
}
value, _ = json.Marshal(data)
exp = param.RefreshExpires - nowTime
... ... @@ -67,8 +66,26 @@ func ExistLoginToken(userid int64) bool {
func DeleteLoginToken(userid int64) error {
client := redis.GetRedis()
key := fmt.Sprintf("%s%s:%d", KEY_PREFIX, KEY_USER_TOKEN, userid)
err:=client.Del(key).Err()
err := client.Del(key).Err()
return err
}
// 刷新token 的有效期
func RefreshLoginTokenExpires(userid int64) error {
client := redis.GetRedis()
key := fmt.Sprintf("%s%s:%d", KEY_PREFIX, KEY_USER_TOKEN, userid)
result, err := client.Exists(key).Result()
if err != nil {
return err
}
if result == 0 {
return nil
}
_, err = client.Expire(key, 30*time.Minute).Result()
if err != nil {
return err
}
return nil
}
//消息发布订阅
... ...
... ... @@ -14,7 +14,7 @@ func ArrayInt64Diff(arr1 []int64, arr2 []int64) []int64 {
}
setmap := make(map[int64]bool)
for i := range arr2 {
setmap[arr1[i]] = true
setmap[arr2[i]] = true
}
var result []int64
for i := range arr1 {
... ... @@ -26,6 +26,25 @@ func ArrayInt64Diff(arr1 []int64, arr2 []int64) []int64 {
return result
}
//ArrayIntDiff 返回切片的差集:arr1-arr2
func ArrayIntDiff(arr1 []int, arr2 []int) []int {
if len(arr2) == 0 {
return arr1
}
setmap := make(map[int]bool)
for i := range arr2 {
setmap[arr1[i]] = true
}
var result []int
for i := range arr1 {
if _, ok := setmap[arr1[i]]; !ok {
result = append(result, arr1[i])
}
}
return result
}
//ArrayStringIn 检查s字符串是否在切片sl中
func ArrayStringIn(arr1 []string, s string) bool {
for _, v := range arr1 {
... ...
... ... @@ -70,6 +70,7 @@ token 的响应内容
```json
{
"token":""
"code": 0,
"msg": "成功",
"data": {
... ... @@ -147,7 +148,6 @@ token 的响应内容
## 公司部门管理
### 部门列表
- 请求路径:/v1/department/list
... ... @@ -155,9 +155,7 @@ token 的响应内容
- 请求 json:
```json
{
}
{}
```
- 正常响应 json
... ... @@ -167,16 +165,18 @@ token 的响应内容
"code": 0,
"msg": "成功",
"data": {
"list": [
"lists": [
{
"id": 1,
"company_id": 1,
"name": "部门1",
"parant_id": 0,
"manages": [{
"id":1,
"name":"主管"
}],
"manages": [
{
"id": 1,
"name": "主管"
}
],
"member": 1
},
{
... ... @@ -184,10 +184,12 @@ token 的响应内容
"company_id": 1,
"name": "部门1-2",
"parant_id": 1,
"manages": [{
"id":1,
"name":"主管"
}],
"manages": [
{
"id": 1,
"name": "主管"
}
],
"member": 1
}
]
... ... @@ -199,9 +201,6 @@ token 的响应内容
---
### 添加部门
- 请求路径:/v1/department/add
... ... @@ -289,7 +288,6 @@ token 的响应内容
## 公司职位管理
### 职位列表
- 请求路径:/v1/position/list
... ... @@ -297,9 +295,7 @@ token 的响应内容
- 请求 json:
```json
{
}
{}
```
- 响应 json
... ... @@ -448,6 +444,7 @@ token 的响应内容
---
## 公司员工角色
### 角色列表
- 请求路径:/v1/rbac/role/list
... ... @@ -455,15 +452,12 @@ token 的响应内容
- 请求 json:
```json
{
}
{}
```
- 响应 json
```json
{
"code": 0,
"msg": "成功",
... ... @@ -569,9 +563,6 @@ token 的响应内容
---
### 添加角色
- 请求路径:/v1/rbac/role/add
... ...