1
0
mirror of https://github.com/bitwarden/browser.git synced 2024-12-04 13:44:00 +01:00
bitwarden-browser/src/app/services/tokenService.js

91 lines
2.7 KiB
JavaScript
Raw Normal View History

2015-12-09 04:35:05 +01:00
angular
.module('bit.services')
2017-06-23 16:41:57 +02:00
.factory('tokenService', function ($sessionStorage, $localStorage, jwtHelper) {
2015-12-09 04:35:05 +01:00
var _service = {},
_token = null,
_refreshToken = null;
2015-12-09 04:35:05 +01:00
_service.setToken = function (token) {
$sessionStorage.accessToken = token;
2015-12-09 04:35:05 +01:00
_token = token;
};
_service.getToken = function () {
if (!_token) {
_token = $sessionStorage.accessToken;
2015-12-09 04:35:05 +01:00
}
return _token ? _token : null;
2015-12-09 04:35:05 +01:00
};
_service.clearToken = function () {
_token = null;
delete $sessionStorage.accessToken;
};
_service.setRefreshToken = function (token) {
$sessionStorage.refreshToken = token;
_refreshToken = token;
};
_service.getRefreshToken = function () {
if (!_refreshToken) {
_refreshToken = $sessionStorage.refreshToken;
}
return _refreshToken ? _refreshToken : null;
};
_service.clearRefreshToken = function () {
_refreshToken = null;
delete $sessionStorage.refreshToken;
2015-12-09 04:35:05 +01:00
};
2017-06-23 16:41:57 +02:00
_service.setTwoFactorToken = function (token, email) {
if (!$localStorage.twoFactor) {
$localStorage.twoFactor = {};
}
$localStorage.twoFactor[email] = token;
};
_service.getTwoFactorToken = function (email) {
return $localStorage.twoFactor ? $localStorage.twoFactor[email] : null;
};
_service.clearTwoFactorToken = function (email) {
if (email) {
if ($localStorage.twoFactor && $localStorage.twoFactor[email]) {
delete $localStorage.twoFactor[email];
}
}
else {
delete $localStorage.twoFactor;
}
};
_service.clearTokens = function () {
_service.clearToken();
_service.clearRefreshToken();
};
2017-01-28 22:09:38 +01:00
_service.tokenSecondsRemaining = function (token, offsetSeconds) {
var d = jwtHelper.getTokenExpirationDate(token);
offsetSeconds = offsetSeconds || 0;
if (d === null) {
return 0;
}
var msRemaining = d.valueOf() - (new Date().valueOf() + (offsetSeconds * 1000));
return Math.round(msRemaining / 1000);
};
_service.tokenNeedsRefresh = function (token, minutes) {
minutes = minutes || 5; // default 5 minutes
var sRemaining = _service.tokenSecondsRemaining(token);
return sRemaining < (60 * minutes);
};
2015-12-09 04:35:05 +01:00
return _service;
});