-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuth.cpp
More file actions
559 lines (441 loc) · 12.9 KB
/
Copy pathAuth.cpp
File metadata and controls
559 lines (441 loc) · 12.9 KB
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
/**
*
* @file Auth.cpp
* @author Gaspard Kirira
*
* Copyright 2026, Gaspard Kirira.
* All rights reserved.
* https://github.com/rixcpp/auth
*
* Use of this source code is governed by a MIT license
* that can be found in the License file.
*
* Rix
*
*/
#include <rix/auth/Auth.hpp>
#include <rix/auth/detail/Email.hpp>
#include <vix/crypto/hex.hpp>
#include <vix/crypto/random.hpp>
#include <vix/time/Clock.hpp>
#include <vix/validation/Validate.hpp>
#include <array>
#include <cstdint>
#include <string>
#include <utility>
namespace rixlib::auth
{
namespace
{
[[nodiscard]] AuthError invalid_email_error()
{
return make_auth_error(
AuthErrorCode::InvalidEmail,
"Email address is invalid.");
}
[[nodiscard]] AuthError invalid_password_error(std::string message)
{
return make_auth_error(
AuthErrorCode::InvalidPassword,
std::move(message));
}
[[nodiscard]] AuthError invalid_credentials_error()
{
return make_auth_error(
AuthErrorCode::InvalidCredentials,
"Invalid email or password.");
}
[[nodiscard]] AuthError invalid_session_error(std::string message)
{
return make_auth_error(
AuthErrorCode::InvalidSession,
std::move(message));
}
[[nodiscard]] AuthError invalid_state_error(std::string message)
{
return make_auth_error(
AuthErrorCode::InvalidState,
std::move(message));
}
[[nodiscard]] AuthError crypto_error(std::string message)
{
return make_auth_error(
AuthErrorCode::CryptoError,
std::move(message));
}
} // namespace
Auth::Auth(UserStore &users, SessionStore &sessions)
: Auth(users, sessions, AuthConfig::development())
{
}
Auth::Auth(UserStore &users, SessionStore &sessions, AuthConfig config)
: users_(&users),
sessions_(&sessions),
config_(std::move(config)),
password_hasher_(config_)
{
}
AuthResult<User> Auth::register_user(const RegisterRequest &request)
{
const auto config_validation = validate_config();
if (config_validation.failed())
{
return AuthResult<User>::failure(config_validation.error());
}
const std::string email = detail::normalize_email(request.email);
RegisterRequest normalized_request{
email,
request.password};
const auto validation = validate_register_request(normalized_request);
if (validation.failed())
{
return AuthResult<User>::failure(validation.error());
}
auto exists = users_->exists_by_email(email);
if (exists.failed())
{
return AuthResult<User>::failure(exists.error());
}
if (exists.value())
{
return AuthResult<User>::failure(
make_auth_error(
AuthErrorCode::UserAlreadyExists,
"A user already exists with this email address."));
}
auto user_id = make_user_id();
if (user_id.failed())
{
return AuthResult<User>::failure(user_id.error());
}
auto password_hash = password_hasher_.hash(request.password);
if (password_hash.failed())
{
return AuthResult<User>::failure(password_hash.error());
}
const auto now = now_seconds();
User user{
user_id.value(),
email,
password_hash.value(),
now};
user.set_updated_at(now);
user.set_active(true);
user.set_email_verified(!config_.require_email_verification());
auto created = users_->create(user);
if (created.failed())
{
return AuthResult<User>::failure(created.error());
}
return AuthResult<User>::success(std::move(user));
}
AuthResult<LoginResult> Auth::login(const LoginRequest &request)
{
const auto config_validation = validate_config();
if (config_validation.failed())
{
return AuthResult<LoginResult>::failure(config_validation.error());
}
const std::string email = detail::normalize_email(request.email);
LoginRequest normalized_request{
email,
request.password};
const auto validation = validate_login_request(normalized_request);
if (validation.failed())
{
return AuthResult<LoginResult>::failure(validation.error());
}
auto found = users_->find_by_email(email);
if (found.failed())
{
return AuthResult<LoginResult>::failure(found.error());
}
if (!found.value().has_value())
{
return AuthResult<LoginResult>::failure(invalid_credentials_error());
}
User user = found.value().value();
if (!user.active())
{
return AuthResult<LoginResult>::failure(invalid_credentials_error());
}
if (config_.require_email_verification() && !user.email_verified())
{
return AuthResult<LoginResult>::failure(
invalid_state_error("Email verification is required before login."));
}
if (!password_hasher_.verify(request.password, user.password_hash()))
{
return AuthResult<LoginResult>::failure(invalid_credentials_error());
}
auto session_id = make_session_id();
if (session_id.failed())
{
return AuthResult<LoginResult>::failure(session_id.error());
}
auto token_value = make_token_value();
if (token_value.failed())
{
return AuthResult<LoginResult>::failure(token_value.error());
}
const auto now = now_seconds();
Session session{
session_id.value(),
user.id(),
now,
now + config_.session_ttl_seconds()};
auto created = sessions_->create(session);
if (created.failed())
{
return AuthResult<LoginResult>::failure(created.error());
}
Token token = make_token_for_user(
user.id(),
now,
token_value.value());
LoginResult result{
std::move(user),
std::move(session),
std::move(token)};
return AuthResult<LoginResult>::success(std::move(result));
}
AuthStatus Auth::logout(std::string_view session_id)
{
if (session_id.empty())
{
return AuthStatus::failure(
invalid_session_error("Session id cannot be empty."));
}
return sessions_->revoke_by_id(session_id);
}
AuthStatus Auth::logout_user(std::string_view user_id)
{
if (user_id.empty())
{
return AuthStatus::failure(
make_auth_error(
AuthErrorCode::InvalidInput,
"User id cannot be empty."));
}
return sessions_->revoke_by_user_id(user_id);
}
AuthResult<Session> Auth::authenticate_session(std::string_view session_id)
{
if (session_id.empty())
{
return AuthResult<Session>::failure(
invalid_session_error("Session id cannot be empty."));
}
auto found = sessions_->find_by_id(session_id);
if (found.failed())
{
return AuthResult<Session>::failure(found.error());
}
if (!found.value().has_value())
{
return AuthResult<Session>::failure(
invalid_session_error("Session not found."));
}
Session session = found.value().value();
const auto now = now_seconds();
if (session.revoked())
{
return AuthResult<Session>::failure(
make_auth_error(
AuthErrorCode::SessionRevoked,
"Session has been revoked."));
}
if (session.expired(now))
{
return AuthResult<Session>::failure(
make_auth_error(
AuthErrorCode::SessionExpired,
"Session has expired."));
}
session.set_last_seen_at(now);
auto updated = sessions_->update(session);
if (updated.failed())
{
return AuthResult<Session>::failure(updated.error());
}
return AuthResult<Session>::success(std::move(session));
}
AuthResult<Session> Auth::refresh_session(std::string_view session_id)
{
auto authenticated = authenticate_session(session_id);
if (authenticated.failed())
{
return authenticated;
}
Session session = authenticated.value();
const auto now = now_seconds();
if (!session.refreshable(now))
{
return AuthResult<Session>::failure(
invalid_session_error("Session cannot be refreshed."));
}
session.refresh(now, config_.session_ttl_seconds());
auto updated = sessions_->update(session);
if (updated.failed())
{
return AuthResult<Session>::failure(updated.error());
}
return AuthResult<Session>::success(std::move(session));
}
AuthResult<Token> Auth::issue_token(std::string_view user_id)
{
const auto config_validation = validate_config();
if (config_validation.failed())
{
return AuthResult<Token>::failure(config_validation.error());
}
if (user_id.empty())
{
return AuthResult<Token>::failure(
make_auth_error(
AuthErrorCode::InvalidInput,
"User id cannot be empty."));
}
auto token_value = make_token_value();
if (token_value.failed())
{
return AuthResult<Token>::failure(token_value.error());
}
const auto now = now_seconds();
return AuthResult<Token>::success(
make_token_for_user(
std::string(user_id),
now,
token_value.value()));
}
const AuthConfig &Auth::config() const noexcept
{
return config_;
}
const PasswordHasher &Auth::password_hasher() const noexcept
{
return password_hasher_;
}
AuthStatus Auth::validate_register_request(
const RegisterRequest &request) const
{
const auto email = validate_email(request.email);
if (email.failed())
{
return email;
}
const auto password = validate_password_for_register(request.password);
if (password.failed())
{
return password;
}
return AuthStatus::success();
}
AuthStatus Auth::validate_login_request(
const LoginRequest &request) const
{
const auto email = validate_email(request.email);
if (email.failed())
{
return email;
}
if (request.password.empty())
{
return AuthStatus::failure(
invalid_password_error("Password cannot be empty."));
}
return AuthStatus::success();
}
AuthStatus Auth::validate_email(std::string_view email) const
{
const std::string value(email);
const auto result = vix::validation::validate("email", value)
.required("Email address is required.")
.email("Email address is invalid.")
.length_max(320, "Email address is too long.")
.result();
if (!result.ok())
{
return AuthStatus::failure(invalid_email_error());
}
return AuthStatus::success();
}
AuthStatus Auth::validate_password_for_register(
std::string_view password) const
{
if (password.empty())
{
return AuthStatus::failure(
invalid_password_error("Password cannot be empty."));
}
if (!password_hasher_.accepts(password))
{
return AuthStatus::failure(
invalid_password_error(
"Password does not satisfy the configured password policy."));
}
return AuthStatus::success();
}
AuthStatus Auth::validate_config() const
{
if (config_.min_password_length() == 0 ||
config_.max_password_length() == 0 ||
config_.min_password_length() > config_.max_password_length() ||
config_.session_ttl_seconds() <= 0 ||
config_.token_ttl_seconds() <= 0 ||
config_.password_hash_iterations() == 0 ||
config_.password_salt_size() == 0 ||
config_.password_hash_size() == 0 ||
config_.issuer().empty())
{
return AuthStatus::failure(
make_auth_error(
AuthErrorCode::ConfigurationError,
"Authentication configuration is invalid."));
}
return AuthStatus::success();
}
std::int64_t Auth::now_seconds() const noexcept
{
return vix::time::SystemClock::now().seconds_since_epoch();
}
AuthResult<std::string> Auth::make_user_id() const
{
return make_secure_id("user");
}
AuthResult<std::string> Auth::make_session_id() const
{
return make_secure_id("session");
}
AuthResult<std::string> Auth::make_token_value() const
{
return make_secure_id("token");
}
AuthResult<std::string> Auth::make_secure_id(std::string_view prefix) const
{
std::array<std::uint8_t, 32> bytes{};
auto random = vix::crypto::random_bytes(bytes);
if (!random.ok())
{
return AuthResult<std::string>::failure(
crypto_error(std::string(random.error().message)));
}
std::string out(prefix);
out.push_back('_');
out += vix::crypto::hex_lower(bytes);
return AuthResult<std::string>::success(std::move(out));
}
Token Auth::make_token_for_user(
std::string user_id,
std::int64_t now,
std::string value) const
{
Token token{
std::move(value),
std::move(user_id),
now,
now + config_.token_ttl_seconds()};
token.set_issuer(config_.issuer());
return token;
}
} // namespace rixlib::auth