/
app.go
107 lines (87 loc) · 2.41 KB
/
app.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package rbac
import (
"encoding/binary"
"fmt"
"net/http"
"dearcode.net/crab/http/server"
"dearcode.net/crab/log"
"dearcode.net/crab/util/aes"
"dearcode.net/doodle/pkg/rbac/config"
"dearcode.net/doodle/pkg/rbac/meta"
"dearcode.net/doodle/pkg/util"
)
type rbacAPP struct {
}
// GET app查询接口.
func (a *rbacAPP) GET(w http.ResponseWriter, r *http.Request) {
vars := struct {
AppID int64 `json:"app_id"`
Email string `json:"email"`
Sort string `json:"sort"`
Order string `json:"order"`
Offset int `json:"offset"`
Limit int `json:"limit"`
}{}
if err := util.DecodeRequestValue(r, &vars); err != nil {
server.SendResponse(w, http.StatusBadRequest, err.Error())
return
}
where := fmt.Sprintf("id=%d", vars.AppID)
if vars.Email != "" {
where += fmt.Sprintf(" and email='%s'", vars.Email)
}
var as []meta.App
total, err := query("app", where, vars.Sort, vars.Order, vars.Offset, vars.Limit, &as)
if err != nil {
server.SendResponse(w, http.StatusBadRequest, err.Error())
log.Debugf("query error:%s", err.Error())
return
}
if total == 0 || len(as) == 0 {
server.SendResponse(w, http.StatusNotFound, "not found")
log.Debugf("App not found, vars:%#v", vars)
return
}
log.Debugf("query App id:%d, Apps:%#v", vars.AppID, as)
server.SendResponseData(w, as)
}
// POST 添加应用
func (a *rbacAPP) POST(w http.ResponseWriter, r *http.Request) {
vars := struct {
Name string `json:"name"`
Email string `json:"email"`
Comments string `json:"comments"`
}{}
if err := util.DecodeRequestValue(r, &vars); err != nil {
server.SendResponse(w, http.StatusInternalServerError, err.Error())
return
}
log.Debugf("vars:%+v", vars)
id, token, err := AppAdd(vars.Name, vars.Email, vars.Comments)
if err != nil {
log.Errorf("AppAdd vars:%v, err:%v", vars, err)
server.SendResponse(w, http.StatusInternalServerError, err.Error())
return
}
log.Debugf("add app:%v, id:%d, token:%s", vars, id, token)
server.SendResponseData(w, token)
}
// AppAdd 添加app.
func AppAdd(name, email, comments string) (int64, string, error) {
app := meta.App{
Name: name,
Email: email,
Comments: comments,
}
id, err := add("app", app)
if err != nil {
return 0, "", err
}
buf := make([]byte, 8)
binary.PutVarint(buf, id)
token, err := aes.Encrypt(string(buf), config.RBAC.Server.Key)
if err != nil {
return 0, "", err
}
return id, token, updateAppToken(id, token)
}