Level: beginner • Mithril.js Version: latest
api jwt local storage login m.mount m.request m.route vnode wrapper
This example is showing an authentication wrapper around Mithril.js' m.request
.
Normally, we would store and retrieve the bearer token in the browsers window.localStorage
or window.sessionStorage
.
In this example this is only hinted while doing some kind of fake authentication, but you should get the point.
So, let's see the example.
Type | Name | URL |
---|---|---|
script | mithril@latest | https://unpkg.com/mithril@latest |
var api = {
request: (options) => {
options.config = xhr => {
xhr.setRequestHeader('Authorization', 'Bearer ' + api.token())
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
}
return m.request(options).catch((error) => {
if(error.code == 401) m.route.set("/login")
throw error
});
},
token: (value) => {
if (value)
localStorage.setItem('token', value)
return localStorage.getItem('token')
},
tokenRemove: () => localStorage.removeItem('token')
}
// -- utils
function getRequestDemo() {
api.request({
method: "GET", url: "https://httpbin.org/headers"
}).then(function(response) {
//-- handle response
console.log('Success, Auth:', response.headers.Authorization)
}).catch(function(e){
//-- handle error
console.error('Error!')
})
}
function checkAuth() {
if (!api.token())
return false
else
return true
}
function doFakeLogin(username) {
// -- simulate login
api.token(username)
}
// -- app code
var loginForm = {
model: {
username: '',
password: ''
},
view: function(vnode) {
return !checkAuth() ? [
m('input[type="text"][placeholder="Username"]', {
onkeyup: function(e){
vnode.state.model.username = e.target.value
}
}),
m('br'),
m('input[type="password"][placeholder="Password"]', {
onkeyup: function(e){
vnode.state.model.password = e.target.value
}
}),
m('br'),
m('button', {
onclick: () => doFakeLogin(vnode.state.model.username)
}, 'Login')
]
: [
m('h2', 'Hooray!'),
m('button[type="button"]', {
onclick: api.tokenRemove
}, 'Logout/Destroy token'),
m('br'),
m('button[type="button"]', {
onclick: getRequestDemo
}, 'Make a POST request'),
m('span', 'and watch the request in the console')
]
}
}
var app = {
view: function(vnode) {
return [
m('h1', 'Wrapper around m.request to handle authentication with localstorage'),
m('ol',
m('li', 'login - markup only;'),
m('li', 'a token is added to sessionStorage;'),
checkAuth() && m('li', {style: "color:green"}, 'make a POST request - Authorization header is now present')
),
//--
m(loginForm)
]
}
}
m.mount(document.body, app);
As a prerequisite for this snippet, the latest version of Mithril.js framework is required. Beginners should have no problems following this example, that simply shows some basic recipies.
Here we can see use cases of different Mithril.js API methods like m.request
, m.route
or m.mount
, besides the centrepiece m() hyperscript function.
Also covered in this example is the use of Vnodes or virtual DOM nodes, a JavaScript data structure that describes a DOM tree.
The example was written by cmnstmntmn, last edits were made on 26 October 2021.
Did you note a typo or something else? So let me know by opening an issue. Or much better: just fork the repository on GitHub, push your commits and send a pull request. Ready to start your work? Then click on the edit link below. Thanks in advance!