作者 唐旭辉

日常提交存储

... ... @@ -6,7 +6,7 @@
| 短信验证码 | 未开始 | | |
| 获取 token | 未开始 | | |
| 刷新 token | 未开始 | | |
| 获取角色列表 | 进行中 | | /v1/rbac/:companyid/role | get |
| 获取角色列表 | 完成 | | /v1/rbac/:companyid/role | get |
| 添加角色 | 完成 | 2019.11.26 | /v1/rbac/role | post |
| 编辑角色 | 完成 | 2019.11.26 | /v1/rbac/role | put |
| ~~删除角色~~ | ~~完成(待变更)~~ | ~~ 2019.11.26~~ | /v1/rbac/role | delete |
... ...
... ... @@ -23,5 +23,5 @@ redis_auth = ""
##out_put:"console","file"
log_output = "file"
log_filename = "${aliyun_logs_access||./log/ability.log}"
log_level = "${LOG_LEVEL||debug}"
log_level = "${LOG_LEVEL||error}"
#---自定义配置 结束----
\ No newline at end of file
... ...
... ... @@ -16,18 +16,10 @@ type BaseController struct {
// AppHead protocol.BaseHeader
}
//Options 实现beego.ControllerInterface 的接口
// func (this *BaseController) Options() {
// 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.Output.SetStatus(http.StatusOK)
// return
// }
//Prepare 实现beego.ControllerInterface 的接口
func (this *BaseController) Prepare() {
p := this.Ctx.Input.GetData("RouterPattern")
fmt.Println("====>r:", p)
}
func (this *BaseController) GetAppHead() (appHead protocol.BaseHeader) {
... ... @@ -51,6 +43,7 @@ func (this *BaseController) Finish() {
} else {
log.Info(fmt.Sprintf("<====Send to client: RspBodyData: %s", string(strByte)))
}
}
func (this *BaseController) ResposeJson(msg *protocol.ResponseMessage) {
... ...
... ... @@ -197,14 +197,25 @@ func (c *CompanyController) PositionDelete() {
}
// PositionList 获取职位列表
// @router /:companyid/position [delete]
// @router /:companyid/position [get]
func (c *CompanyController) PositionList() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
var err error
msg = protocol.NewReturnResponse(nil, err)
var (
err error
list []protocol.ResponsePositionInfo
companyid int64
)
param := c.Ctx.Input.Param(":companyid")
companyid, _ = strconv.ParseInt(param, 10, 64)
if companyid <= 0 {
msg = protocol.BadRequestParam("1")
return
}
list, err = servecompany.GetPositionList(companyid)
msg = protocol.NewReturnResponse(list, err)
return
}
... ...
... ... @@ -6,6 +6,7 @@ import (
"oppmg/common/config"
"oppmg/common/log"
"oppmg/middleware"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
... ... @@ -17,11 +18,11 @@ func main() {
log.Debug("加载配置%s", config.MConfig.ConfigName)
orm.RegisterDataBase("default", "mysql", config.MConfig.SqlConn)
// orm.Debug = true
if beego.BConfig.RunMode == "dev" {
beego.BConfig.WebConfig.DirectoryIndex = true
beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger"
}
// if beego.BConfig.RunMode == "dev" {
// beego.BConfig.WebConfig.DirectoryIndex = true
// beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger"
// }
beego.InsertFilter("*", beego.BeforeExec, middleware.LogRouter)
log.Debug("应用启动")
beego.Run()
}
... ...
... ... @@ -55,12 +55,6 @@ var AuthToken = func(ctx *context.Context) {
return
}
//AppSwitch 使用外部变量停止处理新的请求
var AppSwitch = func(ctx *context.Context) {
return
}
//AllowOption 允许跨域请求
var AllowOption = func(ctx *context.Context) {
if ctx.Request.Method != "OPTIONS" {
... ... @@ -77,3 +71,10 @@ var AllowOption = func(ctx *context.Context) {
ctx.Output.Body([]byte("{}"))
return
}
var LogRouter = func(ctx *context.Context) {
// RouterPattern
p := ctx.Input.GetData("RouterPattern")
fmt.Println("====>r:", p)
return
}
... ...
... ... @@ -8,19 +8,35 @@ import (
)
type Company struct {
Id int `orm:"column(id);auto"`
Id int64 `orm:"column(id);auto"`
Name string `orm:"column(name);size(40)"`
UserId int `orm:"column(user_id)"`
UserId int64 `orm:"column(user_id)"`
CreateAt time.Time `orm:"column(create_at);type(timestamp);auto_now"`
UpdateAt time.Time `orm:"column(update_at);type(timestamp)"`
DeleteAt time.Time `orm:"column(delete_at);type(timestamp)"`
Logo string `orm:"column(logo);size(255)"`
Enable int8 `orm:"column(enable)"`
}
func (t *Company) TableName() string {
return "company"
}
//公司是否有效
const (
COMPANY_ENABLE_YES int8 = 1 //有效
COMPANY_ENABLE_NO int8 = 2 //无效
)
func (t *Company) ValidateEnable(v int8) bool {
switch v {
case COMPANY_ENABLE_YES:
return true
case COMPANY_ENABLE_NO:
return true
}
return false
}
func init() {
orm.RegisterModel(new(Company))
}
... ... @@ -35,7 +51,7 @@ func AddCompany(m *Company) (id int64, err error) {
// GetCompanyById retrieves Company by Id. Returns error if
// Id doesn't exist
func GetCompanyById(id int) (v *Company, err error) {
func GetCompanyById(id int64) (v *Company, err error) {
o := orm.NewOrm()
v = &Company{Id: id}
if err = o.Read(v); err == nil {
... ... @@ -59,17 +75,18 @@ func UpdateCompanyById(m *Company) (err error) {
return
}
// DeleteCompany deletes Company by Id and returns error if
// the record to be deleted doesn't exist
func DeleteCompany(id int) (err error) {
func GetCompanyByUser(userid int64) ([]Company, error) {
datasql := `SELECT a.user_id, a.id,a.name,a.logo,a.admin_id FROM company AS a
JOIN user_company AS b ON a.id = b.company_id
WHERE a.enable = 1 AND b.user_id=?`
var (
err error
companys []Company
)
o := orm.NewOrm()
v := Company{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&Company{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
_, err = o.Raw(datasql).QueryRows(&companys)
if err == orm.ErrNoRows {
return companys, nil
}
}
return
return companys, err
}
... ...
... ... @@ -53,6 +53,7 @@ func AddPosition(m *Position, om ...orm.Ormer) (id int64, err error) {
m.CreateAt = time.Now()
m.UpdateAt = time.Now()
m.DeleteAt = time.Unix(0, 0)
m.EnableStatus = "1"
id, err = o.Insert(m)
return
}
... ...
... ... @@ -26,6 +26,22 @@ func (t *User) TableName() string {
return "user"
}
//用户是否有效
const (
USER_ENABLE_YES int8 = 1 //有效
USER_ENABLE_NO int8 = 2 //无效
)
func (t *User) IsEnable() bool {
switch t.EnableStatus {
case USER_ENABLE_YES:
return true
case USER_ENABLE_NO:
return false
}
return false
}
func init() {
orm.RegisterModel(new(User))
}
... ... @@ -70,21 +86,6 @@ func UpdateUserById(m *User) (err error) {
return
}
// DeleteUser deletes User by Id and returns error if
// the record to be deleted doesn't exist
func DeleteUser(id int64) (err error) {
o := orm.NewOrm()
v := User{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&User{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
func GetUserByPhone(phone string) (v *User, err error) {
o := orm.NewOrm()
v = &User{Phone: phone}
... ...
... ... @@ -21,6 +21,7 @@ type UserAuth struct {
DeviceToken string `orm:"column(device_token);size(100)" description:"设备识别码 推送标识"`
CreateAt time.Time `orm:"column(create_at);type(timestamp)" description:"创建时间"`
UpdateAt time.Time `orm:"column(update_at);type(timestamp)" description:"更新时间"`
CurrentCompanyId int64 `orm:"column(current_company_id)"`
}
func (t *UserAuth) TableName() string {
... ... @@ -108,14 +109,11 @@ func ValidateDdevice(deviceType int8) bool {
}
//ReadUserAuthByDevice 读取或创建
func ReadUserAuthByDevice(userId int64, deviceType int8) (*UserAuth, error) {
func GetUserAuthByUser(userId int64) (*UserAuth, error) {
o := orm.NewOrm()
if ok := ValidateDdevice(deviceType); !ok {
return nil, fmt.Errorf("unknown deviceType: %d", deviceType)
}
uAuth := &UserAuth{
UserId: userId,
DeviceType: deviceType,
DeviceType: DEVICE_TYPE_WEB,
}
err := o.Read(uAuth, "UserId", "DeviceType")
if err == nil {
... ...
... ... @@ -17,7 +17,7 @@ type InputElement struct {
ValueList string `json:"value_list"` //输入候选值
Required bool `json:"required"` //是否必填
Placeholder string `json:"Placeholder"` //帮助用户填写输入字段的提示
Disable bool `json:"disable ` //"显示隐藏",
Disable bool `json:"disable"` //"显示隐藏",
CurrentValue string `json:"current_value"` //"当前填写的值"
}
... ...
... ... @@ -33,7 +33,14 @@ type RequestLogin struct {
//ResponseLogin 登录响应
type ResponseLogin struct {
AuthCode string `json:"authcode"`
LoginAuthToken
}
type LoginAuthToken struct {
AccessToken string `json:"access_token"`
ExpiresIn int64 `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
RefreshExpires int64 `json:"refresh_expires"`
}
//RequestSwapCompany 切换公司
... ...
... ... @@ -3,7 +3,7 @@ package protocol
//RequestPageInfo 分页获取数据
type RequestPageInfo struct {
PageIndex int `json:"page_index"`
PageSize int `json:"page_size`
PageSize int `json:"page_size"`
}
//ResponsePageInfo 分页信息
... ...
... ... @@ -10,7 +10,7 @@ type RequestDepartmentAdd struct {
type DepartmentManager struct {
Id int64 `json:"id"`
Name string `json:"name`
Name string `json:"name"`
}
//RequestDepartmentEdit 编辑
... ... @@ -55,12 +55,10 @@ type RequestPositionEdit struct {
//ResponsePositionInfo ...
type ResponsePositionInfo struct {
ID int64 `json:"id"`
CompanyID int64 `json:"company_id"`
Name string `json:"name"`
ParentID int64 `json:"parent_id"`
ParemtName string `json:"parent_name`
CreateTime int64 `json:"create_time`
Id int64 `json:"id" orm:"column(id)"`
Name string `json:"name" orm:"column(name)"`
ParentId int64 `json:"parent_id" orm:"column(parent_id)"`
ParemtName string `json:"parent_name,omitempty" orm:"-"`
}
type RequestPositionDelete struct {
... ... @@ -71,7 +69,7 @@ type RequestPositionDelete struct {
type RequestUserAdd struct {
Name string `json:"name"`
CompanyId int64 `json:"company_id"`
Phone string `json:"phone`
Phone string `json:"phone"`
Departments []int64 `json:"departments"`
Positions []int64 `json:"positions"`
Roles []int64 `json:"roles"`
... ...
... ... @@ -6,10 +6,10 @@ import (
)
func Test_Err(t *testing.T) {
errmsg := NewMesage(0)
errmsg := NewMesage("0")
bt1, _ := json.Marshal(errmsg)
t.Log(string(bt1))
normalmsg := NewErrWithMessage(0)
normalmsg := NewErrWithMessage("0")
bt2, _ := json.Marshal(normalmsg)
t.Log(string(bt2))
}
... ...
package protocol
var errmessge ErrorMap = map[string]string{
//操作
"00000": "成功",
"1": "无效请求",
"101": "clientId或clientSecret无效",
"113": "签名验证失败",
"2": "添加成功",
"3": "修改成功",
"4": "删除成功",
//角色相关
"30001": "请先删除该分组下的其他角色",
"30002": "请先删除该角色下的人员",
"10001": "请先删除该分组下的其他角色",
"10002": "请先删除该角色下的人员",
//职位相关
"10011": "该职位已被使用无法删除",
//安全认证相关
"10021": "账号或密码不正确",
"10022": "账号已被禁用",
}
... ...
... ... @@ -22,10 +22,10 @@ type RequestRoleEdit struct {
}
//RequestRoleOne 获取一个角色数据
type RequestRoleOne struct {
CompanyID int `json:"company_id"`
RoleID int `json:"role_id`
}
// type RequestRoleOne struct {
// CompanyID int `json:"company_id"`
// RoleID int `json:"role_id"`
// }
//ResponseRoleInfo 响应数据
type ResponseRoleInfo struct {
... ...
... ... @@ -32,6 +32,7 @@ func init() {
beego.NSRouter("/role_group", &controllers.RbacController{}, "delete:RoleGroupDelete"),
beego.NSRouter("/:companyid([0-9]+)/role", &controllers.RbacController{}, "get:RoleList"),
),
beego.NSAfter(middleware.LogRouter),
)
nsAuth := beego.NewNamespace("/auth",
... ... @@ -40,5 +41,12 @@ func init() {
)
beego.AddNamespace(nsV1)
beego.AddNamespace(nsAuth)
}
//routerPermission 路由对应的权限
var routerPermission = map[string]string{
"get:/v1/company/:companyid/position": "show",
"post:/v1/company/position": "add",
"put:/v1/company/position": "edit",
"delete:/v1/company/position": "delete",
}
... ...
... ... @@ -9,7 +9,6 @@ import (
"oppmg/common/log"
"oppmg/models"
"oppmg/protocol"
"oppmg/utils"
"strings"
"time"
... ... @@ -43,66 +42,110 @@ func LoginAuthByPassword(account, password string) error {
var (
user *models.User
uAuth *models.UserAuth
companys []models.Company
mcompany models.Company
loginToken protocol.LoginAuthToken
err error
)
user, err = models.GetUserByPhone(account)
if err != nil {
log.Error(err.Error())
return protocol.NewErrWithMessage("1", err)
return protocol.NewErrWithMessage("10021", err)
}
if ok := validatePassword(password, user.Passwd); !ok {
return protocol.NewErrWithMessage("1", err)
return protocol.NewErrWithMessage("10021", err)
}
uAuth, err = models.ReadUserAuthByDevice(user.Id, models.DEVICE_TYPE_WEB)
if err != nil && err != orm.ErrNoRows {
e := fmt.Errorf("ReadUserAuthByDevice(%d,%d) err:%s", user.Id, models.DEVICE_TYPE_WEB, err)
log.Error(e.Error())
return protocol.NewErrWithMessage("1", e)
}
var (
authcode string
authcodeExp time.Time
)
authcode = utils.GenerateIDByUUID()
authcodeExp = time.Now().Add(time.Duration(models.AUTHCODE_TIME) * time.Second)
if err == orm.ErrNoRows {
uAuth := &models.UserAuth{
UserId: user.Id,
AuthCode: authcode,
AuthCodeExp: authcodeExp,
CreateAt: time.Now(),
if ok := user.IsEnable(); !ok {
return protocol.NewErrWithMessage("10022")
}
_, err = models.AddUserAuth(uAuth)
companys, err = models.GetCompanyByUser(user.Id)
if err != nil {
e := fmt.Errorf("AddUserAuth err:%s", err)
e := fmt.Errorf("GetCompanyByUser(%d) err:%s", user.Id, err)
log.Error(e.Error())
return protocol.NewErrWithMessage("1", e)
return protocol.NewErrWithMessage("1")
}
if len(companys) <= 0 {
log.Error("can not found company")
return protocol.NewErrWithMessage("1")
}
if err == nil {
uAuth.AuthCode = authcode
uAuth.AuthCodeExp = authcodeExp
uAuth.UpdateAt = time.Now()
err = models.UpdateUserAuthById(uAuth)
mcompany = companys[0]
loginToken, err = GenerateAuthToken(user.Id, mcompany.Id)
if err != nil {
e := fmt.Errorf("UpdateUserAuthById err:%s", err)
e := fmt.Errorf("GenerateAuthToken err:%s", err)
log.Error(e.Error())
return protocol.NewErrWithMessage("1", e)
}
return protocol.NewErrWithMessage("1")
}
// uAuth, err = models.ReadUserAuthByDevice(user.Id, models.DEVICE_TYPE_WEB)
// if err != nil && err != orm.ErrNoRows {
// e := fmt.Errorf("ReadUserAuthByDevice(%d,%d) err:%s", user.Id, models.DEVICE_TYPE_WEB, err)
// log.Error(e.Error())
// return protocol.NewErrWithMessage("1", e)
// }
// var (
// authcode string
// authcodeExp time.Time
// )
// authcode = utils.GenerateIDByUUID()
// authcodeExp = time.Now().Add(time.Duration(models.AUTHCODE_TIME) * time.Second)
// if err == orm.ErrNoRows {
// uAuth := &models.UserAuth{
// UserId: user.Id,
// AuthCode: authcode,
// AuthCodeExp: authcodeExp,
// CreateAt: time.Now(),
// }
// _, err = models.AddUserAuth(uAuth)
// if err != nil {
// e := fmt.Errorf("AddUserAuth err:%s", err)
// log.Error(e.Error())
// return protocol.NewErrWithMessage("1", e)
// }
// }
// if err == nil {
// uAuth.AuthCode = authcode
// uAuth.AuthCodeExp = authcodeExp
// uAuth.UpdateAt = time.Now()
// err = models.UpdateUserAuthById(uAuth)
// if err != nil {
// e := fmt.Errorf("UpdateUserAuthById err:%s", err)
// log.Error(e.Error())
// return protocol.NewErrWithMessage("1", e)
// }
// }
return nil
}
//RefreshAccessToken 刷新token
func RefreshAccessToken(account string, token string) error {
//ResetLoginToken token存数据库
func ResetLoginToken(loginToken protocol.LoginAuthToken, userid int64, companyid int64) error {
var (
uAuth *models.UserAuth
err error
nowTime = time.Now()
)
uAuth, err = models.GetUserAuthByUser(userid)
if err != nil && err != orm.ErrNoRows {
return err
}
if err == orm.ErrNoRows {
//添加用户授权
uAuth = &models.UserAuth{
UserId: userid,
CurrentCompanyId: companyid,
AccessToken: loginToken.AccessToken,
AccessTokenExp: time.Unix(loginToken.ExpiresIn, 0), //,
RefreshToken: loginToken.RefreshToken,
RefreshTokenExp: time.Unix(loginToken.RefreshExpires, 0),
CreateAt: nowTime,
UpdateAt: nowTime,
DeviceType: models.DEVICE_TYPE_WEB,
}
_, err = models.AddUserAuth(uAuth)
return err
}
//更新用户授权
return nil
}
// func buildNewUserAuth(uid int64,) *models.UserAuth {
// m:=&models.UserAuth{
// User
// }
// return nil
// }
//TODO token 存redis
... ...
package auth
import (
"fmt"
"oppmg/protocol"
"time"
jwt "github.com/dgrijalva/jwt-go"
)
var (
key []byte = []byte("sx87sda0w7x7sd")
)
//MyToken ...
type MyToken struct {
jwt.StandardClaims
UID int64 `json:"uid"`
CompanyID int64 `json:"company_id"`
}
//CreateJWTToken ...
func CreateJWTToken(uid int64, companyid int64, expires int64) (string, error) {
nowTime := time.Now().Unix()
claims := MyToken{
StandardClaims: jwt.StandardClaims{
NotBefore: nowTime,
IssuedAt: nowTime,
ExpiresAt: expires, //过期时间
Issuer: "mmm_oppmg",
},
UID: uid,
CompanyID: companyid,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(key)
}
//ValidJWTToken ...
func ValidJWTToken(tokenString string) (*MyToken, error) {
token, err := jwt.ParseWithClaims(
tokenString,
&MyToken{},
func(token *jwt.Token) (interface{}, error) {
return key, nil
})
if err != nil {
return nil, err
}
if claims, ok := token.Claims.(*MyToken); ok && token.Valid {
// 验证成功,返回信息
return claims, nil
}
// 验证失败
return nil, fmt.Errorf("token Valid fail")
}
func GenerateAuthToken(uid int64, companyid int64) (protocol.LoginAuthToken, error) {
var (
authToken protocol.LoginAuthToken
accesstoken string //主token,请求用
expiresIn int64 = 60 * 30 //主token过期时间,30分钟
refreshtoken string //副token,刷新主token用
refreshExpires int64 = 60 * 30 * 2 //副token 过期时间 ,60分钟
err error
nowtime = time.Now()
)
accesstoken, err = CreateJWTToken(uid, companyid, expiresIn+10)
if err != nil {
return authToken, err
}
refreshtoken, err = CreateJWTToken(uid, companyid, refreshExpires+10)
if err != nil {
return authToken, err
}
authToken.AccessToken = accesstoken
authToken.ExpiresIn = nowtime.Unix() + expiresIn
authToken.RefreshToken = refreshtoken
authToken.RefreshExpires = nowtime.Unix() + refreshExpires
return authToken, err
}
... ...
... ... @@ -67,12 +67,9 @@ func PositionAdd(param protocol.RequestPositionAdd) (*protocol.ResponsePositionI
}
o.Commit()
positioninfo = &protocol.ResponsePositionInfo{
ID: positionAdd.Id,
CompanyID: positionAdd.CompanyId,
Id: positionAdd.Id,
Name: positionAdd.Name,
ParentID: positionAdd.ParentId,
ParemtName: "",
CreateTime: nowTime.Unix(),
ParentId: positionAdd.ParentId,
}
if parentPosition != nil {
positioninfo.ParemtName = parentPosition.Name
... ... @@ -129,13 +126,12 @@ func PositionEdit(param protocol.RequestPositionEdit) (*protocol.ResponsePositio
return nil, protocol.NewErrWithMessage("1", e)
}
positioninfo = &protocol.ResponsePositionInfo{
ID: positionUpdate.Id,
CompanyID: positionUpdate.CompanyId,
Id: positionUpdate.Id,
Name: positionUpdate.Name,
CreateTime: positionUpdate.CreateAt.Unix(),
}
if param.ParentID != 0 {
positioninfo.ParentID = parentPosition.Id
positioninfo.ParentId = parentPosition.Id
positioninfo.ParemtName = parentPosition.Name
}
... ... @@ -270,3 +266,20 @@ func PositionDelete(param protocol.RequestPositionDelete) error {
o.Commit()
return nil
}
func GetPositionList(companyid int64) ([]protocol.ResponsePositionInfo, error) {
const (
dataSql = `SELECT id,parent_id,name FROM position WHERE company_id=? AND delete_at=0`
)
var (
err error
list []protocol.ResponsePositionInfo
)
err = utils.ExecuteQueryAll(&list, dataSql, companyid)
if err != nil {
e := fmt.Errorf("EXECUTE SQL err:%s", err)
log.Error(e.Error())
return nil, protocol.NewErrWithMessage("1", e)
}
return list, nil
}
... ...
... ... @@ -216,11 +216,6 @@ func getRoleGroupByCompany(companyid int64) ([]protocol.RoleInfo, error) {
return roles, err
}
func RoleGetOne(param protocol.RequestRoleOne) (*protocol.ResponseRoleInfo, error) {
// roledata, err := models.GetRoleById(param.RoleID)
return nil, nil
}
func GetRoleGroup() error {
return nil
}
... ...
package utils
import (
"fmt"
"time"
jwt "github.com/dgrijalva/jwt-go"
)
var (
key = []byte("sx87sda0w7x7sd")
)
//MyToken ...
type MyToken struct {
jwt.StandardClaims
UID int `json:"uid"`
CompanyID int `json:"company_id"`
}
//CreateJWTToken ...
func CreateJWTToken(id int) (string, error) {
nowTime := time.Now().Unix()
claims := MyToken{
StandardClaims: jwt.StandardClaims{
NotBefore: nowTime,
IssuedAt: nowTime,
ExpiresAt: 60 * 60 * 2, //过期时间
Issuer: "mmm_oppmg",
},
UID: id,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(key)
}
//ValidJWTToken ...
func ValidJWTToken(tokenString string) (*MyToken, error) {
token, err := jwt.ParseWithClaims(
tokenString,
&MyToken{},
func(token *jwt.Token) (interface{}, error) {
return key, nil
})
if err != nil {
return nil, err
}
if claims, ok := token.Claims.(*MyToken); ok && token.Valid {
// 验证成功,返回信息
return claims, nil
}
// 验证失败
return nil, fmt.Errorf("token Valid fail")
}
... ...
... ... @@ -35,7 +35,7 @@ func ExecuteQueryOneWithOrmer(o orm.Ormer, result interface{}, sqlstr string, pa
var err error
err = o.Raw(sqlstr, param).QueryRow(result)
if err != nil {
return fmt.Errorf("SQL Execute err:%s", err)
return err
}
return nil
}
... ... @@ -57,7 +57,7 @@ func ExecuteQueryAllWithOrmer(o orm.Ormer, result interface{}, sqlstr string, pa
)
_, err = o.Raw(sqlstr, param).QueryRows(result)
if err != nil {
return fmt.Errorf("SQL Execute err:%s", err)
return err
}
return nil
}
... ...
package utils
type TreeDataBuilder interface {
GetPid() int64
GetName() string
GetOrtherData() map[string]interface{}
}
... ...