-
Notifications
You must be signed in to change notification settings - Fork 3
/
access.go
61 lines (55 loc) · 1.6 KB
/
access.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
// Copyright (c) 2013 Jason McVetta. This is Free Software, released under the
// terms of the GPL v3. See http://www.gnu.org/copyleft/gpl.html for details.
// Resist intellectual serfdom - the ownership of ideas is akin to slavery.
package o2pro
import "log"
/*
ACCESSING PROTECTED RESOURCES
http://tools.ietf.org/html/rfc6749#section-7
*/
import "net/http"
// RequireScope wraps a HandlerFunc, restricting access to authenticated users
// with the specified scope.
func (p *Provider) RequireScope(fn http.HandlerFunc, scope string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
token, err := bearerToken(r)
if err != nil { // No token found
log.Println(err)
http.Error(w, "", http.StatusUnauthorized)
return
}
a, err := p.authz(token)
if err != nil {
log.Println(err)
http.Error(w, "", http.StatusUnauthorized)
return
}
_, ok := a.ScopesMap()[scope]
if !ok {
log.Printf("Need scope '%v' but only authorized for '%v'", scope, a.ScopeString())
http.Error(w, "", http.StatusUnauthorized)
return
}
fn(w, r) // Call the wrapped function
return
}
}
// RequireAuthc wraps a HandlerFunc, restricting access to authenticated users.
func (p *Provider) RequireAuthc(fn http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
token, err := bearerToken(r)
if err != nil { // No token found
log.Println(err)
http.Error(w, "", http.StatusUnauthorized)
return
}
_, err = p.authz(token)
if err != nil {
log.Println(err)
http.Error(w, "", http.StatusUnauthorized)
return
}
fn(w, r)
return
}
}