-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth.go
192 lines (161 loc) · 4.94 KB
/
auth.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
package auth
import (
"code.google.com/p/go.net/context"
gorillactx "github.com/gorilla/context"
"github.com/gorilla/mux"
"github.com/kidstuff/auth/authmodel"
"github.com/kidstuff/conf"
"net/http"
"strings"
"text/template"
"time"
)
var (
// HANDLER_REGISTER should be "overided" by the "manager". Implement of this function
// must use the "or" logic for the conditions.
HANDLER_REGISTER func(fn HandleFunc, owner bool, pri []string) http.Handler
// DEFAULT_NOTIFICATOR should be "overided" by the "manager".
DEFAULT_NOTIFICATOR Notificator
// DEFAULT_LOGGER should be "overided" by the "manager".
DEFAULT_LOGGER Logger
OnlineThreshold = time.Hour
HandleTimeout = time.Minute * 2
)
type HandleFunc func(*AuthContext, http.ResponseWriter, *http.Request) (int, error)
type ctxWrapper struct {
context.Context
req *http.Request
}
// Value returns Gorilla's context package's value for this Context's request
// and key. It delegates to the parent Context if there is no such value.
func (ctx *ctxWrapper) Value(key interface{}) interface{} {
if val, ok := gorillactx.GetOk(ctx.req, key); ok {
return val
}
return ctx.Context.Value(key)
}
type ctxKey int
const (
userTokenKey ctxKey = iota
userIdKey
)
type AuthContext struct {
ctxWrapper
Auth authmodel.Manager
Settings conf.Configurator
Notifications Notificator
Logs Logger
currentUser *authmodel.User
}
func (ctx *AuthContext) saveToken(token string) {
ctx.Context = context.WithValue(ctx.Context, userTokenKey, token)
}
func (ctx *AuthContext) saveId(id string) {
ctx.Context = context.WithValue(ctx.Context, userIdKey, id)
}
// ValidCurrentUser validate user privilege and cacuate user total privilege base on groups.
// In some case a non-nil *authmodel.User object still return with an error.
func (ctx *AuthContext) ValidCurrentUser(owner bool, pri []string) (*authmodel.User, error) {
if ctx.currentUser == nil {
//try to query current user
token, ok := ctx.Value(userTokenKey).(string)
if !ok || len(token) == 0 {
return nil, ErrForbidden
}
var err error
ctx.currentUser, err = ctx.Auth.GetUser(token)
if err != nil {
return nil, err
}
// calculate user privilege base on user's privilege and group's privilege
mPri := make(map[string]bool)
for _, p := range ctx.currentUser.Privileges {
mPri[p] = true
}
aid := make([]string, 0, len(ctx.currentUser.Groups))
for _, v := range ctx.currentUser.Groups {
aid = append(aid, *v.Id)
}
groups, err := ctx.Auth.FindSomeGroup(aid, nil)
if err == nil {
for _, v := range groups {
for _, p := range v.Privileges {
mPri[p] = true
}
}
} else {
ctx.Logs.Errorf("cannot load user groups to get group privilege")
}
aPri := make([]string, 0, len(mPri))
for p := range mPri {
aPri = append(aPri, p)
}
ctx.currentUser.Privileges = aPri
}
err := validCurrentUser(ctx, ctx.currentUser, owner, pri)
return ctx.currentUser, err
}
func validPri(userPri, requirePri []string) bool {
if len(requirePri) > 0 {
for _, up := range userPri {
for _, rp := range requirePri {
if up == rp {
return true
}
}
}
return false
}
return true
}
func validCurrentUser(authCtx *AuthContext, user *authmodel.User, owner bool, privilege []string) error {
// check for the current user
if owner {
sid, ok := authCtx.Context.Value(userIdKey).(string)
if !ok || len(sid) == 0 || sid != *user.Id {
if len(privilege) > 0 && validPri(user.Privileges, privilege) {
return nil
}
return ErrForbidden
}
}
if !validPri(user.Privileges, privilege) {
return ErrForbidden
}
return nil
}
type Condition struct {
RequiredPri []string
Owner bool
}
// BasicMngrHandler can be use in "manager" ServeHTTP after initital required interface like
// authmodel.UserManager, authmodel.GroupManager, conf.Configurator...etc
func BasicMngrHandler(authCtx *AuthContext, rw http.ResponseWriter, req *http.Request, cond *Condition, fn HandleFunc) {
var cancel context.CancelFunc
authCtx.Context, cancel = context.WithTimeout(context.Background(), HandleTimeout)
defer cancel()
authCtx.req = req
token := strings.TrimPrefix(req.Header.Get("Authorization"), "Bearer ")
authCtx.saveToken(token)
authCtx.saveId(mux.Vars(req)["user_id"])
authCtx.Notifications = DEFAULT_NOTIFICATOR
authCtx.Logs = DEFAULT_LOGGER
rw.Header().Set("Content-Type", "application/json; charset=utf-8")
if cond.RequiredPri != nil || cond.Owner {
_, err := authCtx.ValidCurrentUser(cond.Owner, cond.RequiredPri)
if err != nil {
JSONError(rw, err.Error(), http.StatusForbidden)
return
}
}
status, err := fn(authCtx, rw, req)
if err != nil {
authCtx.Logs.Errorf("HTTP %d: %q", status, err)
JSONError(rw, err.Error(), status)
}
}
// JSONError is a helper function to write json error message to http.ResponseWriter
func JSONError(rw http.ResponseWriter, message string, code int) {
rw.WriteHeader(code)
rw.Write([]byte(`{"error":"` + template.JSEscapeString(message) + `"}`))
}