Created
March 16, 2017 16:38
-
-
Save du5rte/d79ef2b5bf57f16b9ce40fe6a1923fe0 to your computer and use it in GitHub Desktop.
mobX Auth Store
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Nice thanks