Created
March 26, 2019 15:43
-
-
Save MangelMaxime/8d3758cbc0bc69ffb9a156db294ea8e9 to your computer and use it in GitHub Desktop.
Http.fs - Demonstrate a way to retry fetching a new access token when old one expired
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[<RequireQualifiedAccess>] | |
module Http | |
open Fable.Import | |
open Fable.PowerPack | |
open Fable.PowerPack.Fetch | |
open Thoth.Json | |
open Fable.Core.JsInterop | |
type User = | |
{ Id : int | |
Permissions : string | |
Firstname : string | |
Surname : string | |
Token : string | |
RefreshToken : string | |
DefaultDomain : int } | |
static member Decoder = | |
Decode.object | |
(fun get -> | |
{ Id = get.Required.Field "userId" Decode.int | |
Permissions = get.Required.Field "permissions" Decode.string | |
Firstname = get.Required.Field "firstname" Decode.string | |
Surname = get.Required.Field "surname" Decode.string | |
Token = get.Required.Field "token" Decode.string | |
RefreshToken = get.Required.Field "refreshToken" Decode.string | |
DefaultDomain = get.Required.Field "defaultDomain" Decode.int } : User ) | |
let inline applyDecoder decoder promise = | |
promise | |
|> Promise.map (fun res -> | |
match Decode.fromString decoder res with | |
| Ok successValue -> successValue | |
| Error error -> | |
failwith error | |
) | |
type FetchResult = | |
| Success of Response | |
| BadStatus of Response | |
| NetworkError | |
let fetch (url: string) (init: RequestProperties list) : JS.Promise<FetchResult> = | |
GlobalFetch.fetch(RequestInfo.Url url, requestProps init) | |
|> Promise.map (fun response -> | |
if response.Ok then | |
Success response | |
else | |
if response.Status < 200 || response.Status >= 300 then | |
BadStatus response | |
else | |
NetworkError | |
) | |
let postRecord (url: string) (body: string) (properties: RequestProperties list) = | |
let defaultProps = | |
[ RequestProperties.Method HttpMethod.POST | |
requestHeaders [ ContentType "application/json" ] | |
RequestProperties.Body !^(body) ] | |
List.append defaultProps properties | |
|> fetch url | |
|> Promise.bind(fun result -> | |
promise { | |
match result with | |
| Success response -> return response | |
| BadStatus response -> | |
return failwith (string response.Status + " " + response.StatusText + " for URL " + response.Url) | |
| NetworkError -> | |
return failwith "network error" | |
} | |
) | |
let putRecord (url: string) (body: string) (properties: RequestProperties list) = | |
let defaultProps = | |
[ RequestProperties.Method HttpMethod.PUT | |
requestHeaders [ ContentType "application/json" ] | |
RequestProperties.Body !^(body) ] | |
List.append defaultProps properties | |
|> fetch url | |
|> Promise.bind(fun result -> | |
promise { | |
match result with | |
| Success response -> return response | |
| BadStatus response -> | |
return failwith (string response.Status + " " + response.StatusText + " for URL " + response.Url) | |
| NetworkError -> | |
return failwith "network error" | |
} | |
) | |
module Auth = | |
let private notifySessionChange (user : User) = | |
let detail = | |
jsOptions<Browser.CustomEventInit>(fun o -> | |
o.detail <- Some (box user) | |
) | |
let event = Browser.CustomEvent.Create("onSessionUpdate", detail) | |
Browser.window.dispatchEvent(event) | |
|> ignore | |
exception UnknownRefreshToken | |
let handleRefreshToken user (httpRequest : string -> JS.Promise<FetchResult>) result = | |
promise { | |
match result with | |
| Success response -> return response | |
| BadStatus response -> | |
if response.Status = 401 then | |
let body = | |
Encode.object [ | |
"refreshToken", Encode.string user.RefreshToken | |
] |> Encode.toString 0 | |
let! res = postRecord "/api/auth/token" body [] | |
let! txt = res.text() | |
match Decode.fromString (Decode.field "code" Decode.string) txt with | |
| Ok "unkown_token" -> | |
return raise UnknownRefreshToken | |
| Ok "success" -> | |
match Decode.fromString (Decode.field "data" User.Decoder) txt with | |
| Ok user -> | |
let! secondRes = httpRequest user.Token | |
match secondRes with | |
| Success response -> | |
notifySessionChange user | |
return response | |
| BadStatus response -> return failwith "bad status" | |
| NetworkError -> return failwith "network error" | |
| Error error -> return failwith error | |
| Ok code -> return failwith ("Unkown code: `" + code + "`") | |
| Error error -> return failwith error | |
else | |
return failwith (string response.Status + " " + response.StatusText + " for URL " + response.Url) | |
| NetworkError -> | |
return failwith "network error" | |
} | |
let getRecord (url : string) (user: User) (properties: RequestProperties list) = | |
let httpRequest token = | |
let defaultProps = | |
[ RequestProperties.Method HttpMethod.GET | |
requestHeaders [ ContentType "application/json" | |
Authorization ("Bearer " + token) ] ] | |
List.append defaultProps properties | |
|> fetch url | |
httpRequest user.Token | |
|> Promise.bind (handleRefreshToken user httpRequest) | |
|> Promise.catch (fun err -> | |
match err with | |
| UnknownRefreshToken -> | |
Browser.localStorage.removeItem("session") | |
Browser.location.href <- "/#login?needLogin" | |
failwith "User redirection has been executed" | |
| _ -> | |
failwithf "Unkown error: %A" err | |
) | |
let postRecord (url: string) (user : User) (body: string) (properties: RequestProperties list) = | |
let httpRequest token = | |
let defaultProps = | |
[ RequestProperties.Method HttpMethod.POST | |
requestHeaders [ ContentType "application/json" | |
Authorization ("Bearer " + token) ] | |
RequestProperties.Body !^(body) ] | |
List.append defaultProps properties | |
|> fetch url | |
httpRequest user.Token | |
|> Promise.bind (handleRefreshToken user httpRequest) | |
|> Promise.catch (fun err -> | |
match err with | |
| UnknownRefreshToken -> | |
Browser.localStorage.removeItem("session") | |
Browser.location.href <- "/#login?needLogin" | |
failwith "User redirection has been executed" | |
| _ -> | |
failwithf "Unkown error: %A" err | |
) | |
let putRecord (url: string) (user : User) (body: string) (properties: RequestProperties list) = | |
let httpRequest token = | |
let defaultProps = | |
[ RequestProperties.Method HttpMethod.PUT | |
requestHeaders [ ContentType "application/json" | |
Authorization ("Bearer " + token) ] | |
RequestProperties.Body !^(body) ] | |
List.append defaultProps properties | |
|> fetch url | |
httpRequest user.Token | |
|> Promise.bind (handleRefreshToken user httpRequest) | |
|> Promise.catch (fun err -> | |
match err with | |
| UnknownRefreshToken -> | |
Browser.localStorage.removeItem("session") | |
Browser.location.href <- "/#login?needLogin" | |
failwith "User redirection has been executed" | |
| _ -> | |
failwithf "Unkown error: %A" err | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Function under
Auth
will try once to get a newaccess token
if the session expired.If it succeeds retrieving a new
access token
then it will re-send the request.You can register
onSessionUpdate
from your application in order to update theaccess token
stored in your application.