-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth.go
185 lines (151 loc) · 4.26 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
package auth
import (
"encoding/json"
"errors"
"net/http"
"github.com/gorilla/context"
"github.com/dahernan/auth/jwt"
"github.com/dahernan/auth/store"
)
const (
TokenKey = "token"
UserKey = "user"
)
type AuthRoute struct {
userStore store.UserRepository
options jwt.Options
}
func NewAuthRoute(store store.UserRepository, opt jwt.Options) *AuthRoute {
return &AuthRoute{
userStore: store,
options: opt,
}
}
func (a *AuthRoute) Login(w http.ResponseWriter, req *http.Request) {
var authForm map[string]string
err := RequestToJsonObject(req, &authForm)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
email := authForm["email"]
pass := authForm["password"]
userId, err := a.userStore.Login(email, pass)
if err != nil {
http.Error(w, "Username or Password Invalid", http.StatusUnauthorized)
return
}
token, err := jwt.GenerateJWTToken(userId, a.options)
if err != nil {
http.Error(w, "Error while Signing Token :S", http.StatusInternalServerError)
return
}
jtoken, err := json.Marshal(map[string]string{"token": token})
if err != nil {
http.Error(w, "Error marshalling the token to json", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(jtoken)
}
func (a *AuthRoute) RefreshToken(w http.ResponseWriter, req *http.Request) {
userId, _, err := a.authenticate(w, req)
if err != nil {
http.Error(w, err.Error(), http.StatusUnauthorized)
return
}
token, err := jwt.GenerateJWTToken(userId, a.options)
if err != nil {
http.Error(w, "Error while Signing Token :S", http.StatusInternalServerError)
return
}
jtoken, err := json.Marshal(map[string]string{"token": token})
if err != nil {
http.Error(w, "Error marshalling the token to json", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(jtoken)
}
func (a *AuthRoute) Signin(w http.ResponseWriter, req *http.Request) {
var authForm map[string]string
err := RequestToJsonObject(req, &authForm)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
email := authForm["email"]
pass := authForm["password"]
userId, err := a.userStore.Signin(email, pass)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
juser, err := json.Marshal(map[string]string{"id": userId})
if err != nil {
http.Error(w, "Error marshalling the user to json", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
w.Header().Set("Content-Type", "application/json")
w.Write(juser)
}
func (a *AuthRoute) authenticate(w http.ResponseWriter, r *http.Request) (string, string, error) {
auth := r.Header.Get("Authorization")
if auth == "" {
return "", "", errors.New("Error no token is provided")
}
userId, token, err := jwt.ValidateToken(r, a.options.PublicKey)
if err != nil {
return "", "", err
}
return userId, token, nil
}
// Get User from the context
func GetUserId(r *http.Request) string {
return context.Get(r, UserKey).(string)
}
// Get Token from the context
func GetToken(r *http.Request) string {
return context.Get(r, TokenKey).(string)
}
// Auth middleware for negroni
func (a *AuthRoute) AuthMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
userId, token, err := a.authenticate(w, r)
if err != nil {
http.Error(w, err.Error(), http.StatusUnauthorized)
return
}
context.Set(r, TokenKey, token)
context.Set(r, UserKey, userId)
next(w, r)
context.Clear(r)
}
// Auth Handler for net/http
func (a *AuthRoute) AuthHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
userId, token, err := a.authenticate(w, r)
if err != nil {
http.Error(w, err.Error(), http.StatusUnauthorized)
return
}
context.Set(r, TokenKey, token)
context.Set(r, UserKey, userId)
h.ServeHTTP(w, r)
context.Clear(r)
})
}
func (a *AuthRoute) AuthHandlerFunc(next http.HandlerFunc) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
a.AuthMiddleware(w, r, next)
})
}
func RequestToJsonObject(req *http.Request, jsonDoc interface{}) error {
defer req.Body.Close()
decoder := json.NewDecoder(req.Body)
err := decoder.Decode(jsonDoc)
if err != nil {
return err
}
return nil
}