Skip to content

Instantly share code, notes, and snippets.

@ishan-marikar
Forked from du5rte/Auth.js
Created July 25, 2018 10:05
Show Gist options
  • Save ishan-marikar/e912feddf762dc493fce8cb4d36075c2 to your computer and use it in GitHub Desktop.
Save ishan-marikar/e912feddf762dc493fce8cb4d36075c2 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