Last active
June 15, 2020 15:25
-
-
Save codrin-iftimie/ea76be6b2ae82c49174db29a84bfbe5e to your computer and use it in GitHub Desktop.
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
// Disclaimer: not actual code | |
import history from "services/history" | |
import store from "services/store" | |
import api from "services/api" | |
class AuthService { | |
constructor() { | |
this.tokenRefresher = throttle(this.refreshToken, 4 * 60 * 1000); | |
} | |
login(data) { | |
const promise = api.post("/login", data); | |
const token = await promise; | |
store.dispatch({type: "AUTH_TOKEN", value: token}); // let the view know the user is now logged in | |
history.push("/home"); // move to the default route | |
this.trackInactivity(); | |
return promise; | |
} | |
logout() { | |
const promise = api.post("/logout"); | |
await promise; | |
store.dispatch({type: "AUTH_TOKEN", value: null}) | |
history.push("/login") | |
return promise; | |
} | |
refreshToken = async () => { | |
await api.get("/login/refresh"); | |
this.cookieTimestamp = new Date(); | |
}; | |
trackInactivity() { | |
["mousemove", "mousedown", "keydown", "mousewheel"].forEach((event) => | |
window.addEventListener(event, this.tokenRefresher) | |
); | |
this.inactivityTracker = setInterval(async () => { | |
if (!this.cookieTimestamp) { | |
return; | |
} | |
const now = new Date(); | |
const timePassed = Math.abs(now - this.cookieTimestamp); | |
const minutesPassed = timePassed / (1000 * 60); | |
if (minutesPassed > 10) { | |
await this.logout(); | |
history.push("/login"); | |
store.dispatch({type: "USER_INACTIVE"}) | |
} | |
}, 5000); | |
} | |
} | |
const authService = new AuthService(); | |
export default authService; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment