package sihl-user

  1. Overview
  2. Docs

Source file password_reset.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
let log_src =
  Logs.Src.create ("sihl.service." ^ Sihl.Contract.Password_reset.name)
;;

module Logs = (val Logs.src_log log_src : Logs.LOG)

module Make
  (UserService : Sihl.Contract.User.Sig)
  (TokenService : Sihl.Contract.Token.Sig) =
struct
  let create_reset_token ?ctx email =
    let%lwt user = UserService.find_by_email_opt ?ctx email in
    match user with
    | Some user ->
      let user_id = user.id in
      TokenService.create
        ?ctx
        ~expires_in:Sihl.Time.OneDay
        [ "user_id", user_id ]
      |> Lwt.map Option.some
    | None ->
      Logs.warn (fun m -> m "No user found with email %s" email);
      Lwt.return None
  ;;

  let reset_password ?ctx ~token password password_confirmation =
    let%lwt user_id = TokenService.read ?ctx token ~k:"user_id" in
    match user_id with
    | None -> Lwt.return @@ Error "Token invalid or not assigned to any user"
    | Some user_id ->
      let%lwt user = UserService.find ?ctx user_id in
      let%lwt result =
        UserService.set_password ?ctx user ~password ~password_confirmation
      in
      Lwt.return @@ Result.map (fun _ -> ()) result
  ;;

  let start () = Lwt.return ()
  let stop () = Lwt.return ()

  let lifecycle =
    Sihl.Container.create_lifecycle
      Sihl.Contract.Password_reset.name
      ~start
      ~stop
      ~dependencies:(fun () ->
      [ TokenService.lifecycle; UserService.lifecycle ])
  ;;

  let register () = Sihl.Container.Service.create lifecycle
end
OCaml

Innovation. Community. Security.