Browse Source

replace token with jwt token

token_replace
Tooooommy 4 years ago
parent
commit
882699fc06
  1. 88
      controllers/author.go
  2. 101
      controllers/client/login.go
  3. 2
      controllers/client/order_entry.go
  4. 2
      controllers/client/shake_red_envelope.go
  5. 15
      controllers/pc/login.go
  6. 32
      controllers/pc/ws.go
  7. 8
      hdws/ws/client.go
  8. 93
      hdws/ws/login.go
  9. 2
      hdws/ws/msg.go
  10. 61
      hdws/ws/node.go
  11. 4
      hdws/ws/timer.go
  12. 10
      models/activity.go
  13. 42
      models/area_store.go
  14. 85
      models/base.go
  15. 23
      models/customer.go
  16. 46
      models/order_entry_person.go
  17. 27
      models/user.go
  18. 3
      utils/define/define.go
  19. 12
      utils/utils.go

88
controllers/author.go

@ -2,61 +2,73 @@ package controllers
import (
"hudongzhuanjia/libs/jwt"
"hudongzhuanjia/models"
"hudongzhuanjia/utils/code"
"hudongzhuanjia/utils/define"
jwt2 "github.com/dgrijalva/jwt-go"
)
//执行路由方法前校验登陆态,并且解析page、pageSize
type AuthorCtl struct {
BaseCtl
claims *jwt.Claims
AccountId int
AccountType string
claims *jwt.Claims
}
func (t *AuthorCtl) Prepare() {
t.BaseCtl.Prepare()
skip, _ := t.GetInt("skip")
if skip != 0 {
t.claims = &jwt.Claims{
AccountType: "customer",
AccountId: skip,
CustomerId: 1,
CustomerPid: 0,
ActivityId: 1,
AreaId: 1,
StandardClaims: jwt2.StandardClaims{},
}
return
//skip, _ := t.GetInt("skip")
//if skip != 0 {
//t.AccountId
//t.claims = &jwt.Claims{
// AccountType: "customer",
// AccountId: skip,
// CustomerId: 1,
// CustomerPid: 0,
// ActivityId: 1,
// AreaId: 1,
// StandardClaims: jwt2.StandardClaims{},
//}
//return
//} else {
token := ""
if t.Request.SESSION[define.TOKEN] != "" {
token = t.Request.SESSION[define.TOKEN]
} else if t.Request.REQUEST[define.TOKEN] != "" {
token = t.Request.REQUEST[define.TOKEN]
} else if t.Request.HEADER[define.TOKEN] != "" {
token = t.Request.HEADER[define.TOKEN]
} else {
token := ""
if tokenStr, ok := t.Request.SESSION[define.TOKEN]; ok {
token = tokenStr
} else if tokenStr, ok = t.Request.REQUEST[define.TOKEN]; ok {
token = tokenStr
} else if tokenStr, ok = t.Request.HEADER[define.TOKEN]; ok {
token = tokenStr
} else {
var param = make(map[string]interface{}, 0)
err := t.RequestToStruct(&param)
t.CheckErr(err)
if tokenStr, ok := param[define.TOKEN]; ok {
token = tokenStr.(string)
}
}
claims, err := jwt.ParseAccessToken(token)
if err != nil {
t.ERROR("token 失效", code.MSG_ERR_Authority)
}
t.claims = claims
// 最后多地区:子账号的area_id = area_id, 但是主账号的area_id 需要通过activity_id 进行获取
var param = make(map[string]interface{}, 0)
err := t.RequestToStruct(&param)
t.CheckErr(err)
token = param[define.TOKEN].(string)
}
if token == "" {
t.ERROR("token失效", code.MSG_ERR_Authority)
}
_type, id, err := models.ParseToken(token)
if err != nil {
t.ERROR("token失效", code.MSG_ERR_Authority)
return
}
t.AccountType = _type
t.AccountId = id
//claims, err := jwt.ParseAccessToken(token)
//if err != nil {
// t.ERROR("token 失效", code.MSG_ERR_Authority)
//}
//t.claims = claims
// 最后多地区:子账号的area_id = area_id, 但是主账号的area_id 需要通过activity_id 进行获取
//}
}
func (t *AuthorCtl) GetAccountId() int {
return t.claims.AccountId
return t.AccountId
}
func (t *AuthorCtl) GetAccountType() string {
return t.claims.AccountType
return t.AccountType
}

101
controllers/client/login.go

@ -9,6 +9,7 @@ import (
"hudongzhuanjia/logger"
"hudongzhuanjia/models"
activity_service "hudongzhuanjia/services/activity"
"hudongzhuanjia/utils"
"hudongzhuanjia/utils/code"
"hudongzhuanjia/utils/define"
"time"
@ -27,36 +28,41 @@ func (t *UserCtl) EntryLogin() {
password := t.MustGet("password")
activityId := t.MustGetInt("activity_id") // 需要获取
entryPeople := new(models.OrderEntryPerson)
exist, err := entryPeople.Auth(account, password, activityId)
entry := new(models.OrderEntryPerson)
exist, err := entry.Auth(account, password, activityId)
t.CheckErr(err)
t.Assert(exist, code.MSG_ENTRYPEOPLE_NOT_EXIST, "录入人员不存在")
area := new(models.AreaStore)
exist, err = models.Get(area, entryPeople.AreaId)
exist, err = area.Get(area, entry.AreaId)
t.CheckErr(err)
t.Assert(exist, code.MSG_AREASTORE_NOT_EXIST, "地区不存在")
activity := new(models.Activity)
exist, err = models.Get(activity, activityId)
exist, err = activity.Get(activity, activityId)
t.CheckErr(err)
t.Assert(exist, code.MSG_ACTIVITY_NOT_EXIST, "互动不存在")
customer := new(models.Customer)
exist, err = models.Get(customer, entryPeople.Pid)
exist, err = customer.Get(customer, entry.Pid)
t.CheckErr(err)
t.Assert(exist, code.MSG_CUSTOMER_NOT_EXIST, "客户不存在")
// 怎讲activity
token, err := jwt.GenJwtToken(define.TYPE_ENTRYPEOPLE, entryPeople.Id, customer.Id, customer.Pid, entryPeople.AreaId, entryPeople.ActivityId)
//token, err := jwt.GenJwtToken(define.TYPE_ENTRYPEOPLE, entry.Id, customer.Id, customer.Pid, entry.AreaId, entry.ActivityId)
//t.CheckErr(err)
if entry.Token == "" {
entry.Token = utils.GenToken(entry.Name)
}
entry.AreaName = area.Name
entry.ActivityName = activity.Name
entry.IsSpecial = customer.IsSpecial
_, err = entry.Update(entry, entry.Id)
t.CheckErr(err)
t.SetSession(define.TOKEN, token)
entryPeople.Token = token
entryPeople.AreaName = area.Name
entryPeople.ActivityName = activity.Name
entryPeople.IsSpecial = customer.IsSpecial
entry.Token = fmt.Sprintf("%s:%s", define.TYPE_ENTRYPEOPLE, entry.Token)
t.SetSession(define.TOKEN, entry.Token)
t.JSON(map[string]interface{}{
"people": entryPeople,
"people": entry,
})
}
@ -90,15 +96,12 @@ func (t *UserCtl) WxLogin() {
user := new(models.User)
exist, err = user.GetUserByOpenid(info.OpenId)
t.CheckErr(err)
if user.Token == "" {
user.Token = utils.GenToken(user.Openid)
}
user.Nickname = info.Nickname
user.Openid = info.OpenId
user.Gender = func() string {
if info.Sex == 1 {
return "男"
}
return "女"
}()
user.Gender = utils.GetGender(info.Sex)
user.Avatar = info.HeadImageURL
user.Unionid = info.UnionId
user.City = info.City
@ -107,9 +110,9 @@ func (t *UserCtl) WxLogin() {
user.CreatedAt = time.Now()
user.UpdatedAt = time.Now()
if !exist {
_, err = models.Add(user)
_, err = user.Add(user)
} else {
_, err = user.SaveUserInfo(user.Id)
_, err = user.Update(user, user.Id)
}
t.CheckErr(err)
@ -143,13 +146,14 @@ func (t *UserCtl) WxLogin() {
}
}
jwtToken, err := jwt.GenJwtToken(define.TYPE_H5USER, user.Id, customer.Id, customer.Pid, area.Id, activityId)
t.CheckErr(err)
t.SetSession(define.TOKEN, jwtToken)
//jwtToken, err := jwt.GenJwtToken(define.TYPE_USER, user.Id, customer.Id, customer.Pid, area.Id, activityId)
//t.CheckErr(err)
user.Token = fmt.Sprintf("%s:%s", define.TYPE_USER, user.Token)
t.SetSession(define.TOKEN, user.Token)
t.JSON(map[string]interface{}{
"user": user,
"token": jwtToken,
"token": user.Token,
"activity": activity,
"sign_in": signIn,
"sign": signExist,
@ -163,16 +167,41 @@ func (t *UserCtl) WxLogin() {
func (t *UserCtl) Login() {
wxcode := t.MustGet("code")
user := new(models.User)
//user := new(models.User)
token, err := wechat.GetToken(wxcode)
t.CheckErr(err)
user.Openid = token.OpenId
exist, err := user.GetUserByOpenid(user.Openid)
//user.Openid = token.OpenId
//exist, err := user.GetUserByOpenid(user.Openid)
//t.CheckErr(err)
//if !exist {
// _, err = models.Add(user)
// t.CheckErr(err)
//}
info, err := wechat.GetUserInfo(token)
t.CheckErr(err)
user := new(models.User)
exist, err := user.GetUserByOpenid(info.OpenId)
t.CheckErr(err)
if user.Token == "" {
user.Token = utils.GenToken(user.Openid)
}
user.Nickname = info.Nickname
user.Openid = info.OpenId
user.Gender = utils.GetGender(info.Sex)
user.Avatar = info.HeadImageURL
user.Unionid = info.UnionId
user.City = info.City
user.Province = info.Province
user.Country = info.Country
user.CreatedAt = time.Now()
user.UpdatedAt = time.Now()
if !exist {
_, err = models.Add(user)
t.CheckErr(err)
_, err = user.Add(user)
} else {
_, err = user.Update(user, user.Id)
}
t.CheckErr(err)
area := &models.AreaStore{}
admin := 0
@ -198,17 +227,17 @@ func (t *UserCtl) Login() {
}
}
jwtToken, err := jwt.GenJwtToken(define.TYPE_H5USER, user.Id, 0, 0, 0, 0)
t.CheckErr(err)
t.SetSession(define.TOKEN, jwtToken)
//jwtToken, err := jwt.GenJwtToken(define.TYPE_USER, user.Id, 0, 0, 0, 0)
//t.CheckErr(err)
user.Token = fmt.Sprintf("%s:%s", define.TYPE_LIVEUSER, user.Token)
t.SetSession(define.TOKEN, user.Token)
sign, err := im.AccountImport(fmt.Sprintf("%d", user.Id), user.Nickname, user.Avatar)
t.CheckErr(err)
user.Sig = sign
t.JSON(map[string]interface{}{
"user": user,
"token": jwtToken,
"token": user.Token,
"area": area,
"admin": admin,
})
@ -239,7 +268,7 @@ func (t *UserCtl) DebugLogin() {
t.CheckErr(err)
t.Assert(exist, code.MSG_AREASTORE_NOT_EXIST, "地区不存在")
jwtToken, err := jwt.GenJwtToken(define.TYPE_H5USER, user.Id, customer.Id, customer.Pid, area.Id, activityId)
jwtToken, err := jwt.GenJwtToken(define.TYPE_USER, user.Id, customer.Id, customer.Pid, area.Id, activityId)
t.CheckErr(err)
t.SetSession(define.TOKEN, jwtToken)
t.JSON(map[string]interface{}{

2
controllers/client/order_entry.go

@ -35,7 +35,7 @@ func (t *OrderEntryCtl) List() {
goods, err := models.GetGoodsByActivityId(activityId, areaId)
t.CheckErr(err)
if _type == define.TYPE_H5USER {
if _type == define.TYPE_USER {
for index := range goods {
url := fmt.Sprintf("%s/PcClient/Client/OrderEntryCtl/order?"+
"user_id=%d&activity_id=%d&good_id=%d", define.HOST, uid, activityId, goods[index].Id)

2
controllers/client/shake_red_envelope.go

@ -108,7 +108,7 @@ func (t *ShakeRedEnvelopeCtl) Shake() {
t.CheckErr(err)
go ws_send_service.SendShakeRedEnvelope(fmt.Sprintf("%d", activity.Id),
define.TYPE_H5USER, userId, map[string]interface{}{
define.TYPE_USER, userId, map[string]interface{}{
"customer_id": area.CustomerId,
"user_id": user.Id,
"type": "shake_rb",

15
controllers/pc/login.go

@ -15,6 +15,7 @@ import (
"hudongzhuanjia/libs/wx"
"hudongzhuanjia/models"
activity_service "hudongzhuanjia/services/activity"
"hudongzhuanjia/utils"
"hudongzhuanjia/utils/code"
"hudongzhuanjia/utils/define"
)
@ -38,16 +39,22 @@ func (t *UserCtl) Login() {
t.CheckErr(err)
// 主账号无法确定
token, err := jwt.GenJwtToken(define.TYPE_CUSTOMER, customer.Id, customer.Id, customer.Pid, customer.AreaId, customer.ActivityId)
t.CheckErr(err)
t.SetSession(define.TOKEN, token)
customer.Token = token
//token, err := jwt.GenJwtToken(define.TYPE_CUSTOMER, customer.Id, customer.Id, customer.Pid, customer.AreaId, customer.ActivityId)
//t.CheckErr(err)
if customer.Token == "" {
customer.Token = utils.GenToken(customer.Username)
}
customer.Activities = activities
pid := customer.Pid
if pid == 0 {
pid = customer.Id
}
customer.Tag = "activity"
_, err = customer.Update(customer, customer.Id)
t.CheckErr(err)
customer.Token = fmt.Sprintf("%s:%s", define.TYPE_CUSTOMER, customer.Token)
t.SetSession(define.TOKEN, customer.Token)
t.JSON(customer)
}

32
controllers/pc/ws.go

@ -6,6 +6,8 @@ import (
"hudongzhuanjia/logger"
"hudongzhuanjia/models"
"hudongzhuanjia/utils/code"
"hudongzhuanjia/utils/define"
"strings"
"time"
)
@ -61,3 +63,33 @@ func (t *WsCtl) SaveOp() {
}
t.SUCCESS("success")
}
func (t *WsCtl) CheckToken() {
token := t.MustGet("token")
tokens := strings.SplitN(token, ":", 2)
if tokens[0] == define.TYPE_USER { // h5用户
user := &models.User{}
err := user.GetByToken(tokens[1])
t.CheckErr(err)
t.AccountId = user.Id
t.AccountType = tokens[0]
} else if tokens[0] == define.TYPE_CUSTOMER { // 客户
customer := &models.Customer{}
err := customer.GetByToken(tokens[1])
t.CheckErr(err)
t.AccountId = customer.Id
t.AccountType = tokens[0]
} else if tokens[0] == define.TYPE_ENTRYPEOPLE { // 录入人员
entry := &models.OrderEntryPerson{}
err := entry.GetByToken(tokens[1])
t.CheckErr(err)
t.AccountId = entry.Id
t.AccountType = tokens[0]
} else {
t.ERROR("token失效", code.MSG_ERR_Authority)
}
t.JSON(map[string]interface{}{
"account_id": t.AccountId,
"account_type": t.AccountType,
})
}

8
hdws/ws/client.go

@ -10,10 +10,10 @@ type Client struct {
Id string // account_typ:account_id
AccountId int
AccountType string
Pid int
Online bool
RoomId string
node *Node
//Pid int
Online bool
RoomId string
node *Node
*melody.Session
}

93
hdws/ws/login.go

@ -2,33 +2,50 @@ package ws
import (
"fmt"
"hudongzhuanjia/models"
)
func init() {
N.RegisterLogic(LogicLogin, loginFunc)
N.SetMiddleware(LogicLogin, LoginMid)
}
func loginFunc(c *Client, msg *Message) {
if _, ok := msg.Data["token"]; !ok {
func LoginMid(c *Client, msg *Message) {
var token string
var ok bool
if token, ok = msg.Data["token"].(string); !ok || token == "" {
_ = c.WriteJson(map[string]interface{}{
"msg": "token不能为空",
"code": 506,
})
return
}
claims, err := ParseAccessToken(msg.Data["token"].(string))
_type, id, err := models.ParseToken(token)
if err != nil {
_ = c.WriteJson(map[string]interface{}{
"msg": "token解析出错, " + err.Error(),
c.WriteJson(map[string]interface{}{
"msg": "token失效",
"code": 507,
})
return
}
c.Online = true
c.Id = fmt.Sprintf("%s:%d", claims.AccountType, claims.AccountId)
c.AccountId = claims.AccountId
c.AccountType = claims.AccountType
c.Pid = claims.CustomerPid
c.AccountId = id
c.AccountType = _type
c.Id = fmt.Sprintf("%s:%d", c.AccountType, c.AccountId)
//claims, err := ParseAccessToken(msg.Data["token"].(string))
//if err != nil {
// _ = c.WriteJson(map[string]interface{}{
// "msg": "token解析出错, " + err.Error(),
// "code": 507,
// })
// return
//}
//c.Online = true
//c.Id = fmt.Sprintf("%s:%d", claims.AccountType, claims.AccountId)
//c.AccountId = claims.AccountId
//c.AccountType = claims.AccountType
//c.Pid = claims.CustomerPid
if err = c.Register(); err != nil {
_ = c.WriteJson(map[string]interface{}{
"msg": err.Error(),
@ -36,34 +53,34 @@ func loginFunc(c *Client, msg *Message) {
})
return
}
if claims.AccountType == IDCustomer {
if c.Pid == 0 { // 主账号发给子账号
m := &Message{
Type: TypeNotice,
Dest: 0,
Tag: IDCustomer,
RoomId: c.RoomId,
From: c.Id,
Data: map[string]interface{}{
"content": "主账号上线",
},
}
c.Send(m)
} else { // 子账号发给主账号
m := &Message{
Type: TypeNotice,
Dest: claims.CustomerPid,
Tag: IDCustomer,
RoomId: c.RoomId,
From: c.Id,
Data: map[string]interface{}{
"content": "子账号上线",
},
}
c.Send(m)
}
}
//
//if claims.AccountType == IDCustomer {
// if c.Pid == 0 { // 主账号发给子账号
// m := &Message{
// Type: TypeNotice,
// Dest: 0,
// Tag: IDCustomer,
// RoomId: c.RoomId,
// From: c.Id,
// Data: map[string]interface{}{
// "content": "主账号上线",
// },
// }
// c.Send(m)
// } else { // 子账号发给主账号
// m := &Message{
// Type: TypeNotice,
// Dest: claims.CustomerPid,
// Tag: IDCustomer,
// RoomId: c.RoomId,
// From: c.Id,
// Data: map[string]interface{}{
// "content": "子账号上线",
// },
// }
// c.Send(m)
// }
//}
_ = c.WriteJson(map[string]interface{}{
"msg": "登录成功",
"code": 200,

2
hdws/ws/msg.go

@ -1,7 +1,7 @@
package ws
func init() {
N.RegisterLogic("msg", msgFunc)
N.SetMiddleware("msg", msgFunc)
}
// 简单明了

61
hdws/ws/node.go

@ -5,7 +5,6 @@ import (
"fmt"
"github.com/rs/zerolog/log"
"gopkg.in/olahol/melody.v1"
"strings"
"sync"
)
@ -68,35 +67,35 @@ func (t *Node) handleMelodyMessage(client *Client, msg *Message) {
// 删掉注册的
func (t *Node) handleMelodyDisconnect(client *Client) {
if client.Online && strings.HasPrefix(client.Id, IDCustomer) {
if client.Pid == 0 { // 主账号下线 通知子账号
msg := &Message{
Type: TypeNotice,
Dest: 0,
Tag: IDCustomer,
RoomId: client.RoomId,
From: client.Id,
Data: map[string]interface{}{
"id": client.AccountId,
"content": "主账号下线",
},
}
t.Send(msg)
} else { // 子账号下线 通知主账号
msg := &Message{
Type: TypeNotice,
Dest: client.Pid,
Tag: IDCustomer,
RoomId: client.RoomId,
From: client.Id,
Data: map[string]interface{}{
"id": client.AccountId,
"content": "子账号下线",
},
}
t.Send(msg)
}
}
//if client.Online && strings.HasPrefix(client.Id, IDCustomer) {
// if client.Pid == 0 { // 主账号下线 通知子账号
// msg := &Message{
// Type: TypeNotice,
// Dest: 0,
// Tag: IDCustomer,
// RoomId: client.RoomId,
// From: client.Id,
// Data: map[string]interface{}{
// "id": client.AccountId,
// "content": "主账号下线",
// },
// }
// t.Send(msg)
// } else { // 子账号下线 通知主账号
// msg := &Message{
// Type: TypeNotice,
// Dest: client.Pid,
// Tag: IDCustomer,
// RoomId: client.RoomId,
// From: client.Id,
// Data: map[string]interface{}{
// "id": client.AccountId,
// "content": "子账号下线",
// },
// }
// t.Send(msg)
// }
//}
// 释放内存
if room, ok := t.rooms[client.RoomId]; ok {
room.DeleteClient(client.Id)
@ -107,7 +106,7 @@ func (t *Node) handleMelodyDisconnect(client *Client) {
log.Printf("[websocket] [disconnect] [room:%s] [client:%s] online=>%v\n", client.RoomId, client.Id, client.Online)
}
func (t *Node) RegisterLogic(name string, fn logic) {
func (t *Node) SetMiddleware(name string, fn logic) {
t.handles[name] = fn
}

4
hdws/ws/timer.go

@ -7,11 +7,11 @@ import (
)
func init() {
N.RegisterLogic(LogicSync, syncFunc)
N.SetMiddleware(LogicSync, syncFunc)
}
func syncFunc(c *Client, msg *Message) {
if c.AccountType != IDCustomer && c.Pid != 0 {
if c.AccountType != IDCustomer {
c.Write([]byte("此账号无此权限"))
return
}

10
models/activity.go

@ -8,7 +8,12 @@ const ActivityTableName = TableNamePrefix + "activity"
//互动活动
type Activity struct {
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
Model `xorm:"extends"`
//Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
//IsDelete bool `json:"is_delete" xorm:"not null default(0) comment('删除') TINYINT(1)" description:"删除"`
//CreatedAt time.Time `json:"-" xorm:"not null created comment('创建时间') DATETIME" description:"创建时间"`
//UpdatedAt time.Time `json:"-" xorm:"not null updated comment('更新时间') DATETIME" description:"更新时间"`
CustomerId int `json:"customer_id" xorm:"not null default(0) comment('customer_id, 创建客户id') INT(11)"`
ArchId int `json:"arch_id" xorm:"not null default 0 comment('归档id') INT(11)"`
Services []*ActivityModuleService `json:"services,omitempty" xorm:"-" description:"主活动下的服务"`
@ -34,9 +39,6 @@ type Activity struct {
PhoneBgSwitch string `json:"phone_bg_switch" xorm:"not null default('关闭') comment('手机通用背景开关') VARCHAR(255)"`
MaxBgUrl string `json:"max_bg_url" xorm:"not null default('') comment('大屏通用背景') VARCHAR(255)" description:"大屏通用背景"`
MaxBgSwitch string `json:"max_bg_switch" xorm:"not null default('关闭') comment('大屏通用背景开关')" description:"大屏通用背景开关"`
IsDelete bool `json:"is_delete" xorm:"not null default(0) comment('删除') TINYINT(1)" description:"删除"`
CreatedAt time.Time `json:"-" xorm:"not null created comment('创建时间') DATETIME" description:"创建时间"`
UpdatedAt time.Time `json:"-" xorm:"not null updated comment('更新时间') DATETIME" description:"更新时间"`
}
func (t *Activity) TableName() string {

42
models/area_store.go

@ -1,34 +1,34 @@
package models
import (
"github.com/ouxuanserver/osmanthuswine/src/helper"
"time"
"github.com/ouxuanserver/osmanthuswine/src/core"
"github.com/ouxuanserver/osmanthuswine/src/helper"
)
const AreaStoreTableName = TableNamePrefix + "area_store"
//店铺地区
type AreaStore struct {
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
Name string `json:"name" xorm:"not null default('') comment('名字') VARCHAR(255)"`
Type string `json:"type" xorm:"not null default('') comment('地区类型') VARCHAR(255)"`
Address string `json:"address" xorm:"not null default('') comment('地址') VARCHAR(255)"`
ActivityId int `json:"activity_id" xorm:"not null comment('主活动id') BIGINT(20)"`
CustomerId int `json:"customer_id" xorm:"not null default 0 comment('客户id') INT(11)"`
IsMainArea int `json:"is_main_area" xorm:"not null default(0) comment('是否主地区1是') TINYINT(1)"`
AreaServicePhone string `json:"area_service_phone" xorm:"not null default '' comment('地区客服电话') VARCHAR(128)"`
AdminName string `json:"admin_name" xorm:"not null default '' comment('地区管理员名称') VARCHAR(128)"`
Phone string `json:"phone" xorm:"not null default '' comment('地区管理员账号即手机号') VARCHAR(128)"`
Password string `json:"password" xorm:"not null default '' comment('密码') VARCHAR(255)"`
RawPassword string `json:"raw_password" xorm:"not null default '' comment('密码') VARCHAR(255)"`
IsImport int `json:"is_import" xorm:"not null default 0 comment('是否导入的数据') TINYINT(1)"`
AreaGoodsRuleSwitch int `json:"area_goods_rule_switch" xorm:"not null default 0 comment('地区专属商品规则1开启(用自己地区的商品)0关闭(共用主会场的商品)') TINYINT(1)"`
UserId int `json:"user_id" xorm:"not null default 0 comment('用户id') INT(11)"`
IsDelete bool `json:"is_delete" xorm:"not null default(0) comment('软删除') TINYINT(1)"`
CreatedAt time.Time `json:"created_at" xorm:"not null created comment('创建时间') DATETIME"`
UpdatedAt time.Time `json:"updated_at" xorm:"not null updated comment('更新时间') DATETIME"`
Model `xorm:"extends"`
//Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
//IsDelete bool `json:"is_delete" xorm:"not null default(0) comment('软删除') TINYINT(1)"`
//CreatedAt time.Time `json:"created_at" xorm:"not null created comment('创建时间') DATETIME"`
//UpdatedAt time.Time `json:"updated_at" xorm:"not null updated comment('更新时间') DATETIME"`
//
Name string `json:"name" xorm:"not null default('') comment('名字') VARCHAR(255)"`
Type string `json:"type" xorm:"not null default('') comment('地区类型') VARCHAR(255)"`
Address string `json:"address" xorm:"not null default('') comment('地址') VARCHAR(255)"`
ActivityId int `json:"activity_id" xorm:"not null comment('主活动id') BIGINT(20)"`
CustomerId int `json:"customer_id" xorm:"not null default 0 comment('客户id') INT(11)"`
IsMainArea int `json:"is_main_area" xorm:"not null default(0) comment('是否主地区1是') TINYINT(1)"`
AreaServicePhone string `json:"area_service_phone" xorm:"not null default '' comment('地区客服电话') VARCHAR(128)"`
AdminName string `json:"admin_name" xorm:"not null default '' comment('地区管理员名称') VARCHAR(128)"`
Phone string `json:"phone" xorm:"not null default '' comment('地区管理员账号即手机号') VARCHAR(128)"`
Password string `json:"password" xorm:"not null default '' comment('密码') VARCHAR(255)"`
RawPassword string `json:"raw_password" xorm:"not null default '' comment('密码') VARCHAR(255)"`
IsImport int `json:"is_import" xorm:"not null default 0 comment('是否导入的数据') TINYINT(1)"`
AreaGoodsRuleSwitch int `json:"area_goods_rule_switch" xorm:"not null default 0 comment('地区专属商品规则1开启(用自己地区的商品)0关闭(共用主会场的商品)') TINYINT(1)"`
UserId int `json:"user_id" xorm:"not null default 0 comment('用户id') INT(11)"`
}
func (t *AreaStore) TableName() string {

85
models/base.go

@ -1,9 +1,12 @@
package models
import (
"errors"
"fmt"
"hudongzhuanjia/utils/define"
"reflect"
"strings"
"time"
"github.com/ouxuanserver/osmanthuswine/src/core"
"github.com/xormplus/xorm"
@ -11,6 +14,88 @@ import (
const TableNamePrefix = "ox_"
type Model struct {
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
IsDelete bool `json:"is_delete" xorm:"default(0)" description:"是否删除"`
CreatedAt time.Time `json:"created_at" xorm:"created" description:"创建时间"`
UpdatedAt time.Time `json:"updated_at" xorm:"updated" description:"更新时间"`
}
func ParseToken(token string) (_type string, id int, err error) {
tokens := strings.SplitN(token, ":", 2)
if len(tokens) < 2 {
err = errors.New("token失效")
return
}
_type = tokens[0]
if tokens[0] == define.TYPE_USER { // h5用户
user := &User{}
err = user.GetByToken(tokens[1])
if err != nil {
return
}
id = user.Id
} else if tokens[0] == define.TYPE_CUSTOMER { // 客户
customer := &Customer{}
err = customer.GetByToken(tokens[1])
if err != nil {
return
}
id = customer.Id
} else if tokens[0] == define.TYPE_ENTRYPEOPLE { // 录入人员
entry := &OrderEntryPerson{}
err = entry.GetByToken(tokens[1])
if err != nil {
return
}
id = entry.Id
} else {
err = errors.New("token失效")
}
return
}
func (m *Model) TableName(bean interface{}) string {
return core.GetXormAuto().TableName(bean)
}
func (m *Model) Alias(bean interface{}, alias string) string {
tn := m.TableName(bean)
return fmt.Sprintf("%s as %s", tn, alias)
}
func (m *Model) Add(bean interface{}) (int64, error) {
return core.GetXormAuto().InsertOne(bean)
}
func (m *Model) Get(bean interface{}, id interface{}) (bool, error) {
return core.GetXormAuto().NoAutoCondition().Where("is_delete=0 and id=?", id).Get(bean)
}
func (m *Model) Del(bean interface{}, id interface{}) (int64, error) {
return core.GetXormAuto().NoAutoCondition().Where("is_delete=0 and id=?", id).Delete(bean)
}
func (m *Model) Update(bean, id interface{}, field ...string) (int64, error) {
s := core.GetXormAuto().NoAutoCondition().ID(id)
defer s.Close()
if len(field) > 0 {
if field[0] == "*" {
s = s.AllCols()
} else if field[0] == "#" {
s = s.MustCols(field[1:]...)
} else {
s = s.Cols(field...)
}
}
return s.Update(bean)
}
func (m *Model) Exist(bean, id interface{}) (bool, error) {
return core.GetXormAuto().NoAutoCondition().Where("is_delete=0 and id=?", id).Exist(bean)
}
func init() {
err := core.GetXormAuto().Sync2(
new(Activity),

23
models/customer.go

@ -2,8 +2,6 @@ package models
import (
"fmt"
"time"
"github.com/ouxuanserver/osmanthuswine/src/core"
"github.com/ouxuanserver/osmanthuswine/src/helper"
"github.com/pkg/errors"
@ -13,7 +11,12 @@ const CustomerTN = TableNamePrefix + "customer"
//客户表
type Customer struct {
Id int `json:"id" xorm:"not null pk autoincr comment('主键') INT(11)"`
Model `xorm:"extends"`
//Id int `json:"id" xorm:"not null pk autoincr comment('主键') INT(11)"`
//IsDelete bool `json:"-" xorm:"not null default(0) comment('软删除') TINYINT(1)"`
//CreatedAt time.Time `json:"-" xorm:"not null created comment('创建时间') DATETIME"`
//UpdatedAt time.Time `json:"-" xorm:"not null updated comment('更新时间') DATETIME"`
Activities []*Activity `json:"activities" xorm:"-" description:"用户创建的主活动"`
Nickname string `json:"nickname" xorm:"not null default('') comment('昵称') VARCHAR(255)"`
Username string `json:"username" xorm:"not null default('') comment('用户名') VARCHAR(255)"`
@ -33,9 +36,6 @@ type Customer struct {
IsSpecial int `json:"is_special" xorm:"not null default 0 comment('是否是特殊用户') TINYINT(1)"`
RoleId int `json:"role_id" xorm:"not null default(4) comment('1超级管理员|2平台管理员|3普通管理员|4代理会员|5渠道会员|6普通会员') INT(11)"`
TopId int `json:"top_id" xorm:"not null default(0) comment('角色的上级id') INT(11)"`
IsDelete bool `json:"-" xorm:"not null default(0) comment('软删除') TINYINT(1)"`
CreatedAt time.Time `json:"-" xorm:"not null created comment('创建时间') DATETIME"`
UpdatedAt time.Time `json:"-" xorm:"not null updated comment('更新时间') DATETIME"`
}
func (t *Customer) TableName() string {
@ -73,3 +73,14 @@ func (t *Customer) GetByQQOpenid(openid string) (bool, error) {
func (t *Customer) GetByActivityIdAndAreaId(activityId, areaId interface{}) (bool, error) {
return core.GetXormAuto().Where("is_delete=0 and activity_id=? and area_id=?", activityId, areaId).Get(t)
}
func (t *Customer) GetByToken(token string) error {
exist, err := core.GetXormAuto().Where("is_delete=0 and token=?", token).Get(t)
if err != nil {
return err
}
if !exist {
return errors.New("customer信息异常")
}
return nil
}

46
models/order_entry_person.go

@ -1,28 +1,31 @@
package models
import (
"time"
"errors"
"github.com/ouxuanserver/osmanthuswine/src/core"
)
const OrderEntryPersonTableName = TableNamePrefix + "order_entry_person"
type OrderEntryPerson struct {
Id int `json:"id" xorm:"pk autoincr BIGINT(20)"`
Name string `json:"name" xorm:"not null default('') comment('名字') VARCHAR(255)"`
Account string `json:"account" xorm:"not null default('') comment('账号') VARCHAR(255)"`
Password string `json:"password" xorm:"not null default('') comment('密码') VARCHAR(255)"`
Pid int `json:"pid" xorm:"not null default 0 comment('主账号') VARCHAR(255)"`
AreaId int `json:"area_id" xorm:"not null default 0 comment('地区id') BIGINT(20)"`
AreaName string `json:"area_name" xorm:"-"`
ActivityId int `json:"activity_id" xorm:"not null default 0 comment('主活动id') BIGINT(20)"`
ActivityName string `json:"activity_name" xorm:"-"`
Token string `json:"token" xorm:"-"`
IsSpecial int `json:"is_special" xorm:"-"`
IsDelete bool `json:"-" xorm:"not null default(0) comment('软删除') TINYINT(1)"`
CreatedAt time.Time `json:"-" xorm:"not null created comment('创建时间') DATETIME"`
UpdatedAt time.Time `json:"-" xorm:"not null updated comment('更新时间') DATETIME"`
Model `xorm:"extends"`
//Id int `json:"id" xorm:"pk autoincr BIGINT(20)"`
//IsDelete bool `json:"-" xorm:"not null default(0) comment('软删除') TINYINT(1)"`
//CreatedAt time.Time `json:"-" xorm:"not null created comment('创建时间') DATETIME"`
//UpdatedAt time.Time `json:"-" xorm:"not null updated comment('更新时间') DATETIME"`
Name string `json:"name" xorm:"not null default('') comment('名字') VARCHAR(255)"`
Account string `json:"account" xorm:"not null default('') comment('账号') VARCHAR(255)"`
Password string `json:"password" xorm:"not null default('') comment('密码') VARCHAR(255)"`
Pid int `json:"pid" xorm:"not null default 0 comment('主账号') VARCHAR(255)"`
AreaId int `json:"area_id" xorm:"not null default 0 comment('地区id') BIGINT(20)"`
ActivityId int `json:"activity_id" xorm:"not null default 0 comment('主活动id') BIGINT(20)"`
Token string `json:"token" xorm:"not null default '' comment('token') VARCHAR(255)"`
// 展示字段
AreaName string `json:"area_name" xorm:"-"`
ActivityName string `json:"activity_name" xorm:"-"`
IsSpecial int `json:"is_special" xorm:"-"`
}
func (t *OrderEntryPerson) TableName() string {
@ -33,3 +36,14 @@ func (t *OrderEntryPerson) Auth(account, password, activityId interface{}) (bool
return core.GetXormAuto().Where("is_delete=0 and account = ? and password = ? and activity_id = ?",
account, password, activityId).Get(t)
}
func (t *OrderEntryPerson) GetByToken(token string) error {
exist, err := core.GetXormAuto().Where("is_delete=0 and token=?", token).Get(t)
if err != nil {
return err
}
if exist {
return errors.New("录入人员信息异常")
}
return nil
}

27
models/user.go

@ -1,8 +1,7 @@
package models
import (
"time"
"errors"
"github.com/ouxuanserver/osmanthuswine/src/core"
)
@ -10,10 +9,11 @@ const UserTN = TableNamePrefix + "user"
//用户
type User struct {
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
IsDelete bool `json:"is_delete" xorm:"default(0)" description:"是否删除"`
CreatedAt time.Time `json:"created_at" xorm:"created" description:"创建时间"`
UpdatedAt time.Time `json:"updated_at" xorm:"updated" description:"更新时间"`
Model `xorm:"extends"`
//Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
//IsDelete bool `json:"is_delete" xorm:"default(0)" description:"是否删除"`
//CreatedAt time.Time `json:"created_at" xorm:"created" description:"创建时间"`
//UpdatedAt time.Time `json:"updated_at" xorm:"updated" description:"更新时间"`
Username string `json:"username" xorm:"not null default '' comment('用户名') VARCHAR(128)"`
Phone string `json:"phone" xorm:"not null default '' comment('手机号码') VARCHAR(128)"`
@ -28,9 +28,7 @@ type User struct {
Avatar string `json:"avatar" xorm:"not null default '' comment('头像') VARCHAR(128)"`
Gender string `json:"gender" xorm:"not null default '' comment('性别[男,女]') VARCHAR(128)"`
Balance float64 `json:"balance" xorm:"not null default 0.00 comment('余额') DECIMAL(18,2)"`
//ActivityId int `json:"activity_id" description:"主活动id"` // 不存在
//AreaId int `json:"area_id" description:"地区id"` // 不存在
//AreaName string `json:"area_name" description:"地区名字"`
Token string `json:"token" xorm:"not null default '' comment('token') VARCHAR(255)"`
// 无关变量
Sig string `json:"sig" xorm:"-"`
@ -58,3 +56,14 @@ func GetUsersByIds(ids interface{}) ([]*User, error) {
err := core.GetXormAuto().In("id", ids).Find(&users)
return users, err
}
func (t *User) GetByToken(token string) error {
exist, err := core.GetXormAuto().Where("is_delete=0 and token=?", token).Get(t)
if err != nil {
return err
}
if !exist {
return errors.New("token认证错误")
}
return nil
}

3
utils/define/define.go

@ -79,10 +79,11 @@ const (
//)
const (
TYPE_H5USER = "h5user"
TYPE_USER = "h5user"
TYPE_CUSTOMER = "customer"
TYPE_AREAADMIN = "area_admin"
TYPE_ENTRYPEOPLE = "entry_people"
TYPE_LIVEUSER = "live_user" // 直播
)
// 固定长度

12
utils/utils.go

@ -4,6 +4,7 @@ import (
"crypto/sha1"
"encoding/base64"
"fmt"
"github.com/ouxuanserver/osmanthuswine/src/helper"
"hudongzhuanjia/logger"
"hudongzhuanjia/utils/define"
"io/ioutil"
@ -149,3 +150,14 @@ func HandleTicker(ticker time.Duration, f func() error) {
}
}
}
func GetGender(sex int) string {
if sex == 1 {
return "男"
}
return "女"
}
func GenToken(username string) string {
return helper.Md5("guest_app_hdzj" + time.Now().Format("20060102150405") + helper.CreateUUID() + username)
}
Loading…
Cancel
Save