1
0
mirror of https://github.com/bitwarden/browser.git synced 2024-12-25 16:59:17 +01:00

convert token service to ts

This commit is contained in:
Kyle Spearrin 2017-11-02 20:50:00 -04:00
parent bf38ca9578
commit 9f9e3245de
7 changed files with 23 additions and 277 deletions

View File

@ -6,7 +6,6 @@
<script type="text/javascript" src="lib/forge/forge.js"></script>
<script type="text/javascript" src="models/api/requestModels.js"></script>
<script type="text/javascript" src="models/domainModels.js"></script>
<script type="text/javascript" src="services/tokenService.js"></script>
<script type="text/javascript" src="services/apiService.js"></script>
<script type="text/javascript" src="services/userService.js"></script>
<script type="text/javascript" src="services/settingsService.js"></script>

View File

@ -5,6 +5,7 @@ import CryptoService from './services/crypto.service';
import i18nService from './services/i18nService.js';
import LockService from './services/lockService.js';
import PasswordGenerationService from './services/passwordGeneration.service';
import TokenService from './services/token.service';
import UtilsService from './services/utils.service';
// Model imports
@ -75,7 +76,7 @@ var bg_isBackground = true,
window.bg_i18nService = bg_i18nService = new i18nService(bg_utilsService);
window.bg_constantsService = bg_constantsService = new ConstantsService(bg_i18nService);
window.bg_cryptoService = bg_cryptoService = new CryptoService();
window.bg_tokenService = bg_tokenService = new TokenService(bg_utilsService);
window.bg_tokenService = bg_tokenService = new TokenService();
window.bg_appIdService = bg_appIdService = new AppIdService();
window.bg_apiService = bg_apiService = new ApiService(bg_tokenService, bg_appIdService, bg_utilsService, bg_constantsService, logout);
window.bg_environmentService = bg_environmentService = new EnvironmentService(bg_constantsService, bg_apiService);

View File

