Skip to content

Instantly share code, notes, and snippets.

@pygy
Last active March 23, 2019 16:51
Show Gist options
  • Save pygy/89c34b25ad7dd145c2dc to your computer and use it in GitHub Desktop.
Save pygy/89c34b25ad7dd145c2dc to your computer and use it in GitHub Desktop.
Mithril Login redirect by Barney Carol

Taken from https://gitter.im/lhorie/mithril.js?at=553bdd1763c55be30636a16b in case it disappeared.

@barneycarol said:

[...] FWIW you can overcome a lot of apparent limitations in m.route by reinitialising m.route when things change

@tobscure said:

interesting, examples?

@barneycarol said:

Well I use it when authentication status changes So the way I do authentication is I store a token locally, which is added as a header to all XHR I get that token when I send the user to authenticate with a third party account service (Google ,Github), and they get redirected to my app with the token in the hash barneycarroll a day ago
So on initialisation:

if( tokenInHash ){
    // User has just been authenticated!
    m.route( body, '/profile', routes.authenticated )
}
else if( localToken ){
    // We already have a token, could still be valid
    m.route( body, '/login', routes.waiting )

    validate( localToken ).then(
        success => m.route( body, '/profile', routes.authenticated ),
        failure => m.route( body, '/login',   routes.lockedOut )
    )
}
else {
    m.route( body, '/signup', routes.lockedOut )
}

...

@barneycarol said:

2 other neat patterns with m.route: Mithril doesn’t do any mutation or initialisation reference to the route map object supplied as 3rd argument, so you can modify that without having to call m.route – although I’ve found that in situations where route options change you also want to change the default route, so it’s not as useful a strategy as it may first seem. Another powerful feature is the ability to set total wildcard routes:

routes.waiting = {
    'login'    : x,
    'signup'   : y,
    '/path...' : {
        controller : function(){
            localStorage.setItem(
                'entryPoint',
                m.route()
            )
        },
        view: function() {
          // ask the user to login or sign up, and update the route table
        }
        
    }
}

// Then, after login...
m.route( localStorage.getItem( 'entryPoint' ) )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment