This repository has been archived on 2021-07-29. You can view files and clone it, but cannot push or open issues or pull requests.
find_coach/src/store/modules/auth/actions.js

91 lines
2.1 KiB
JavaScript
Raw Normal View History

2021-07-28 22:40:49 +02:00
import getAuth from '../../../scripts/axios-auth';
2021-07-28 22:16:20 +02:00
2021-07-29 18:06:59 +02:00
let timer;
2021-07-28 22:40:49 +02:00
export default {
2021-07-28 22:58:02 +02:00
async login(context, payload) {
2021-07-29 17:44:12 +02:00
return context.dispatch('auth', {
...payload,
mode: 'login'
});
2021-07-28 22:58:02 +02:00
},
2021-07-28 22:40:49 +02:00
async signup(context, payload) {
2021-07-29 17:44:12 +02:00
return context.dispatch('auth', {
...payload,
mode: 'signup'
});
},
async auth(context, payload) {
const mode = payload.mode;
let url = 'accounts:signInWithPassword';
if (mode === 'signup') {
url = 'accounts:signUp';
}
2021-07-28 22:40:49 +02:00
try {
2021-07-29 17:44:12 +02:00
const response = await getAuth.post(url, {
2021-07-28 22:40:49 +02:00
email: payload.email,
password: payload.password,
returnSecureToken: true
});
const responseData = response.data;
2021-07-29 17:49:55 +02:00
2021-07-29 18:06:59 +02:00
const expiresIn = +responseData.expiresIn * 1000;
const expirationDate = new Date().getTime() + expiresIn;
2021-07-29 17:49:55 +02:00
localStorage.setItem('token', responseData.idToken);
localStorage.setItem('userId', responseData.localId);
2021-07-29 18:06:59 +02:00
localStorage.setItem('tokenExpiration', expirationDate);
timer = setTimeout(function() {
context.dispatch('autoLogout');
}, expiresIn);
2021-07-29 17:49:55 +02:00
2021-07-28 22:40:49 +02:00
context.commit('setUser', {
token: responseData.idToken,
2021-07-29 18:06:59 +02:00
userId: responseData.localId
2021-07-28 22:40:49 +02:00
});
} catch (err) {
const error = new Error(err.message);
throw error;
}
2021-07-29 17:11:31 +02:00
},
2021-07-29 17:49:55 +02:00
tryLogin(context) {
const token = localStorage.getItem('token');
const userId = localStorage.getItem('userId');
2021-07-29 18:06:59 +02:00
const tokenExpiration = localStorage.getItem('tokenExpiration');
const expiresIn = +tokenExpiration - new Date().getTime();
if (expiresIn < 0) {
return;
}
setTimeout(function() {
context.dispatch('autoLogout');
}, expiresIn);
2021-07-29 17:49:55 +02:00
if (token && userId) {
context.commit('setUser', {
token: token,
2021-07-29 18:06:59 +02:00
userId: userId
2021-07-29 17:49:55 +02:00
});
}
},
2021-07-29 17:11:31 +02:00
logout(context) {
2021-07-29 18:06:59 +02:00
localStorage.removeItem('token');
localStorage.removeItem('userId');
localStorage.removeItem('tokenExpiration');
clearTimeout(timer);
2021-07-29 17:11:31 +02:00
context.commit('setUser', {
token: null,
2021-07-29 18:06:59 +02:00
userId: null
2021-07-29 17:11:31 +02:00
});
2021-07-29 18:06:59 +02:00
},
autoLogout(context) {
context.dispatch('logout');
context.commit('setAutoLogout');
2021-07-28 22:40:49 +02:00
}
};