-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth_provider_api.go
302 lines (257 loc) · 8.72 KB
/
auth_provider_api.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
package authless
import (
"crypto/sha1"
"encoding/json"
"mime"
"net/http"
"github.com/golang-jwt/jwt"
"github.com/n10ty/authless/storage"
"github.com/n10ty/authless/token"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
// MaxHTTPBodySize defines max http body size
const MaxHTTPBodySize = 1024 * 1024
const TokenLength = 64
// credentials holds user credentials
type credentials struct {
Email string `json:"email"`
Password string `json:"password"`
}
// ApiAuthHandler aims to handle unauthorized requests and errors as json
type ApiAuthHandler struct {
host string
credChecker CredCheckerFunc
jwtService *token.Service
storage storage.Storage
activateAccountFunc ActivateAccountFunc
changePasswordRequestFunc ChangePasswordRequestFunc
}
func NewApiAuthHandler(host string, credChecker CredCheckerFunc, jwtService *token.Service, storage storage.Storage) *ApiAuthHandler {
return &ApiAuthHandler{host: host, credChecker: credChecker, jwtService: jwtService, storage: storage}
}
func (a *ApiAuthHandler) LoginHandler(w http.ResponseWriter, r *http.Request) {
creds, err := a.getCredentials(w, r)
if err != nil {
renderJSONWithStatus(w, JSON{"error": "failed to parse credentials"}, http.StatusBadRequest)
return
}
sessOnly := r.URL.Query().Get("sess") == "1"
if a.credChecker == nil {
renderJSONWithStatus(w, JSON{"error": "no credential checker"}, http.StatusInternalServerError)
return
}
ok, err := a.credChecker.Check(creds.Email, creds.Password)
log.Debugf("LOGIN check: %v", ok)
if err != nil {
renderJSONWithStatus(w, JSON{"error": "failed to check user credentials"}, http.StatusInternalServerError)
return
}
if !ok {
renderJSONWithStatus(w, JSON{"error": "incorrect email or password"}, http.StatusForbidden)
return
}
userID := token.HashID(sha1.New(), creds.Email)
u := token.User{
Name: creds.Email,
ID: userID,
}
claims := token.Claims{
User: &u,
StandardClaims: jwt.StandardClaims{
Id: RandToken(TokenLength),
Issuer: a.host,
},
SessionOnly: sessOnly,
}
if _, err = a.jwtService.Set(w, claims); err != nil {
renderJSONWithStatus(w, JSON{"error": "internal error"}, http.StatusInternalServerError)
return
}
tkn, err := a.jwtService.Token(claims)
if err != nil {
log.Printf("internal error: %s\n", err)
renderJSONWithStatus(w, JSON{"error": "internal error"}, http.StatusInternalServerError)
return
}
renderJSONWithStatus(w, JSON{"user": claims.User, "jwt": tkn}, http.StatusOK)
}
func (a *ApiAuthHandler) LogoutHandler(w http.ResponseWriter, r *http.Request) {
a.jwtService.Reset(w)
http.Redirect(w, r, "/", 302)
}
func (a *ApiAuthHandler) ActivationHandler(w http.ResponseWriter, r *http.Request) {
token := r.URL.Query().Get("token")
if token == "" {
renderJSONWithStatus(w, JSON{"error": "bad request"}, http.StatusBadRequest)
return
}
user, err := a.storage.GetUserByConfirmationToken(token)
if err != nil && !errors.Is(err, storage.ErrUserNotFound) {
log.Printf("internal error: %s", err)
renderJSONWithStatus(w, JSON{"error": "internal error"}, http.StatusInternalServerError)
return
} else if errors.Is(err, storage.ErrUserNotFound) {
renderJSONWithStatus(w, JSON{"error": "bad request"}, http.StatusBadRequest)
return
}
user.Enabled = true
if err := a.storage.UpdateUser(user); err != nil {
log.Printf("internal error: %s", err)
renderJSONWithStatus(w, JSON{"error": "internal error"}, http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func (a *ApiAuthHandler) RegistrationHandler(w http.ResponseWriter, r *http.Request) {
email := r.FormValue("email")
if email == "" {
renderJSONWithStatus(w, JSON{"error": "bad request"}, http.StatusBadRequest)
return
}
password := r.FormValue("password")
if password == "" {
renderJSONWithStatus(w, JSON{"error": "bad request"}, http.StatusBadRequest)
return
}
if !passwordValid(password) {
renderJSONWithStatus(w, JSON{"error": "password must be contains at least 6 symbols"}, http.StatusBadRequest)
return
}
if !emailValid(email) {
renderJSONWithStatus(w, JSON{"error": "invalid email"}, http.StatusBadRequest)
return
}
_, err := a.storage.GetUser(email)
if err != nil && !errors.Is(err, storage.ErrUserNotFound) {
log.Printf("internal error: %s", err)
renderJSONWithStatus(w, JSON{"error": "email already exists"}, http.StatusBadRequest)
return
}
user, err := storage.NewUser(email, password)
if err != nil {
log.Printf("internal error: %s", err)
renderJSONWithStatus(w, JSON{"error": "internal error"}, http.StatusInternalServerError)
return
}
err = a.storage.CreateUser(user)
if err != nil {
log.Printf("internal error: %s", err)
renderJSONWithStatus(w, JSON{"error": "internal error"}, http.StatusInternalServerError)
return
}
if a.activateAccountFunc != nil {
if err := a.activateAccountFunc(email, user.ConfirmationToken); err != nil {
log.Errorf("error during send activation token: %s", err)
}
}
w.WriteHeader(http.StatusOK)
}
func (a *ApiAuthHandler) ForgetPasswordRequestHandler(w http.ResponseWriter, r *http.Request) {
email := r.FormValue("email")
if email == "" {
log.Info("change password: empty email")
renderJSONWithStatus(w, JSON{"error": "bad request"}, http.StatusBadRequest)
return
}
user, err := a.storage.GetUser(email)
if err != nil {
log.Printf("change password: %s", err)
renderJSONWithStatus(w, nil, http.StatusOK)
return
}
if !user.Enabled {
renderJSONWithStatus(w, nil, http.StatusOK)
return
}
user.RegenerateChangePasswordToken()
if err := a.storage.UpdateUser(user); err != nil {
log.Printf("update user error: %s", err)
renderJSONWithStatus(w, JSON{"error": "internal error"}, http.StatusInternalServerError)
return
}
if err := a.changePasswordRequestFunc(email, user.ChangePasswordToken); err != nil {
log.Printf("change password execution error: %s", err)
renderJSONWithStatus(w, JSON{"error": "internal error"}, http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func (a *ApiAuthHandler) ChangePasswordHandler(w http.ResponseWriter, r *http.Request) {
token := r.FormValue("token")
password := r.FormValue("password")
if token == "" || password == "" {
log.Info("change request: empty password or token")
renderJSONWithStatus(w, JSON{"error": "bad request"}, http.StatusBadRequest)
return
}
user, err := a.storage.GetUserByChangePasswordToken(token)
if err != nil && !errors.Is(err, storage.ErrUserNotFound) {
log.Errorf("internal error: %s", err)
renderJSONWithStatus(w, JSON{"error": "internal error"}, http.StatusInternalServerError)
return
} else if errors.Is(err, storage.ErrUserNotFound) {
log.Info("change request: user not found")
renderJSONWithStatus(w, JSON{"error": "bad request"}, http.StatusBadRequest)
return
}
if user.ChangePasswordToken == "" || user.ChangePasswordToken != token {
renderJSONWithStatus(w, JSON{"error": "bad request"}, http.StatusBadRequest)
return
}
if err = user.UpdatePassword(password); err != nil {
log.Errorf("internal error: %s", err)
renderJSONWithStatus(w, JSON{"error": "internal error"}, http.StatusInternalServerError)
}
if err := a.storage.UpdateUser(user); err != nil {
log.Errorf("internal error: %s", err)
renderJSONWithStatus(w, JSON{"error": "internal error"}, http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func (a *ApiAuthHandler) getCredentials(w http.ResponseWriter, r *http.Request) (credentials, error) {
// GET /something?user=name&passwd=xyz&aud=bar
if r.Method == "GET" {
return credentials{
Email: r.URL.Query().Get("email"),
Password: r.URL.Query().Get("password"),
}, nil
}
if r.Method != "POST" {
return credentials{}, errors.Errorf("method %s not supported", r.Method)
}
if r.Body != nil {
r.Body = http.MaxBytesReader(w, r.Body, MaxHTTPBodySize)
}
contentType := r.Header.Get("Content-Type")
if contentType != "" {
mt, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return credentials{}, err
}
contentType = mt
}
// POST with json body
if contentType == "application/json" {
var creds credentials
if err := json.NewDecoder(r.Body).Decode(&creds); err != nil {
return credentials{}, errors.Wrap(err, "failed to parse request body")
}
return creds, nil
}
// POST with form
if err := r.ParseForm(); err != nil {
return credentials{}, errors.Wrap(err, "failed to parse request")
}
return credentials{
Email: r.Form.Get("email"),
Password: r.Form.Get("password"),
}, nil
}
func (a *ApiAuthHandler) SetActivationTokenSenderFunc(f ActivateAccountFunc) {
a.activateAccountFunc = f
}
func (a *ApiAuthHandler) SetChangePasswordRequestFunc(f ChangePasswordRequestFunc) {
a.changePasswordRequestFunc = f
}