作者 唐旭辉

新增

@@ -10,6 +10,7 @@ require ( @@ -10,6 +10,7 @@ require (
10 github.com/lib/pq v1.2.0 // indirect 10 github.com/lib/pq v1.2.0 // indirect
11 github.com/onsi/ginkgo v1.10.3 // indirect 11 github.com/onsi/ginkgo v1.10.3 // indirect
12 github.com/onsi/gomega v1.7.1 // indirect 12 github.com/onsi/gomega v1.7.1 // indirect
  13 + github.com/satori/go.uuid v1.2.0
13 github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 // indirect 14 github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 // indirect
14 github.com/sony/sonyflake v1.0.0 15 github.com/sony/sonyflake v1.0.0
15 golang.org/x/crypto v0.0.0-20191119213627-4f8c1d86b1ba // indirect 16 golang.org/x/crypto v0.0.0-20191119213627-4f8c1d86b1ba // indirect
@@ -45,6 +45,8 @@ github.com/onsi/gomega v1.7.1 h1:K0jcRCwNQM3vFGh1ppMtDh/+7ApJrjldlX8fA0jDTLQ= @@ -45,6 +45,8 @@ github.com/onsi/gomega v1.7.1 h1:K0jcRCwNQM3vFGh1ppMtDh/+7ApJrjldlX8fA0jDTLQ=
45 github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= 45 github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
46 github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= 46 github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
47 github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 47 github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
  48 +github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww=
  49 +github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
48 github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 h1:X+yvsM2yrEktyI+b2qND5gpH8YhURn0k8OCaeRnkINo= 50 github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 h1:X+yvsM2yrEktyI+b2qND5gpH8YhURn0k8OCaeRnkINo=
49 github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644/go.mod h1:nkxAfR/5quYxwPZhyDxgasBMnRtBZd0FCEpawpjMUFg= 51 github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644/go.mod h1:nkxAfR/5quYxwPZhyDxgasBMnRtBZd0FCEpawpjMUFg=
50 github.com/siddontang/go v0.0.0-20180604090527-bdc77568d726/go.mod h1:3yhqj7WBBfRhbBlzyOC3gUxftwsU0u8gqevxwIHQpMw= 52 github.com/siddontang/go v0.0.0-20180604090527-bdc77568d726/go.mod h1:3yhqj7WBBfRhbBlzyOC3gUxftwsU0u8gqevxwIHQpMw=
@@ -11,7 +11,7 @@ import ( @@ -11,7 +11,7 @@ import (
11 ) 11 )
12 12
13 type User struct { 13 type User struct {
14 - Id int `orm:"column(id);pk" description:"用户id"` 14 + Id int64 `orm:"column(id);pk" description:"用户id"`
15 NickName string `orm:"column(nick_name);size(100)" description:"昵称"` 15 NickName string `orm:"column(nick_name);size(100)" description:"昵称"`
16 Phone string `orm:"column(phone);size(40)" description:"手机号码"` 16 Phone string `orm:"column(phone);size(40)" description:"手机号码"`
17 Passwd string `orm:"column(passwd);size(128)" description:"密码"` 17 Passwd string `orm:"column(passwd);size(128)" description:"密码"`
@@ -42,7 +42,7 @@ func AddUser(m *User) (id int64, err error) { @@ -42,7 +42,7 @@ func AddUser(m *User) (id int64, err error) {
42 42
43 // GetUserById retrieves User by Id. Returns error if 43 // GetUserById retrieves User by Id. Returns error if
44 // Id doesn't exist 44 // Id doesn't exist
45 -func GetUserById(id int) (v *User, err error) { 45 +func GetUserById(id int64) (v *User, err error) {
46 o := orm.NewOrm() 46 o := orm.NewOrm()
47 v = &User{Id: id} 47 v = &User{Id: id}
48 if err = o.Read(v); err == nil { 48 if err = o.Read(v); err == nil {
@@ -146,7 +146,7 @@ func UpdateUserById(m *User) (err error) { @@ -146,7 +146,7 @@ func UpdateUserById(m *User) (err error) {
146 146
147 // DeleteUser deletes User by Id and returns error if 147 // DeleteUser deletes User by Id and returns error if
148 // the record to be deleted doesn't exist 148 // the record to be deleted doesn't exist
149 -func DeleteUser(id int) (err error) { 149 +func DeleteUser(id int64) (err error) {
150 o := orm.NewOrm() 150 o := orm.NewOrm()
151 v := User{Id: id} 151 v := User{Id: id}
152 // ascertain id exists in the database 152 // ascertain id exists in the database
@@ -158,3 +158,12 @@ func DeleteUser(id int) (err error) { @@ -158,3 +158,12 @@ func DeleteUser(id int) (err error) {
158 } 158 }
159 return 159 return
160 } 160 }
  161 +
  162 +func GetUserByPhone(phone string) (v *User, err error) {
  163 + o := orm.NewOrm()
  164 + v = &User{Phone: phone}
  165 + if err = o.Read(v, "Phone"); err == nil {
  166 + return v, nil
  167 + }
  168 + return nil, err
  169 +}
1 package models 1 package models
2 2
3 import ( 3 import (
4 - "errors"  
5 "fmt" 4 "fmt"
6 - "reflect"  
7 - "strings"  
8 "time" 5 "time"
9 6
10 "github.com/astaxie/beego/orm" 7 "github.com/astaxie/beego/orm"
11 ) 8 )
12 9
13 type UserAuth struct { 10 type UserAuth struct {
14 - Id int `orm:"column(id);auto"` 11 + Id int64 `orm:"column(id);auto"`
15 UserId int64 `orm:"column(user_id)" description:"表user.id "` 12 UserId int64 `orm:"column(user_id)" description:"表user.id "`
16 RefreshToken string `orm:"column(refresh_token);size(64)" description:"refresh token "` 13 RefreshToken string `orm:"column(refresh_token);size(64)" description:"refresh token "`
17 RefreshTokenExp time.Time `orm:"column(refresh_token_exp);type(timestamp)" description:"refresh token 过期时间"` 14 RefreshTokenExp time.Time `orm:"column(refresh_token_exp);type(timestamp)" description:"refresh token 过期时间"`
@@ -19,7 +16,7 @@ type UserAuth struct { @@ -19,7 +16,7 @@ type UserAuth struct {
19 AccessTokenExp time.Time `orm:"column(access_token_exp);type(timestamp)" description:"access token 过期时间"` 16 AccessTokenExp time.Time `orm:"column(access_token_exp);type(timestamp)" description:"access token 过期时间"`
20 AuthCode string `orm:"column(auth_code);size(64)" description:"auth_code"` 17 AuthCode string `orm:"column(auth_code);size(64)" description:"auth_code"`
21 AuthCodeExp time.Time `orm:"column(auth_code_exp);type(timestamp)" description:"auth_code过期时间"` 18 AuthCodeExp time.Time `orm:"column(auth_code_exp);type(timestamp)" description:"auth_code过期时间"`
22 - DeviceType int8 `orm:"column(device_type)" description:"设备类型 0:ios 1:安卓 2:web "` 19 + DeviceType int8 `orm:"column(device_type)" description:"设备类型 1:ios 2:安卓 3:web "`
23 ClientId string `orm:"column(client_id);size(100)" description:"设备识别码 推送标识"` 20 ClientId string `orm:"column(client_id);size(100)" description:"设备识别码 推送标识"`
24 DeviceToken string `orm:"column(device_token);size(100)" description:"设备识别码 推送标识"` 21 DeviceToken string `orm:"column(device_token);size(100)" description:"设备识别码 推送标识"`
25 CreateAt time.Time `orm:"column(create_at);type(timestamp)" description:"创建时间"` 22 CreateAt time.Time `orm:"column(create_at);type(timestamp)" description:"创建时间"`
@@ -34,6 +31,21 @@ func init() { @@ -34,6 +31,21 @@ func init() {
34 orm.RegisterModel(new(UserAuth)) 31 orm.RegisterModel(new(UserAuth))
35 } 32 }
36 33
  34 +//设备类型 1:ios 2:安卓 3:web
  35 +const (
  36 + _ int8 = iota
  37 + DEVICE_TYPE_IOS
  38 + DEVICE_TYPE_ANDROID
  39 + DEVICE_TYPE_WEB
  40 +)
  41 +
  42 +//过期时长设置,单位:秒
  43 +const (
  44 + REFRESH_TIME int64 = 60 * 60 * 4 //4小时
  45 + ACCESS_TIME int64 = 60 * 60 * 2 //2小时
  46 + AUTHCODE_TIME int64 = 60 * 60 * 2 //2小时
  47 +)
  48 +
37 // AddUserAuth insert a new UserAuth into database and returns 49 // AddUserAuth insert a new UserAuth into database and returns
38 // last inserted Id on success. 50 // last inserted Id on success.
39 func AddUserAuth(m *UserAuth) (id int64, err error) { 51 func AddUserAuth(m *UserAuth) (id int64, err error) {
@@ -44,7 +56,7 @@ func AddUserAuth(m *UserAuth) (id int64, err error) { @@ -44,7 +56,7 @@ func AddUserAuth(m *UserAuth) (id int64, err error) {
44 56
45 // GetUserAuthById retrieves UserAuth by Id. Returns error if 57 // GetUserAuthById retrieves UserAuth by Id. Returns error if
46 // Id doesn't exist 58 // Id doesn't exist
47 -func GetUserAuthById(id int) (v *UserAuth, err error) { 59 +func GetUserAuthById(id int64) (v *UserAuth, err error) {
48 o := orm.NewOrm() 60 o := orm.NewOrm()
49 v = &UserAuth{Id: id} 61 v = &UserAuth{Id: id}
50 if err = o.Read(v); err == nil { 62 if err = o.Read(v); err == nil {
@@ -53,84 +65,6 @@ func GetUserAuthById(id int) (v *UserAuth, err error) { @@ -53,84 +65,6 @@ func GetUserAuthById(id int) (v *UserAuth, err error) {
53 return nil, err 65 return nil, err
54 } 66 }
55 67
56 -// GetAllUserAuth retrieves all UserAuth matches certain condition. Returns empty list if  
57 -// no records exist  
58 -func GetAllUserAuth(query map[string]string, fields []string, sortby []string, order []string,  
59 - offset int64, limit int64) (ml []interface{}, err error) {  
60 - o := orm.NewOrm()  
61 - qs := o.QueryTable(new(UserAuth))  
62 - // query k=v  
63 - for k, v := range query {  
64 - // rewrite dot-notation to Object__Attribute  
65 - k = strings.Replace(k, ".", "__", -1)  
66 - if strings.Contains(k, "isnull") {  
67 - qs = qs.Filter(k, (v == "true" || v == "1"))  
68 - } else {  
69 - qs = qs.Filter(k, v)  
70 - }  
71 - }  
72 - // order by:  
73 - var sortFields []string  
74 - if len(sortby) != 0 {  
75 - if len(sortby) == len(order) {  
76 - // 1) for each sort field, there is an associated order  
77 - for i, v := range sortby {  
78 - orderby := ""  
79 - if order[i] == "desc" {  
80 - orderby = "-" + v  
81 - } else if order[i] == "asc" {  
82 - orderby = v  
83 - } else {  
84 - return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")  
85 - }  
86 - sortFields = append(sortFields, orderby)  
87 - }  
88 - qs = qs.OrderBy(sortFields...)  
89 - } else if len(sortby) != len(order) && len(order) == 1 {  
90 - // 2) there is exactly one order, all the sorted fields will be sorted by this order  
91 - for _, v := range sortby {  
92 - orderby := ""  
93 - if order[0] == "desc" {  
94 - orderby = "-" + v  
95 - } else if order[0] == "asc" {  
96 - orderby = v  
97 - } else {  
98 - return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")  
99 - }  
100 - sortFields = append(sortFields, orderby)  
101 - }  
102 - } else if len(sortby) != len(order) && len(order) != 1 {  
103 - return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")  
104 - }  
105 - } else {  
106 - if len(order) != 0 {  
107 - return nil, errors.New("Error: unused 'order' fields")  
108 - }  
109 - }  
110 -  
111 - var l []UserAuth  
112 - qs = qs.OrderBy(sortFields...)  
113 - if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {  
114 - if len(fields) == 0 {  
115 - for _, v := range l {  
116 - ml = append(ml, v)  
117 - }  
118 - } else {  
119 - // trim unused fields  
120 - for _, v := range l {  
121 - m := make(map[string]interface{})  
122 - val := reflect.ValueOf(v)  
123 - for _, fname := range fields {  
124 - m[fname] = val.FieldByName(fname).Interface()  
125 - }  
126 - ml = append(ml, m)  
127 - }  
128 - }  
129 - return ml, nil  
130 - }  
131 - return nil, err  
132 -}  
133 -  
134 // UpdateUserAuth updates UserAuth by Id and returns error if 68 // UpdateUserAuth updates UserAuth by Id and returns error if
135 // the record to be updated doesn't exist 69 // the record to be updated doesn't exist
136 func UpdateUserAuthById(m *UserAuth) (err error) { 70 func UpdateUserAuthById(m *UserAuth) (err error) {
@@ -148,7 +82,7 @@ func UpdateUserAuthById(m *UserAuth) (err error) { @@ -148,7 +82,7 @@ func UpdateUserAuthById(m *UserAuth) (err error) {
148 82
149 // DeleteUserAuth deletes UserAuth by Id and returns error if 83 // DeleteUserAuth deletes UserAuth by Id and returns error if
150 // the record to be deleted doesn't exist 84 // the record to be deleted doesn't exist
151 -func DeleteUserAuth(id int) (err error) { 85 +func DeleteUserAuth(id int64) (err error) {
152 o := orm.NewOrm() 86 o := orm.NewOrm()
153 v := UserAuth{Id: id} 87 v := UserAuth{Id: id}
154 // ascertain id exists in the database 88 // ascertain id exists in the database
@@ -160,3 +94,32 @@ func DeleteUserAuth(id int) (err error) { @@ -160,3 +94,32 @@ func DeleteUserAuth(id int) (err error) {
160 } 94 }
161 return 95 return
162 } 96 }
  97 +
  98 +func ValidateDdevice(deviceType int8) bool {
  99 + switch deviceType {
  100 + case DEVICE_TYPE_IOS:
  101 + return true
  102 + case DEVICE_TYPE_ANDROID:
  103 + return true
  104 + case DEVICE_TYPE_WEB:
  105 + return true
  106 + }
  107 + return false
  108 +}
  109 +
  110 +//ReadUserAuthByDevice 读取或创建
  111 +func ReadUserAuthByDevice(userId int64, deviceType int8) (*UserAuth, error) {
  112 + o := orm.NewOrm()
  113 + if ok := ValidateDdevice(deviceType); !ok {
  114 + return nil, fmt.Errorf("unknown deviceType: %d", deviceType)
  115 + }
  116 + uAuth := &UserAuth{
  117 + UserId: userId,
  118 + DeviceType: deviceType,
  119 + }
  120 + err := o.Read(uAuth, "UserId", "DeviceType")
  121 + if err == nil {
  122 + return uAuth, nil
  123 + }
  124 + return nil, err
  125 +}
@@ -33,6 +33,7 @@ type RequestLogin struct { @@ -33,6 +33,7 @@ type RequestLogin struct {
33 33
34 //ResponseLogin 登录响应 34 //ResponseLogin 登录响应
35 type ResponseLogin struct { 35 type ResponseLogin struct {
  36 + AuthCode string `json:"authcode"`
36 } 37 }
37 38
38 //RequestSwapCompany 切换公司 39 //RequestSwapCompany 切换公司
  1 +package protocol
  2 +
  3 +//RequestPageInfo 分页获取数据
  4 +type RequestPageInfo struct {
  5 + PageIndex int `json:"page_index"`
  6 + PageSize int `json:"page_size`
  7 +}
  8 +
  9 +//ResponsePageInfo 分页信息
  10 +type ResponsePageInfo struct {
  11 + TotalPage int `json:"total_page"`
  12 + CurrentPage int `json:"current_page"`
  13 +}
1 package protocol 1 package protocol
2 2
3 var errmessge ErrorMap = map[string]string{ 3 var errmessge ErrorMap = map[string]string{
4 - "1": "系统异常",  
5 - "101": "clientId或clientSecret无效",  
6 - "113": "签名验证失败", 4 + "00000": "成功",
  5 + "1": "系统异常",
  6 + "101": "clientId或clientSecret无效",
  7 + "113": "签名验证失败",
7 } 8 }
@@ -3,14 +3,10 @@ package protocol @@ -3,14 +3,10 @@ package protocol
3 //RequestRoleAdd 添加角色信息操作入参 3 //RequestRoleAdd 添加角色信息操作入参
4 type RequestRoleAdd struct { 4 type RequestRoleAdd struct {
5 CompanyID int `json:"company,omitempty"` 5 CompanyID int `json:"company,omitempty"`
6 - RoleName string `json:"role_name"` 6 + Name string `json:"name"`
7 Descript string `json:"descript"` 7 Descript string `json:"descript"`
8 } 8 }
9 9
10 -// func (r RequestRoleAdd) Valid() error {  
11 -// return nil  
12 -// }  
13 -  
14 //RequestRoleDelete 删除一个角色数据 10 //RequestRoleDelete 删除一个角色数据
15 type RequestRoleDelete struct { 11 type RequestRoleDelete struct {
16 CompanyID int `json:"company_id"` 12 CompanyID int `json:"company_id"`
@@ -19,8 +15,8 @@ type RequestRoleDelete struct { @@ -19,8 +15,8 @@ type RequestRoleDelete struct {
19 15
20 //RequestRoleEdit 编辑角色信息入参 16 //RequestRoleEdit 编辑角色信息入参
21 type RequestRoleEdit struct { 17 type RequestRoleEdit struct {
22 - RoleID int `json:"role_id"`  
23 - RoleName string `json:"role_name"` 18 + ID int `json:"id"`
  19 + Name string `json:"name"`
24 CompanyID int `json:"company_id"` 20 CompanyID int `json:"company_id"`
25 Descript string `json:"descript"` 21 Descript string `json:"descript"`
26 } 22 }
@@ -33,16 +29,23 @@ type RequestRoleOne struct { @@ -33,16 +29,23 @@ type RequestRoleOne struct {
33 29
34 //ResponseRoleInfo 响应数据 30 //ResponseRoleInfo 响应数据
35 type ResponseRoleInfo struct { 31 type ResponseRoleInfo struct {
36 - RoleID int `json:"role_id"`  
37 - RoleName string `json:"role_name"`  
38 - Descript string `json:"descript"` 32 + ID int `json:"id"`
  33 + Name string `json:"name"`
  34 + Descript string `json:"descript"`
  35 + CreateTime int64 `json:"create_time`
  36 + UpdateTime int64 `json:"update_time"`
39 } 37 }
40 38
41 //RequestRoleList 分页获取角色列表 39 //RequestRoleList 分页获取角色列表
42 type RequestRoleList struct { 40 type RequestRoleList struct {
43 - PageIndex int `json:"page_index"`  
44 - PageSize int `json:"page_size"`  
45 - keyword string `json:"keyword"` // 搜索关键字 41 + RequestPageInfo
  42 + CompanyId int `json:"company_id"`
  43 + Keyword string `json:"keyword"` // 搜索关键字
  44 +}
  45 +
  46 +type ResponseRoleList struct {
  47 + ResponsePageInfo
  48 + Data []ResponseRoleInfo `json:"data`
46 } 49 }
47 50
48 type RequestRolePermission struct { 51 type RequestRolePermission struct {
@@ -5,22 +5,28 @@ import ( @@ -5,22 +5,28 @@ import (
5 "oppmg/common/log" 5 "oppmg/common/log"
6 "oppmg/models" 6 "oppmg/models"
7 "oppmg/protocol" 7 "oppmg/protocol"
  8 + "oppmg/utils"
8 "time" 9 "time"
9 ) 10 )
10 11
11 -func RoleAdd(param protocol.RequestRoleAdd) error { 12 +func RoleAdd(param protocol.RequestRoleAdd) (*protocol.ResponseRoleInfo, error) {
12 role := models.Role{ 13 role := models.Role{
13 CompanyId: param.CompanyID, 14 CompanyId: param.CompanyID,
14 - Name: param.RoleName, 15 + Name: param.Name,
15 CreateAt: time.Now(), 16 CreateAt: time.Now(),
16 Descript: param.Descript, 17 Descript: param.Descript,
17 } 18 }
18 - _, err := models.AddRole(&role) 19 + roleid, err := models.AddRole(&role)
19 if err != nil { 20 if err != nil {
20 log.Error("AddRole err:%s", err) 21 log.Error("AddRole err:%s", err)
21 - return protocol.NewErrWithMessage("1", err) 22 + return nil, protocol.NewErrWithMessage("1", err)
22 } 23 }
23 - return nil 24 + r := &protocol.ResponseRoleInfo{
  25 + ID: int(roleid),
  26 + Name: role.Name,
  27 + Descript: role.Descript,
  28 + }
  29 + return r, nil
24 } 30 }
25 31
26 func RoleDelete(param protocol.RequestRoleDelete) error { 32 func RoleDelete(param protocol.RequestRoleDelete) error {
@@ -44,40 +50,69 @@ func RoleDelete(param protocol.RequestRoleDelete) error { @@ -44,40 +50,69 @@ func RoleDelete(param protocol.RequestRoleDelete) error {
44 return nil 50 return nil
45 } 51 }
46 52
47 -func RoleEdit(param protocol.RequestRoleEdit) error { 53 +func RoleEdit(param protocol.RequestRoleEdit) (*protocol.ResponseRoleInfo, error) {
48 var ( 54 var (
49 role *models.Role 55 role *models.Role
50 err error 56 err error
51 ) 57 )
52 - role, err = models.GetRoleById(param.RoleID) 58 + role, err = models.GetRoleById(param.ID)
53 if err != nil { 59 if err != nil {
54 e := fmt.Errorf("GetRoleById err:%s", err) 60 e := fmt.Errorf("GetRoleById err:%s", err)
55 log.Error(e.Error()) 61 log.Error(e.Error())
56 - return protocol.NewErrWithMessage("1", e) 62 + return nil, protocol.NewErrWithMessage("1", e)
57 } 63 }
58 if role.CompanyId != param.CompanyID { 64 if role.CompanyId != param.CompanyID {
59 e := fmt.Errorf("role.CompanyId(%d) != param.CompanyID(%d)", role.CompanyId, param.CompanyID) 65 e := fmt.Errorf("role.CompanyId(%d) != param.CompanyID(%d)", role.CompanyId, param.CompanyID)
60 log.Error(e.Error()) 66 log.Error(e.Error())
61 - return protocol.NewErrWithMessage("1", e) 67 + return nil, protocol.NewErrWithMessage("1", e)
62 } 68 }
63 role.Descript = param.Descript 69 role.Descript = param.Descript
64 - role.Name = param.RoleName 70 + role.Name = param.Name
65 if err = models.UpdateRoleById(role); err != nil { 71 if err = models.UpdateRoleById(role); err != nil {
66 e := fmt.Errorf("UpdateRoleById err:%s", err) 72 e := fmt.Errorf("UpdateRoleById err:%s", err)
67 log.Error(e.Error()) 73 log.Error(e.Error())
68 - return protocol.NewErrWithMessage("1", e) 74 + return nil, protocol.NewErrWithMessage("1", e)
69 } 75 }
70 -  
71 - return nil 76 + r := &protocol.ResponseRoleInfo{
  77 + ID: param.ID,
  78 + Name: param.Name,
  79 + Descript: param.Descript,
  80 + }
  81 + return r, nil
72 } 82 }
73 83
74 -func RoleGetOne(param protocol.RequestRoleOne) error { 84 +func RoleGetOne(param protocol.RequestRoleOne) (*protocol.ResponseRoleInfo, error) {
75 85
76 - return nil 86 + return nil, nil
77 } 87 }
78 88
79 -func RoleGetByPage(param protocol.RequestRoleList) error {  
80 - return nil 89 +func RoleGetByPage(param protocol.RequestRoleList) (*protocol.ResponseRoleList, error) {
  90 + var (
  91 + where string = `a.company_id=? and a.delete_at=0`
  92 + dataSql string = `SELECT a.id,a.name,a.descript,a.create_at,a.update_at
  93 + FROM role AS a
  94 + where ` + where
  95 + countSql string = `SELECT COUNT(*) FROM role as a where ` + where
  96 + )
  97 + var (
  98 + roleList []protocol.ResponseRoleInfo
  99 + pageinfo protocol.ResponsePageInfo
  100 + err error
  101 + )
  102 + pagequery := utils.NewQueryDataByPage(countSql, dataSql)
  103 + pagequery.LimitPage(param.PageIndex, param.PageSize)
  104 + pagequery.AddParam(param.CompanyId)
  105 + pageinfo, err = pagequery.Query(&roleList)
  106 + if err != nil {
  107 + e := fmt.Errorf("SQL EXECUTE err:%s", err)
  108 + log.Error(e.Error())
  109 + return nil, protocol.NewErrWithMessage("1", e)
  110 + }
  111 + r := &protocol.ResponseRoleList{
  112 + ResponsePageInfo: pageinfo,
  113 + Data: roleList,
  114 + }
  115 + return r, nil
81 } 116 }
82 117
83 func RoleHasPermission() error { 118 func RoleHasPermission() error {
@@ -2,12 +2,18 @@ package serveauth @@ -2,12 +2,18 @@ package serveauth
2 2
3 import ( 3 import (
4 "crypto/sha1" 4 "crypto/sha1"
  5 + "encoding/hex"
5 "fmt" 6 "fmt"
6 "io" 7 "io"
7 "oppmg/common/config" 8 "oppmg/common/config"
8 "oppmg/common/log" 9 "oppmg/common/log"
  10 + "oppmg/models"
9 "oppmg/protocol" 11 "oppmg/protocol"
  12 + "oppmg/utils"
10 "strings" 13 "strings"
  14 + "time"
  15 +
  16 + "github.com/astaxie/beego/orm"
11 ) 17 )
12 18
13 //GetAccessToken 获取accessToken 19 //GetAccessToken 获取accessToken
@@ -21,11 +27,11 @@ func GetAccessToken(param protocol.RequestCheckSmsCode) (*protocol.DataUserInfo, @@ -21,11 +27,11 @@ func GetAccessToken(param protocol.RequestCheckSmsCode) (*protocol.DataUserInfo,
21 27
22 //ValidatePassword ... 28 //ValidatePassword ...
23 //from:待校验的密码;to:比对用的密文 29 //from:待校验的密码;to:比对用的密文
24 -func ValidatePassword(from, to string) bool { 30 +func validatePassword(from, to string) bool {
25 //密码加密方式sha1 31 //密码加密方式sha1
26 h := sha1.New() 32 h := sha1.New()
27 io.WriteString(h, from) 33 io.WriteString(h, from)
28 - str := fmt.Sprintf("%x", h.Sum(nil)) 34 + str := hex.EncodeToString(h.Sum(nil))
29 if strings.Compare(str, to) == 0 { 35 if strings.Compare(str, to) == 0 {
30 return true 36 return true
31 } 37 }
@@ -33,7 +39,59 @@ func ValidatePassword(from, to string) bool { @@ -33,7 +39,59 @@ func ValidatePassword(from, to string) bool {
33 } 39 }
34 40
35 //LoginAuth 登录认证 41 //LoginAuth 登录认证
36 -func LoginAuth(account, password string) error { 42 +func LoginAuthByPassword(account, password string) error {
  43 + var (
  44 + user *models.User
  45 + uAuth *models.UserAuth
  46 + err error
  47 + )
  48 + user, err = models.GetUserByPhone(account)
  49 + if err != nil {
  50 + log.Error(err.Error())
  51 + return protocol.NewErrWithMessage("1", err)
  52 + }
  53 + if ok := validatePassword(password, user.Passwd); !ok {
  54 + return protocol.NewErrWithMessage("1", err)
  55 + }
  56 +
  57 + uAuth, err = models.ReadUserAuthByDevice(user.Id, models.DEVICE_TYPE_WEB)
  58 + if err != nil && err != orm.ErrNoRows {
  59 + e := fmt.Errorf("ReadUserAuthByDevice(%d,%d) err:%s", user.Id, models.DEVICE_TYPE_WEB, err)
  60 + log.Error(e.Error())
  61 + return protocol.NewErrWithMessage("1", e)
  62 + }
  63 + var (
  64 + authcode string
  65 + authcodeExp time.Time
  66 + )
  67 + authcode = utils.GenerateIDByUUID()
  68 + authcodeExp = time.Now().Add(time.Duration(models.AUTHCODE_TIME) * time.Second)
  69 + if err == orm.ErrNoRows {
  70 + uAuth := &models.UserAuth{
  71 + UserId: user.Id,
  72 + AuthCode: authcode,
  73 + AuthCodeExp: authcodeExp,
  74 + CreateAt: time.Now(),
  75 + }
  76 + _, err = models.AddUserAuth(uAuth)
  77 + if err != nil {
  78 + e := fmt.Errorf("AddUserAuth err:%s", err)
  79 + log.Error(e.Error())
  80 + return protocol.NewErrWithMessage("1", e)
  81 + }
  82 + }
  83 + if err == nil {
  84 + uAuth.AuthCode = authcode
  85 + uAuth.AuthCodeExp = authcodeExp
  86 + uAuth.UpdateAt = time.Now()
  87 + err = models.UpdateUserAuthById(uAuth)
  88 + if err != nil {
  89 + e := fmt.Errorf("UpdateUserAuthById err:%s", err)
  90 + log.Error(e.Error())
  91 + return protocol.NewErrWithMessage("1", e)
  92 + }
  93 + }
  94 +
37 return nil 95 return nil
38 } 96 }
39 97
@@ -41,3 +99,10 @@ func LoginAuth(account, password string) error { @@ -41,3 +99,10 @@ func LoginAuth(account, password string) error {
41 func RefreshAccessToken(account string, token string) error { 99 func RefreshAccessToken(account string, token string) error {
42 return nil 100 return nil
43 } 101 }
  102 +
  103 +// func buildNewUserAuth(uid int64,) *models.UserAuth {
  104 +// m:=&models.UserAuth{
  105 +// User
  106 +// }
  107 +// return nil
  108 +// }
1 package utils 1 package utils
2 2
3 import ( 3 import (
  4 + "encoding/hex"
  5 +
  6 + uuid "github.com/satori/go.uuid"
4 "github.com/sony/sonyflake" 7 "github.com/sony/sonyflake"
5 ) 8 )
6 9
7 var sf = sonyflake.NewSonyflake(sonyflake.Settings{}) 10 var sf = sonyflake.NewSonyflake(sonyflake.Settings{})
8 11
9 -func GetUniqueId() int64 { 12 +func GenerateIDBySonyflake() int64 {
10 num, _ := sf.NextID() 13 num, _ := sf.NextID()
11 return int64(num) 14 return int64(num)
12 } 15 }
  16 +
  17 +func GenerateIDByUUID() string {
  18 + ubyte := uuid.NewV4().Bytes()
  19 + s := hex.EncodeToString(ubyte)
  20 + return s
  21 +}
1 package utils 1 package utils
2 2
3 import ( 3 import (
  4 + "fmt"
4 "time" 5 "time"
5 6
6 jwt "github.com/dgrijalva/jwt-go" 7 jwt "github.com/dgrijalva/jwt-go"
@@ -13,7 +14,8 @@ var ( @@ -13,7 +14,8 @@ var (
13 //MyToken ... 14 //MyToken ...
14 type MyToken struct { 15 type MyToken struct {
15 jwt.StandardClaims 16 jwt.StandardClaims
16 - ID int `json:"id"` 17 + UID int `json:"uid"`
  18 + CompanyID int `json:"company_id"`
17 } 19 }
18 20
19 //CreateJWTToken ... 21 //CreateJWTToken ...
@@ -26,7 +28,7 @@ func CreateJWTToken(id int) (string, error) { @@ -26,7 +28,7 @@ func CreateJWTToken(id int) (string, error) {
26 ExpiresAt: 60 * 60 * 2, //过期时间 28 ExpiresAt: 60 * 60 * 2, //过期时间
27 Issuer: "test_a", 29 Issuer: "test_a",
28 }, 30 },
29 - ID: id, 31 + UID: id,
30 } 32 }
31 33
32 token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) 34 token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
@@ -49,5 +51,5 @@ func ValidJWTToken(tokenString string) (*MyToken, error) { @@ -49,5 +51,5 @@ func ValidJWTToken(tokenString string) (*MyToken, error) {
49 return claims, nil 51 return claims, nil
50 } 52 }
51 // 验证失败 53 // 验证失败
52 - return nil, err 54 + return nil, fmt.Errorf("token Valid fail")
53 } 55 }
  1 +package utils
  2 +
  3 +import (
  4 + "fmt"
  5 + "oppmg/common/log"
  6 + "oppmg/protocol"
  7 +
  8 + "github.com/astaxie/beego/orm"
  9 +)
  10 +
  11 +//PrintLogSql 打印sql语句
  12 +func PrintLogSql(sql string, param ...interface{}) {
  13 + format := `SQL EXCUTE:[%s]-%s`
  14 + log.Debug(format, sql, fmt.Sprint(param...))
  15 +}
  16 +
  17 +//ExcuteSql 执行原生sql语句
  18 +func ExcuteSql(result interface{}, sqlstr string, param ...interface{}) error {
  19 + PrintLogSql(sqlstr, param...)
  20 + var err error
  21 + o := orm.NewOrm()
  22 + err = ExcuteSqlWithOrmer(o, result, sqlstr, param)
  23 + return err
  24 +}
  25 +
  26 +//ExcuteSqlWithOrmer 执行原生sql语句
  27 +func ExcuteSqlWithOrmer(o orm.Ormer, result interface{}, sqlstr string, param ...interface{}) error {
  28 + PrintLogSql(sqlstr, param...)
  29 + var err error
  30 + err = o.Raw(sqlstr, param).QueryRow(result)
  31 + if err != nil {
  32 + return fmt.Errorf("SQL EXCUTE err:%s", err)
  33 + }
  34 + return nil
  35 +}
  36 +
  37 +type QueryDataByPage struct {
  38 + CountSql string
  39 + DataSql string
  40 + Param []interface{}
  41 + offset int
  42 + num int
  43 +}
  44 +
  45 +func NewQueryDataByPage(countsql, datasql string) *QueryDataByPage {
  46 + return &QueryDataByPage{
  47 + CountSql: countsql,
  48 + DataSql: datasql,
  49 + }
  50 +}
  51 +
  52 +func (q *QueryDataByPage) AddParam(param ...interface{}) {
  53 + q.Param = param
  54 +}
  55 +
  56 +func (q *QueryDataByPage) LimitPage(offset, num int) {
  57 + q.offset = offset
  58 + q.num = num
  59 +}
  60 +
  61 +func (q *QueryDataByPage) Query(result interface{}) (pageinfo protocol.ResponsePageInfo, err error) {
  62 + pagebegin := (q.offset - 1) * q.num
  63 + if pagebegin < 0 {
  64 + pagebegin = 0
  65 + }
  66 + var (
  67 + total int
  68 + )
  69 + o := orm.NewOrm()
  70 + err = ExcuteSqlWithOrmer(o, &total, q.CountSql, q.Param...)
  71 + if err != nil {
  72 + return
  73 + }
  74 + if total == 0 {
  75 + return protocol.ResponsePageInfo{CurrentPage: q.offset, TotalPage: total}, nil
  76 + }
  77 + q.DataSql = fmt.Sprintf("%s limit %d,%d", q.DataSql, pagebegin, q.num)
  78 + err = ExcuteSqlWithOrmer(o, result, q.DataSql, q.Param...)
  79 + if err != nil {
  80 + return
  81 + }
  82 + return protocol.ResponsePageInfo{CurrentPage: q.offset, TotalPage: total}, nil
  83 +}