forked from muka/peerjs-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
90 lines (70 loc) · 1.78 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
package server
import (
"errors"
"net/http"
"github.com/gorilla/mux"
"github.com/sirupsen/logrus"
)
var errInvalidKey = errors.New(ErrorInvalidKey)
var errUnauthorized = errors.New(http.StatusText(http.StatusUnauthorized))
// NewAuth init a new Auth middleware
func NewAuth(realm IRealm, opts Options) *Auth {
a := new(Auth)
a.opts = opts
a.realm = realm
a.log = createLogger("auth", opts)
return a
}
// Auth handles request authentication
type Auth struct {
opts Options
log *logrus.Entry
realm IRealm
}
//checkRequest check if the input is valid
func (a *Auth) checkRequest(key, id, token string) error {
if key != a.opts.Key {
return errInvalidKey
}
if id == "" {
return errUnauthorized
}
client := a.realm.GetClientByID(id)
if client == nil {
return errUnauthorized
}
if len(client.GetToken()) > 0 && client.GetToken() != token {
return errUnauthorized
}
return nil
}
//WSHandler return a websocket handler middleware
func (a *Auth) WSHandler(handler http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// keys := r.URL.Query()
// key := keys.Get("key")
// id := keys.Get("id")
// token := keys.Get("token")
// err := a.checkRequest(key, id, token)
// if err != nil {
// http.Error(w, err.Error(), http.StatusUnauthorized)
// return
// }
handler(w, r)
})
}
//HTTPHandler return an HTTP handler middleware
func (a *Auth) HTTPHandler(handler http.HandlerFunc) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
key := params["key"]
id := params["id"]
token := params["token"]
err := a.checkRequest(key, id, token)
if err != nil {
http.Error(w, err.Error(), http.StatusUnauthorized)
return
}
handler(w, r)
})
}