Skip to content

Instantly share code, notes, and snippets.

@tiarebalbi
Forked from du5rte/Auth.js
Created March 22, 2018 07:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiarebalbi/b0b33c10d4c20cad3d3efadca25b76ed to your computer and use it in GitHub Desktop.
Save tiarebalbi/b0b33c10d4c20cad3d3efadca25b76ed 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment