-
Notifications
You must be signed in to change notification settings - Fork 3
/
user_model.ml
672 lines (644 loc) · 20.4 KB
/
user_model.ml
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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
module Rng = Mirage_crypto_rng
type token = {
token_type : string;
value : string;
expires_in : int;
created_at : Ptime.t;
(* In seconds, so after 1 hour would be 3600 seconds of inactivity *)
}
type cookie = {
name : string;
value : string;
expires_in : int;
uuid : string option;
created_at : Ptime.t;
last_access : Ptime.t;
user_agent : string option;
}
type user = {
name : string;
email : string;
email_verified : Ptime.t option;
password : string;
uuid : string;
tokens : token list;
cookies : cookie list;
created_at : Ptime.t;
updated_at : Ptime.t;
email_verification_uuid : Uuidm.t option;
active : bool;
super_user : bool;
}
let week = 604800 (* a week = 7 days * 24 hours * 60 minutes * 60 seconds *)
let session_cookie = "molly_session"
let csrf_cookie = "molly_csrf"
let cookie_to_json (cookie : cookie) : Yojson.Basic.t =
`Assoc
[
("name", `String cookie.name);
( "created_at",
`String (Utils.TimeHelper.string_of_ptime cookie.created_at) );
("value", `String cookie.value);
("expires_in", `Int cookie.expires_in);
( "uuid",
match cookie.uuid with Some uuid -> `String uuid | None -> `Null );
( "last_access",
`String (Utils.TimeHelper.string_of_ptime cookie.last_access) );
( "user_agent",
match cookie.user_agent with
| Some agent -> `String agent
| None -> `Null );
]
let string_or_none field = function
| None | Some `Null -> Ok None
| Some (`String v) -> Ok (Some v)
| Some json ->
Error
(`Msg
("invalid json for " ^ field ^ ": " ^ Yojson.Basic.to_string json))
let ( let* ) = Result.bind
let cookie_v1_of_json = function
| `Assoc xs -> (
match
Utils.Json.
( get "name" xs,
get "value" xs,
get "expires_in" xs,
get "uuid" xs,
get "created_at" xs )
with
| ( Some (`String name),
Some (`String value),
Some (`Int expires_in),
uuid,
Some (`String created_at_str) ) ->
let created_at =
match Utils.TimeHelper.ptime_of_string created_at_str with
| Ok ptime -> ptime
| Error (`Msg msg) ->
Logs.warn (fun m ->
m "couldn't parse created_at %s: value %S" msg
created_at_str);
Ptime.epoch
in
let* uuid = string_or_none "uuid" uuid in
Ok
{
name;
value;
expires_in;
uuid;
created_at;
last_access = created_at;
user_agent = None;
}
| _ ->
Error
(`Msg
("invalid json for cookie: " ^ Yojson.Basic.to_string (`Assoc xs)))
)
| js ->
Error
(`Msg
("invalid json for cookie, expected a dict: "
^ Yojson.Basic.to_string js))
let cookie_of_json = function
| `Assoc xs -> (
match
Utils.Json.
( get "name" xs,
get "value" xs,
get "expires_in" xs,
get "uuid" xs,
get "created_at" xs,
get "last_access" xs,
get "user_agent" xs )
with
| ( Some (`String name),
Some (`String value),
Some (`Int expires_in),
uuid,
Some (`String created_at_str),
Some (`String last_access_str),
user_agent ) ->
let created_at =
match Utils.TimeHelper.ptime_of_string created_at_str with
| Ok ptime -> ptime
| Error (`Msg msg) ->
Logs.warn (fun m ->
m "couldn't parse created_at %s: value %S" msg
created_at_str);
Ptime.epoch
in
let last_access =
match Utils.TimeHelper.ptime_of_string last_access_str with
| Ok ptime -> ptime
| Error (`Msg msg) ->
Logs.warn (fun m ->
m "couldn't parse last_access %s: value %S" msg
last_access_str);
created_at
in
let* uuid = string_or_none "uuid" uuid in
let* user_agent = string_or_none "user-agent" user_agent in
Ok
{
name;
value;
expires_in;
uuid;
created_at;
last_access;
user_agent;
}
| _ ->
Error
(`Msg
("invalid json for cookie: " ^ Yojson.Basic.to_string (`Assoc xs)))
)
| js ->
Error
(`Msg
("invalid json for cookie, expected a dict: "
^ Yojson.Basic.to_string js))
let token_to_json t : Yojson.Basic.t =
`Assoc
[
("token_type", `String t.token_type);
("value", `String t.value);
("expires_in", `Int t.expires_in);
("created_at", `String (Utils.TimeHelper.string_of_ptime t.created_at));
]
let token_of_json = function
| `Assoc xs -> (
match
Utils.Json.
( get "token_type" xs,
get "value" xs,
get "expires_in" xs,
get "created_at" xs )
with
| ( Some (`String token_type),
Some (`String value),
Some (`Int expires_in),
Some (`String created_at_str) ) ->
let created_at =
match Utils.TimeHelper.ptime_of_string created_at_str with
| Ok ptime -> Some ptime
| Error _ -> None
in
Ok
{
token_type;
value;
expires_in;
created_at = Option.get created_at;
}
| _ ->
Error
(`Msg
("invalid json for token: requires token_type, value, and \
expires_in: "
^ Yojson.Basic.to_string (`Assoc xs))))
| js ->
Error
(`Msg
("invalid json for token: expected a dict: "
^ Yojson.Basic.to_string js))
let user_to_json (u : user) : Yojson.Basic.t =
`Assoc
[
("name", `String u.name);
("email", `String u.email);
("email_verified", Utils.TimeHelper.ptime_to_json u.email_verified);
("password", `String u.password);
("uuid", `String u.uuid);
("tokens", `List (List.map token_to_json u.tokens));
("cookies", `List (List.map cookie_to_json u.cookies));
("created_at", `String (Utils.TimeHelper.string_of_ptime u.created_at));
("updated_at", `String (Utils.TimeHelper.string_of_ptime u.updated_at));
( "email_verification_uuid",
match u.email_verification_uuid with
| None -> `Null
| Some s -> `String (Uuidm.to_string s) );
("active", `Bool u.active);
("super_user", `Bool u.super_user);
]
let user_v1_of_json = function
| `Assoc xs -> (
match
Utils.Json.
( get "name" xs,
get "email" xs,
get "email_verified" xs,
get "password" xs,
get "uuid" xs,
get "tokens" xs,
get "cookies" xs,
get "created_at" xs,
get "updated_at" xs,
get "email_verification_uuid" xs )
with
| ( Some (`String name),
Some (`String email),
Some email_verified,
Some (`String password),
Some (`String uuid),
Some (`List tokens),
Some (`List cookies),
Some (`String updated_at_str),
Some (`String created_at_str),
Some email_verification_uuid ) ->
let created_at =
match Utils.TimeHelper.ptime_of_string created_at_str with
| Ok ptime -> Some ptime
| Error _ -> None
in
let updated_at =
match Utils.TimeHelper.ptime_of_string updated_at_str with
| Ok ptime -> Some ptime
| Error _ -> None
in
let* email_verified = Utils.TimeHelper.ptime_of_json email_verified in
let* tokens =
List.fold_left
(fun acc js ->
let* acc = acc in
let* token = token_of_json js in
Ok (token :: acc))
(Ok []) tokens
in
let* cookies =
List.fold_left
(fun acc js ->
let* acc = acc in
let* cookie = cookie_v1_of_json js in
Ok (cookie :: acc))
(Ok []) cookies
in
let* email_verification_uuid =
match email_verification_uuid with
| `Null -> Ok None
| `String s ->
let* uuid =
Option.to_result
~none:
(`Msg ("invalid UUID for email verification UUID: " ^ s))
(Uuidm.of_string s)
in
Ok (Some uuid)
| js ->
Error
(`Msg
("invalid json data for email verification UUID, expected \
a string: " ^ Yojson.Basic.to_string js))
in
Ok
{
name;
email;
email_verified;
password;
uuid;
tokens;
cookies;
created_at = Option.get created_at;
updated_at = Option.get updated_at;
email_verification_uuid;
active = true;
super_user = true;
}
| _ ->
Error
(`Msg
("invalid json for user: " ^ Yojson.Basic.to_string (`Assoc xs))))
| js ->
Error
(`Msg
("invalid json for user, expected a dict: "
^ Yojson.Basic.to_string js))
let user_v2_of_json = function
| `Assoc xs -> (
match
Utils.Json.
( get "name" xs,
get "email" xs,
get "email_verified" xs,
get "password" xs,
get "uuid" xs,
get "tokens" xs,
get "cookies" xs,
get "created_at" xs,
get "updated_at" xs,
get "email_verification_uuid" xs,
get "active" xs )
with
| ( Some (`String name),
Some (`String email),
Some email_verified,
Some (`String password),
Some (`String uuid),
Some (`List tokens),
Some (`List cookies),
Some (`String updated_at_str),
Some (`String created_at_str),
Some email_verification_uuid,
Some (`Bool active) ) ->
let created_at =
match Utils.TimeHelper.ptime_of_string created_at_str with
| Ok ptime -> Some ptime
| Error _ -> None
in
let updated_at =
match Utils.TimeHelper.ptime_of_string updated_at_str with
| Ok ptime -> Some ptime
| Error _ -> None
in
let* email_verified = Utils.TimeHelper.ptime_of_json email_verified in
let* tokens =
List.fold_left
(fun acc js ->
let* acc = acc in
let* token = token_of_json js in
Ok (token :: acc))
(Ok []) tokens
in
let* cookies =
List.fold_left
(fun acc js ->
let* acc = acc in
let* cookie = cookie_v1_of_json js in
Ok (cookie :: acc))
(Ok []) cookies
in
let* email_verification_uuid =
match email_verification_uuid with
| `Null -> Ok None
| `String s ->
let* uuid =
Option.to_result
~none:
(`Msg ("invalid UUID for email verification UUID: " ^ s))
(Uuidm.of_string s)
in
Ok (Some uuid)
| js ->
Error
(`Msg
("invalid json data for email verification UUID, expected \
a string: " ^ Yojson.Basic.to_string js))
in
Ok
{
name;
email;
email_verified;
password;
uuid;
tokens;
cookies;
created_at = Option.get created_at;
updated_at = Option.get updated_at;
email_verification_uuid;
active;
super_user = true;
}
| _ ->
Error
(`Msg
("invalid json for user: " ^ Yojson.Basic.to_string (`Assoc xs))))
| js ->
Error
(`Msg
("invalid json for user, expected a dict: "
^ Yojson.Basic.to_string js))
let user_of_json cookie_fn = function
| `Assoc xs -> (
match
Utils.Json.
( get "name" xs,
get "email" xs,
get "email_verified" xs,
get "password" xs,
get "uuid" xs,
get "tokens" xs,
get "cookies" xs,
get "created_at" xs,
get "updated_at" xs,
get "email_verification_uuid" xs,
get "active" xs,
get "super_user" xs )
with
| ( Some (`String name),
Some (`String email),
Some email_verified,
Some (`String password),
Some (`String uuid),
Some (`List tokens),
Some (`List cookies),
Some (`String updated_at_str),
Some (`String created_at_str),
Some email_verification_uuid,
Some (`Bool active),
Some (`Bool super_user) ) ->
let created_at =
match Utils.TimeHelper.ptime_of_string created_at_str with
| Ok ptime -> Some ptime
| Error _ -> None
in
let updated_at =
match Utils.TimeHelper.ptime_of_string updated_at_str with
| Ok ptime -> Some ptime
| Error _ -> None
in
let* email_verified = Utils.TimeHelper.ptime_of_json email_verified in
let* tokens =
List.fold_left
(fun acc js ->
let* acc = acc in
let* token = token_of_json js in
Ok (token :: acc))
(Ok []) tokens
in
let* cookies =
List.fold_left
(fun acc js ->
let* acc = acc in
let* cookie = cookie_fn js in
Ok (cookie :: acc))
(Ok []) cookies
in
let* email_verification_uuid =
match email_verification_uuid with
| `Null -> Ok None
| `String s ->
let* uuid =
Option.to_result
~none:
(`Msg ("invalid UUID for email verification UUID: " ^ s))
(Uuidm.of_string s)
in
Ok (Some uuid)
| js ->
Error
(`Msg
("invalid json data for email verification UUID, expected \
a string: " ^ Yojson.Basic.to_string js))
in
Ok
{
name;
email;
email_verified;
password;
uuid;
tokens;
cookies;
created_at = Option.get created_at;
updated_at = Option.get updated_at;
email_verification_uuid;
active;
super_user;
}
| _ ->
Error
(`Msg
("invalid json for user: " ^ Yojson.Basic.to_string (`Assoc xs))))
| js ->
Error
(`Msg
("invalid json for user, expected a dict: "
^ Yojson.Basic.to_string js))
let hash_password ~password ~uuid =
let hash =
Digestif.SHA256.(to_raw_string (digestv_string [ uuid; "-"; password ]))
in
Base64.encode_string hash
let generate_uuid () =
let data = Rng.generate 16 in
Uuidm.v4 (Bytes.unsafe_of_string data)
let generate_token ?(expires_in = 3600) ~created_at () =
let token = generate_uuid () in
{
token_type = "Bearer";
value = Uuidm.to_string token;
expires_in;
created_at;
}
let generate_cookie ~name ~uuid ?(expires_in = 3600) ~created_at ~user_agent ()
=
let id = generate_uuid () in
{
name;
value = Base64.encode_string (Uuidm.to_string id);
expires_in;
uuid = Some uuid;
created_at;
last_access = created_at;
user_agent;
}
let create_user ~name ~email ~password ~created_at ~active ~super_user
~user_agent =
let uuid = Uuidm.to_string (generate_uuid ()) in
let password = hash_password ~password ~uuid in
let auth_token = generate_token ~created_at () in
let session =
generate_cookie ~name:session_cookie ~expires_in:week ~uuid ~created_at
~user_agent ()
in
( {
name;
email;
email_verified = None;
password;
uuid;
tokens = [ auth_token ];
cookies = [ session ];
created_at;
updated_at = created_at;
email_verification_uuid = None;
active;
super_user;
},
session )
let update_user user ?name ?email ?email_verified ?password ?tokens ?cookies
?updated_at ?email_verification_uuid ?active ?super_user () =
{
user with
name = Option.value ~default:user.name name;
email = Option.value ~default:user.email email;
email_verified = Option.value ~default:user.email_verified email_verified;
password = Option.value ~default:user.password password;
tokens = Option.value ~default:user.tokens tokens;
cookies = Option.value ~default:user.cookies cookies;
updated_at = Option.value ~default:user.updated_at updated_at;
email_verification_uuid =
Option.value ~default:user.email_verification_uuid email_verification_uuid;
active = Option.value ~default:user.active active;
super_user = Option.value ~default:user.super_user super_user;
}
let is_valid_cookie (cookie : cookie) now =
Utils.TimeHelper.diff_in_seconds ~current_time:now
~check_time:cookie.created_at
< cookie.expires_in
let is_email_verified user = Option.is_some user.email_verified
let password_validation password = String.length password >= 8
let verify_email_token u _uuid timestamp =
match u with
| None ->
Logs.err (fun m -> m "email verification: Token couldn't be found.");
Error (`Msg "No token was found.")
| Some u -> (
match
Utils.TimeHelper.diff_in_seconds ~current_time:timestamp
~check_time:u.updated_at
< 3600
with
| true ->
let updated_user =
update_user u ~email_verified:(Some timestamp) ~updated_at:timestamp
~email_verification_uuid:None ()
in
Ok updated_user
| false ->
Logs.err (fun m -> m "email verification: This link is expired.");
Error
(`Msg
"This link has expired. Please sign in to get a new verification \
link."))
let user_session_cookie (user : user) cookie_value =
List.find_opt
(fun (cookie : cookie) ->
String.equal cookie.name session_cookie
&& String.equal cookie_value cookie.value)
user.cookies
let user_csrf_token (user : user) cookie_value =
List.find_opt
(fun (cookie : cookie) ->
String.equal cookie.name csrf_cookie
&& String.equal cookie_value cookie.value)
user.cookies
let keep_session_cookies user =
List.filter
(fun (cookie : cookie) -> String.equal cookie.name session_cookie)
user.cookies
let login_user ~email ~password ~user_agent user now =
match user with
| None -> Error (`Msg "This account does not exist.")
| Some u -> (
if not u.active then
(* TODO move to a middleware, provide instructions how to reactive an account *)
Error (`Msg "This account is not active")
else
let pass = hash_password ~password ~uuid:u.uuid in
match String.equal u.password pass && String.equal u.email email with
| true ->
let new_session =
generate_cookie ~name:session_cookie ~expires_in:week ~uuid:u.uuid
~created_at:now ~user_agent ()
in
let cookies = new_session :: keep_session_cookies u in
let updated_user = update_user u ~cookies () in
Ok (updated_user, new_session)
| false -> Error (`Msg "Invalid email or password."))
(* Invalid email or password is a trick error message to at least prevent malicious users from guessing login details :).*)