@ -40,26 +40,26 @@ angular
}
if (response.twoFactorToken) {
tokenService.setTwoFactorToken(response.twoFactorToken, email, function () { });
tokenService.setTwoFactorToken(response.twoFactorToken, email);
}
tokenService.setTokens(response.accessToken, response.refreshToken, function () {
cryptoService.setKey(key).then(function () {
return cryptoService.setKeyHash(hashedPassword);
}).then(function () {
userService.setUserIdAndEmail(tokenService.getUserId(), tokenService.getEmail(),
function () {
cryptoService.setEncKey(response.key).then(function () {
return cryptoService.setEncPrivateKey(response.privateKey);
}).then(function () {
chrome.runtime.sendMessage({ command: 'loggedIn' });
deferred.resolve({
twoFactor: false,
twoFactorProviders: null
});
tokenService.setTokens(response.accessToken, response.refreshToken).then(function () {
return cryptoService.setKey(key);
}).then(function () {
return cryptoService.setKeyHash(hashedPassword);
}).then(function () {
userService.setUserIdAndEmail(tokenService.getUserId(), tokenService.getEmail(),
function () {
cryptoService.setEncKey(response.key).then(function () {
return cryptoService.setEncPrivateKey(response.privateKey);
}).then(function () {
chrome.runtime.sendMessage({ command: 'loggedIn' });
deferred.resolve({
twoFactor: false,
twoFactorProviders: null
});
});
});
});
});
}, function (providers) {
// two factor required

View File

@ -71,7 +71,7 @@ function initApiService() {
error: function (jqXHR, textStatus, errorThrown) {
if (jqXHR.responseJSON && jqXHR.responseJSON.TwoFactorProviders2 &&
Object.keys(jqXHR.responseJSON.TwoFactorProviders2).length) {
self.tokenService.clearTwoFactorToken(tokenRequest.email, function () {
self.tokenService.clearTwoFactorToken(tokenRequest.email).then(function () {
successWithTwoFactor(jqXHR.responseJSON.TwoFactorProviders2);
});
}
@ -439,7 +439,7 @@ function initApiService() {
function handleTokenState(self) {
var deferred = Q.defer();
self.tokenService.getToken(function (accessToken) {
self.tokenService.getToken().then(function (accessToken) {
if (!self.tokenService.tokenNeedsRefresh()) {
resolveTokenQs(accessToken, deferred);
return;
@ -447,7 +447,7 @@ function initApiService() {
doRefreshToken(self, function (response) {
var tokenResponse = new IdentityTokenResponse(response);
self.tokenService.setTokens(tokenResponse.accessToken, tokenResponse.refreshToken, function () {
self.tokenService.setTokens(tokenResponse.accessToken, tokenResponse.refreshToken).then(function () {
resolveTokenQs(tokenResponse.accessToken, deferred);
});
}, function (jqXHR) {
@ -459,7 +459,7 @@ function initApiService() {
}
function doRefreshToken(self, success, error) {
self.tokenService.getRefreshToken(function (refreshToken) {
self.tokenService.getRefreshToken().then(function (refreshToken) {
if (!refreshToken || refreshToken === '') {
error();
return;

View File

@ -12,7 +12,6 @@ export default class TokenService {
decodedToken: any;
refreshToken: string;
// TODO: fix callbacks
setTokens(accessToken: string, refreshToken: string): Promise<any> {
return Promise.all([
this.setToken(accessToken),
@ -20,14 +19,12 @@ export default class TokenService {
]);
}
// TODO: fix callback implementations
setToken(token: string): Promise<any> {
this.token = token;
this.decodedToken = null;
return UtilsService.saveObjToStorage(Keys.accessToken, token);
}
// TODO: fix callback implementations
async getToken(): Promise<string> {
if (this.token != null) {
return this.token;
@ -37,13 +34,11 @@ export default class TokenService {
return this.token;
}
// TODO: fix callback implementations
setRefreshToken(refreshToken: string): Promise<any> {
this.refreshToken = refreshToken;
return UtilsService.saveObjToStorage(Keys.refreshToken, refreshToken);
}
// TODO: fix callback implementations
async getRefreshToken(): Promise<string> {
if (this.refreshToken != null) {
return this.refreshToken;
@ -53,7 +48,6 @@ export default class TokenService {
return this.refreshToken;
}
// TODO: fix callback implementations
setTwoFactorToken(token: string, email: string): Promise<any> {
return UtilsService.saveObjToStorage(Keys.twoFactorTokenPrefix + email, token);
}
@ -62,7 +56,6 @@ export default class TokenService {
return UtilsService.getObjFromStorage<string>(Keys.twoFactorTokenPrefix + email);
}
// TODO: fix callback implementations
clearTwoFactorToken(email: string): Promise<any> {
return UtilsService.removeFromStorage(Keys.twoFactorTokenPrefix + email);
}

View File

@ -1,247 +0,0 @@
function TokenService(utilsService) {
this.utilsService = utilsService;
initTokenService();
}
function initTokenService() {
var _token,
_decodedToken,
_refreshToken;
TokenService.prototype.setTokens = function (accessToken, refreshToken, callback) {
if (!callback || typeof callback !== 'function') {
throw 'callback function required';
}
var self = this;
self.setToken(accessToken, function () {
self.setRefreshToken(refreshToken, function () {
callback();
});
});
};
TokenService.prototype.setToken = function (token, callback) {
if (!callback || typeof callback !== 'function') {
throw 'callback function required';
}
_token = token;
_decodedToken = null;
chrome.storage.local.set({
'accessToken': token
}, function () {
callback();
});
};
TokenService.prototype.getToken = function (callback) {
if (!callback || typeof callback !== 'function') {
throw 'callback function required';
}
if (_token) {
return callback(_token);
}
chrome.storage.local.get('accessToken', function (obj) {
if (obj && obj.accessToken) {
_token = obj.accessToken;
}
return callback(_token);
});
};
TokenService.prototype.setRefreshToken = function (refreshToken, callback) {
if (!callback || typeof callback !== 'function') {
throw 'callback function required';
}
_refreshToken = refreshToken;
chrome.storage.local.set({
'refreshToken': refreshToken
}, function () {
callback();
});
};
TokenService.prototype.getRefreshToken = function (callback) {
if (!callback || typeof callback !== 'function') {
throw 'callback function required';
}
if (_refreshToken) {
return callback(_refreshToken);
}
chrome.storage.local.get('refreshToken', function (obj) {
if (obj && obj.refreshToken) {
_refreshToken = obj.refreshToken;
}
return callback(_refreshToken);
});
};
TokenService.prototype.setTwoFactorToken = function (token, email, callback) {
if (!callback || typeof callback !== 'function') {
throw 'callback function required';
}
var obj = {};
obj['twoFactorToken_' + email] = token;
chrome.storage.local.set(obj, function () {
callback();
});
};
TokenService.prototype.getTwoFactorToken = function (email) {
return this.utilsService.getObjFromStorage('twoFactorToken_' + email).then(function (token) {
return token;
});
};
TokenService.prototype.clearTwoFactorToken = function (email, callback) {
if (!callback || typeof callback !== 'function') {
throw 'callback function required';
}
chrome.storage.local.remove('twoFactorToken_' + email, function () {
callback();
});
};
TokenService.prototype.clearToken = function () {
var self = this;
return Q.all([
self.utilsService.removeFromStorage('accessToken'),
self.utilsService.removeFromStorage('refreshToken')
]).then(function () {
_token = _decodedToken = _refreshToken = null;
});
};
// jwthelper methods
// ref https://github.com/auth0/angular-jwt/blob/master/src/angularJwt/services/jwt.js
TokenService.prototype.decodeToken = function () {
if (_decodedToken) {
return _decodedToken;
}
if (!_token) {
throw 'Token not found.';
}
var parts = _token.split('.');
if (parts.length !== 3) {
throw 'JWT must have 3 parts';
}
var decoded = urlBase64Decode(parts[1]);
if (!decoded) {
throw 'Cannot decode the token';
}
_decodedToken = JSON.parse(decoded);
return _decodedToken;
};
TokenService.prototype.getTokenExpirationDate = function () {
var decoded = this.decodeToken();
if (typeof decoded.exp === 'undefined') {
return null;
}
var d = new Date(0); // The 0 here is the key, which sets the date to the epoch
d.setUTCSeconds(decoded.exp);
return d;
};
TokenService.prototype.tokenSecondsRemaining = function (offsetSeconds) {
var d = this.getTokenExpirationDate();
offsetSeconds = offsetSeconds || 0;
if (d === null) {
return 0;
}
var msRemaining = d.valueOf() - (new Date().valueOf() + (offsetSeconds * 1000));
return Math.round(msRemaining / 1000);
};
TokenService.prototype.tokenNeedsRefresh = function (minutes) {
minutes = minutes || 5; // default 5 minutes
var sRemaining = this.tokenSecondsRemaining();
return sRemaining < (60 * minutes);
};
TokenService.prototype.getUserId = function () {
var decoded = this.decodeToken();
if (typeof decoded.sub === 'undefined') {
throw 'No user id found';
}
return decoded.sub;
};
TokenService.prototype.getEmail = function () {
var decoded = this.decodeToken();
if (typeof decoded.email === 'undefined') {
throw 'No email found';
}
return decoded.email;
};
TokenService.prototype.getName = function () {
var decoded = this.decodeToken();
if (typeof decoded.name === 'undefined') {
throw 'No name found';
}
return decoded.name;
};
TokenService.prototype.getPremium = function () {
var decoded = this.decodeToken();
if (typeof decoded.premium === 'undefined') {
return false;
}
return !!decoded.premium;
};
TokenService.prototype.getIssuer = function () {
var decoded = this.decodeToken();
if (typeof decoded.iss === 'undefined') {
throw 'No issuer found';
}
return decoded.iss;
};
function urlBase64Decode(str) {
var output = str.replace(/-/g, '+').replace(/_/g, '/');
switch (output.length % 4) {
case 0: { break; }
case 2: { output += '=='; break; }
case 3: { output += '='; break; }
default: {
throw 'Illegal base64url string!';
}
}
//polyfill https://github.com/davidchambers/Base64.js
return window.decodeURIComponent(escape(window.atob(output)));
}
}

View File

@ -139,7 +139,7 @@ function initUserService() {
}
var self = this;
self.tokenService.getToken(function (token) {
self.tokenService.getToken().then(function (token) {
if (!token) {
callback(false);
}