Skip to content

Instantly share code, notes, and snippets.

@du5rte
Created March 16, 2017 16:38
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save du5rte/d79ef2b5bf57f16b9ce40fe6a1923fe0 to your computer and use it in GitHub Desktop.
Save du5rte/d79ef2b5bf57f16b9ce40fe6a1923fe0 to your computer and use it in GitHub Desktop.
mobX Auth Store
import mobx, { computed, observable, action } from "mobx"
import store from "store"
import autoStore from "./autoStore"
class Auth {
constructor() {
autoStore("authentication", this)
}
@observable authorization = null
@computed get isAuthenticated() {
return this.authorization ? true : false
}
@action login(body) {
return fetch(__API___, {
method: "POST",
body: JSON.stringify(body)
})
.then((response) => {
return response.json()
})
.then((body) => {
const token = body.token // "abcefghi...
this.setToken(token)
})
}
@action setToken(token) {
this.authorization = `Bearer ${token}`
}
@computed get getToken() {
if (this.authorization) {
return this.authorization.match(/(?:Bearer\s+)?(\w+\.\w+\.\w+)/)[1]
} else {
return null
}
}
@action logout() {
store.clearAll()
}
}
const authStore = window.authStore = new Auth
export default authStore
@patrickmuhi
Copy link

Nice thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment