-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Saving user session in local storage #10
Comments
When the elm application is initialised we can pass the user information stored in local storage as flag: <script>
flags = localStorage.getItem('store'); // get the value linked to the key "store"
Elm.Main.init({flags: flags});
</script> localStorage is saving key/value data where the data represent the person information as a stringify json. You can use the functions On the Elm side, the init function will now takes a flag parameter: init : Maybe String -> Url.Url -> Nav.Key -> ( Model, Cmd Msg ) Here the flag is represented as a From there we can decode the flag to a specific Elm type. type Session = Guest | Session Person
type alias Person = {email: String, token: String} The session can be a guest or a person. Then in the init function we can use json decoder to match the session =
case flag of
Nothing ->
Guest
Just str ->
case decodeString (map2 Person (field "email" string) (field "token" string)) str of
Ok p ->
Session.Session p
_ ->
Session.Guest It tooks me a bit of time to manage to decode the flag to this type. I'm still not sure this is the best solution, however it works. If the string stored in the local storage can't be decoded to the type (wrong json, doesn't contain email or token fields, not a valid json...) the application will convert the person to a see also |
I'm currently working on redirecting the user after authentication to a specific page (home page in my case but this can be change easily for example if we want to display a profile page on authentication). Elm provide the Nav.replaceUrl function: We can see this function take as first parameter a At the moment this key is stored on the main model: Lines 40 to 43 in f33382b
This is an issue when I try to redirect from a specific page as I don't have access to this value:
We can see that all the pages' model contain a session. So a solution to have access to the type Session
= Guest Nav.Key
| Session Nav.Key Person |
The session is now working on localhost (ie login, logout, redirects to home page...) and I'm now making sure that the backend apis are also up to date. app-mvp-elm/src/Pages/Session.elm Lines 52 to 54 in 6eb47dd
|
Now that the application receives a jwt on authentication we can start to manage the user session in a Elm model.
The text was updated successfully, but these errors were encountered: