package ez_api

  1. Overview
  2. Docs
Legend:
Page
Library
Module
Module type
Parameter
Class
Class type
Source

Source file ezSessionClient.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
(**************************************************************************)
(*                                                                        *)
(*                 Copyright 2018-2023 OCamlPro                           *)
(*                                                                        *)
(*  All rights reserved. This file is distributed under the terms of the  *)
(*  GNU Lesser General Public License version 2.1, with the special       *)
(*  exception on linking described in the file LICENSE.                   *)
(*                                                                        *)
(**************************************************************************)

open EzSession.TYPES

module type Make_S = sig
  type user_id
  type user_info
  type auth
  module Service : EzSession.M with type user_id = user_id
                                and type user_info = user_info

  type nonrec login_error = [
    | login_error
    | connect_error
    | logout_error
    | `Too_many_login_attempts
    | `Session_expired ]

  val connect :
    EzAPI.base_url ->
    ?token:string ->
    ((auth option, connect_error) result -> unit) -> unit

  val login :
    ?format:(string -> string) ->
    EzAPI.base_url ->
    ?login:string -> (* login *)
    ?password:string -> (* password *)
    ?foreign:(string * string) -> (* foreign authentication : origin * token *)
    ((auth, login_error) result -> unit) -> unit

  val logout :
    EzAPI.base_url ->
    token:string -> ((bool, logout_error) result -> unit) -> unit

  (* Tell the network layer that we think that the session has ended
     (a request probably returned an error status for missing auth).
     Since the state is kept internally, we have to do this first to
     trigger a full reconnection by `login`.
  *)
  val disconnected : unit -> unit

  val auth_headers : token:string -> (string * string) list
  val get : unit -> auth option
end

(* Takes Req module, that implements request calls. Passing 
   this Req module allows to configure request implementation
  instead of using default EzReq implementation*)
module Make(S: SessionArg)(Req: EzReq_S.S) : Make_S with
  type user_id = S.user_id and type user_info = S.user_info
  and type auth = (S.user_id, S.user_info) auth = struct

  type user_id = S.user_id
  type user_info = S.user_info

  type nonrec login_error = [
    | login_error
    | connect_error
    | logout_error
    | `Too_many_login_attempts
    | `Session_expired ]

(* If cookies are in use on server-side, `connect` might return
  an already authenticated user. Otherwise (CSRF protection),
  a token can be provided (saved in local storage).
*)

  module M = EzSession.Make(S)
  include M

  let set_cookie _token = (* TODO *)
    ()

  let remove_cookie _token = (* TODO *)
    ()

  type state =
    | Disconnected
    | Connected of EzSession.TYPES.auth_needed
    | User of auth

  let state = ref Disconnected

  let disconnected () = state := Disconnected

  let auth_headers ~token =
    match S.token_kind with
    | `Cookie _name -> [] (* Cookies are automatically added by browsers *)
    | `CSRF name -> [name, token ]
  
  let connect api ?token f =
    begin
      match token with
      | None -> ()
      | Some _ -> disconnected ()
    end;
    match !state with
    | Disconnected ->
       let headers = match token with
         | Some token -> Some (auth_headers ~token)
         | None -> None
       in
       Req.get0 ~msg:"connect"
         api
         Service.connect
         ?headers
         ~params:[]
         (function
          | Ok (AuthOk auth) ->
             state := User auth;
             f (Ok (Some auth))
          | Ok (AuthNeeded auth_needed) ->
             state := Connected auth_needed;
             f (Ok None)
          | Error e ->
             state := Disconnected;
             f (Error e)
         )
    | Connected _ ->
       (try f (Ok None) with _ -> ())
    | User u ->
       (try f (Ok (Some u)) with _ -> ())

  let logout api ~token f =
    remove_cookie ();
    match !state with
    | Disconnected
    | Connected _
      -> (try f (Ok false) with _ -> ())
    | User u ->
      Req.get0 ~msg:"logout"
        api
        Service.logout
        ~params:[]
        ~headers:(auth_headers ~token)
        (function
          | Ok auth_needed ->
            remove_cookie u.auth_token;
            state := Connected auth_needed;
            f (Ok true)
          | Error e ->
            f (Error e)
        )

  let rec login_rec ?format ntries api ?login ?password ?foreign
      (f : (('a, login_error) result -> unit)) =
    if ntries = 0 then
      (try f (Error `Too_many_login_attempts) with _ -> ())
    else
      match !state with
      | Disconnected ->
        connect api
          (function
            | Error e -> f (Error (e :> login_error))
            | Ok None -> login_rec ?format (ntries-1) api ?login ?password ?foreign f
            | Ok (Some u) ->
              if Some u.auth_login <> login then
                logout
                  api
                  ~token:u.auth_token
                  (function
                      Ok _ ->
                      login_rec ?format (ntries-1) api ?login ?password ?foreign f
                    | Error e ->
                      f (Error (e :> login_error)) )
              else
                f (Ok u))
      | User u ->
        if Some u.auth_login <> login then
          logout api
            ~token:u.auth_token
            (function
              | Ok _ ->
                login_rec ?format (ntries-1) api ?login ?password f
              | Error e ->
                f (Error (e :> login_error))
            )
        else
          f (Ok u)
      | Connected { challenge_id; challenge } ->
        match login, password, foreign with
        | Some login, Some password, _ ->
          let pwhash = EzSession.Hash.password ~login ~password in
          let pwhash = match format with
            | None -> pwhash
            | Some f -> f pwhash in
          let login_challenge_reply = EzSession.Hash.challenge ~challenge ~pwhash in
          Req.post0 ~msg:"login" api Service.login
            ~input:(Local {
                login_user = login;
                login_challenge_id = challenge_id;
                login_challenge_reply;
              })
            (function
              | Ok (LoginOk u) ->
                set_cookie u.auth_token;
                state := User u;
                f (Ok u)
              | Ok _ ->
                f (Error `Unverified_user)
              | Error `Challenge_not_found_or_expired _ ->
                login_rec ?format (ntries-1) api ~login ~password f
              | Error e -> f (Error (e :> login_error))
            )
        | _, _, Some (foreign_origin, foreign_token) ->
          Req.post0 ~msg:"login" api Service.login
            ~input:(Foreign { foreign_origin; foreign_token })
            (function
              | Ok (LoginOk u) ->
                set_cookie u.auth_token;
                state := User u;
                f (Ok u)
              | Ok _ ->
                f (Error `Unverified_user)
              | Error `Challenge_not_found_or_expired _ ->
                login_rec ?format (ntries-1) api ?foreign f
              | Error e -> f (Error (e :> login_error))
            )
        | _ -> assert false

  let login ?format api ?login ?password ?foreign f =
    login_rec ?format 4 api ?login ?password ?foreign f

  let get () =
    match !state with
    | User u -> Some u
    | Disconnected
      | Connected _ -> None

end
OCaml

Innovation. Community. Security.