accounts-frontend/src/services/api/authentication.js

106 lines
2.8 KiB
JavaScript
Raw Normal View History

import request from 'services/request';
import accounts from 'services/api/accounts';
2016-11-05 15:41:41 +05:30
const authentication = {
login({
login = '',
password = '',
rememberMe = false
}) {
return request.post(
'/api/authentication/login',
{login, password, rememberMe},
{token: null}
);
},
/**
* @param {object} options
* @param {object} [options.token] - an optional token to overwrite headers
* in middleware and disable token auto-refresh
*
* @return {Promise}
*/
logout(options = {}) {
return request.post('/api/authentication/logout', {}, {
token: options.token
});
},
2016-07-28 10:33:30 +05:30
forgotPassword({
login = '',
captcha = ''
2016-07-28 10:33:30 +05:30
}) {
return request.post(
'/api/authentication/forgot-password',
{login, captcha},
{token: null}
2016-07-28 10:33:30 +05:30
);
},
recoverPassword({
key = '',
newPassword = '',
newRePassword = ''
}) {
return request.post(
'/api/authentication/recover-password',
{key, newPassword, newRePassword},
{token: null}
2016-07-28 10:33:30 +05:30
);
},
/**
* Resolves if token is valid
*
* @param {object} options
* @param {string} options.token
* @param {string} options.refreshToken
*
* @return {Promise} - resolves with options.token or with a new token
* if it was refreshed. As a side effect the response
* will have a `user` field with current user data
*/
validateToken({token, refreshToken}) {
2016-11-05 15:41:41 +05:30
return new Promise((resolve) => {
if (typeof token !== 'string') {
throw new Error('token must be a string');
}
resolve();
})
.then(() => accounts.current({token}))
.then((user) => ({token, refreshToken, user}))
2016-11-05 15:41:41 +05:30
.catch((resp) => {
if (resp.message === 'Token expired') {
return authentication.requestToken(refreshToken)
.then(({token}) =>
accounts.current({token})
.then((user) => ({token, refreshToken, user}))
);
2016-11-05 15:41:41 +05:30
}
return Promise.reject(resp);
});
},
2016-08-10 00:47:49 +05:30
/**
* Request new access token using a refreshToken
*
* @param {string} refreshToken
*
* @return {Promise} - resolves to {token}
*/
requestToken(refreshToken) {
return request.post(
'/api/authentication/refresh-token',
{refresh_token: refreshToken}, // eslint-disable-line
{token: null}
2016-08-10 00:47:49 +05:30
).then((resp) => ({
token: resp.access_token
}));
}
};
2016-11-05 15:41:41 +05:30
export default authentication;