-
Notifications
You must be signed in to change notification settings - Fork 7
/
auth.go
242 lines (205 loc) · 5.23 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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
// Copyright 2014 Tim Shannon. All rights reserved.
// Use of this source code is governed by the MIT license
// that can be found in the LICENSE file.
package main
import (
"encoding/base64"
"errors"
"net/http"
"strings"
"bitbucket.org/tshannon/freehold/fail"
"bitbucket.org/tshannon/freehold/log"
"bitbucket.org/tshannon/freehold/permission"
"bitbucket.org/tshannon/freehold/ratelimit"
"bitbucket.org/tshannon/freehold/resource"
"bitbucket.org/tshannon/freehold/session"
"bitbucket.org/tshannon/freehold/setting"
"bitbucket.org/tshannon/freehold/token"
"bitbucket.org/tshannon/freehold/user"
)
const (
authTypeNone = "none"
authTypeBasic = "basic"
authTypeSession = "session"
authTypeToken = "token"
)
const (
publicWriteLimitType = "publicWriteLimit"
authRateLimitType = "authentication"
)
// ErrNoWritePermissions is the error returned when the user does not have permissions
// to write to a given resource
var ErrNoWritePermission = errors.New("You do not have permission to write to this resource.")
// Auth contains the type and identity of a user in Freehold
// if user == nil, then auth is public access
type Auth struct {
AuthType string `json:"type"`
Username string `json:"user,omitempty"`
*user.User
*token.Token
*session.Session `json:"-"`
}
// authenticate authenticates an http request in one of 3 ways
// Checks for basic http authentication where the password is either the user's password
// or a valid security token, or the user has an valid cookie based session.
func authenticate(w http.ResponseWriter, r *http.Request) (*Auth, error) {
blnSuccess := false
defer func() {
if !blnSuccess {
// if failed login attempt,
err := ratelimit.InsertAttempt(ipAddress(r), authRateLimitType, setting.Float("LogonAttemptRateLimit"))
if err != nil {
log.Error(err)
}
}
}()
err := ratelimit.OverLimit(ipAddress(r), authRateLimitType, setting.Float("LogonAttemptRateLimit"))
if err != nil {
return nil, err
}
a := &Auth{
AuthType: authTypeNone,
}
headerInfo := r.Header.Get("Authorization")
if headerInfo != "" {
authInfo := strings.TrimPrefix(headerInfo, "Basic ")
if len(authInfo) == len(headerInfo) {
return nil, fail.New("Error, malformed basic auth header.", nil)
}
userPass, err := base64.StdEncoding.DecodeString(authInfo)
if err != nil {
log.Error(errors.New("Error decoding base64 auth header: " + err.Error()))
return nil, fail.New("Error, malformed basic auth header.", nil)
}
split := strings.SplitN(string(userPass), ":", 2)
if len(split) != 2 {
return nil, fail.New("Error, malformed basic auth header.", nil)
}
u := split[0]
pass := split[1]
if u == "" {
//public access
blnSuccess = true
return a, a.attemptWrite(r)
}
user, err := user.Get(u)
if err != nil {
return nil, err
}
t, err := token.Login(user, pass)
if err != nil {
return nil, err
}
if t != nil {
a.AuthType = authTypeToken
if t.IsExpired() {
return nil, fail.New("Your token has expired", nil)
}
a.Token = t
a.User = t.User()
if a.User != nil {
a.Username = t.User().Username()
}
blnSuccess = true
return a, nil
}
a.AuthType = authTypeBasic
err = user.Login(pass)
if err != nil {
return a, err
}
a.User = user
a.Username = user.Username()
blnSuccess = true
return a, nil
}
//Check for session cookie
ses, err := session.Get(r)
if err != nil {
return nil, err
}
if ses == nil || ses.IsExpired() {
//No valid session cookie
// public access
blnSuccess = true
return a, a.attemptWrite(r)
}
// Check for CSRF token
err = ses.HandleCSRF(w, r)
if err != nil {
return nil, err
}
a.AuthType = authTypeSession
a.User = ses.User()
a.Username = ses.User().Username()
a.Session = ses
blnSuccess = true
return a, nil
}
func (a *Auth) tryRead(res permission.Permitter) error {
var prm *permission.Permission
var err error
if a.AuthType == authTypeToken {
prm, err = a.Token.GetPermission(res)
} else {
prm, err = res.Permission()
}
if err != nil {
return err
}
if !prm.CanRead(a.User) {
switch res.(type) {
case *resource.File:
return four04Fail(res.(*resource.File).URL())
default:
return four04Fail("")
}
}
return nil
}
func (a *Auth) tryWrite(res permission.Permitter) error {
var prm *permission.Permission
var err error
if a.AuthType == authTypeToken {
prm, err = a.Token.GetPermission(res)
} else {
prm, err = res.Permission()
}
if err != nil {
return err
}
if !prm.CanWrite(a.User) {
switch res.(type) {
case *resource.File:
if prm.CanRead(a.User) {
return fail.NewFromErr(ErrNoWritePermission, res.(*resource.File).URL())
}
return four04Fail(res.(*resource.File).URL())
default:
if prm.CanRead(a.User) {
return fail.NewFromErr(ErrNoWritePermission, nil)
}
return four04Fail("")
}
}
return nil
}
func (a *Auth) attemptWrite(r *http.Request) error {
if r.Method == "GET" {
return nil
}
if a.User != nil {
return nil
}
return ratelimit.AttemptRequest(ipAddress(r), publicWriteLimitType, setting.Float("PublicWriteRateLimit"))
}
func authGet(w http.ResponseWriter, r *http.Request) {
auth, err := authenticate(w, r)
if errHandled(err, w, auth) {
return
}
respondJsend(w, &JSend{
Status: statusSuccess,
Data: auth,
})
}