@eduzz/accounts-react-wrapper
Advanced tools
Comparing version 1.1.4 to 1.1.5-beta.0
@@ -0,1 +1,9 @@ | ||
## 1.1.5 (04 de Maio de 2022) | ||
- Corrigido problema de salvar cookie em path diferente de main que impedia de recuperar no main path | ||
- Agora estamos salvando no sessionStorage que não difere os paths. | ||
- Corrigido comportamento de refresh token quando bearer token está expirado. | ||
- Agora fazemos o refresh sempre que usar o token de refresh armazenado em session storage, | ||
se o usuário permanecer na mesma sessão, durante a validade do refresh. | ||
## 1.1.4 (23 de Março de 2022) | ||
@@ -2,0 +10,0 @@ |
@@ -6,6 +6,6 @@ "use strict"; | ||
var token = _a.token, tryRefreshToken = _a.tryRefreshToken, tryRefreshTokenParams = _a.tryRefreshTokenParams; | ||
var saveRefreshTokenOnCookie = tryRefreshTokenParams.saveRefreshTokenOnCookie, eraseRefreshTokenOnCookie = tryRefreshTokenParams.eraseRefreshTokenOnCookie, callAccountsLogout = tryRefreshTokenParams.callAccountsLogout, refreshResponseDefinitions = tryRefreshTokenParams.refreshResponseDefinitions; | ||
var saveRefreshTokenOnSessionStorage = tryRefreshTokenParams.saveRefreshTokenOnSessionStorage, eraseRefreshTokenOnSessionStorage = tryRefreshTokenParams.eraseRefreshTokenOnSessionStorage, callAccountsLogout = tryRefreshTokenParams.callAccountsLogout, refreshResponseDefinitions = tryRefreshTokenParams.refreshResponseDefinitions; | ||
tryRefreshToken({ | ||
saveRefreshTokenOnCookie: saveRefreshTokenOnCookie, | ||
eraseRefreshTokenOnCookie: eraseRefreshTokenOnCookie, | ||
saveRefreshTokenOnSessionStorage: saveRefreshTokenOnSessionStorage, | ||
eraseRefreshTokenOnSessionStorage: eraseRefreshTokenOnSessionStorage, | ||
callAccountsLogout: callAccountsLogout, | ||
@@ -12,0 +12,0 @@ refreshToken: token, |
@@ -9,4 +9,4 @@ "use strict"; | ||
var tryRefreshTokenParams = { | ||
saveRefreshTokenOnCookie: jest.fn(), | ||
eraseRefreshTokenOnCookie: jest.fn(), | ||
saveRefreshTokenOnSessionStorage: jest.fn(), | ||
eraseRefreshTokenOnSessionStorage: jest.fn(), | ||
callAccountsLogout: jest.fn(), | ||
@@ -26,4 +26,4 @@ refreshResponseDefinitions: { | ||
expect(tryRefreshToken).toHaveBeenCalledWith({ | ||
saveRefreshTokenOnCookie: tryRefreshTokenParams.saveRefreshTokenOnCookie, | ||
eraseRefreshTokenOnCookie: tryRefreshTokenParams.eraseRefreshTokenOnCookie, | ||
saveRefreshTokenOnSessionStorage: tryRefreshTokenParams.saveRefreshTokenOnSessionStorage, | ||
eraseRefreshTokenOnSessionStorage: tryRefreshTokenParams.eraseRefreshTokenOnSessionStorage, | ||
callAccountsLogout: tryRefreshTokenParams.callAccountsLogout, | ||
@@ -30,0 +30,0 @@ refreshToken: token, |
@@ -38,3 +38,3 @@ "use strict"; | ||
function initialize() { | ||
var refreshToken = (0, utils_1.getRefreshTokenFromCookie)(); | ||
var refreshToken = (0, utils_1.getRefreshTokenFromSessionStorage)(); | ||
var isSupport = (0, utils_1.isComingFromBackOffice)(backOffice === null || backOffice === void 0 ? void 0 : backOffice.urlParam); | ||
@@ -49,4 +49,4 @@ (0, aux_1.refreshOrlogin)({ | ||
tryRefreshTokenParams: { | ||
saveRefreshTokenOnCookie: utils_1.saveRefreshTokenOnCookie, | ||
eraseRefreshTokenOnCookie: utils_1.eraseRefreshTokenOnCookie, | ||
saveRefreshTokenOnSessionStorage: utils_1.saveRefreshTokenOnSessionStorage, | ||
eraseRefreshTokenOnSessionStorage: utils_1.eraseRefreshTokenOnSessionStorage, | ||
callAccountsLogout: callAccountsLogout, | ||
@@ -61,3 +61,3 @@ refreshResponseDefinitions: refreshResponseDefinitions, | ||
tryLogin: tryLogin, | ||
saveRefreshTokenOnCookie: utils_1.saveRefreshTokenOnCookie, | ||
saveRefreshTokenOnSessionStorage: utils_1.saveRefreshTokenOnSessionStorage, | ||
loginResponseDefinitions: loginResponseDefinitions, | ||
@@ -64,0 +64,0 @@ }); |
@@ -16,6 +16,6 @@ "use strict"; | ||
var test_tools_1 = require("./test.tools"); | ||
var index_1 = require("./index"); | ||
var context_1 = require("./context"); | ||
var mocks_1 = require("./mocks"); | ||
var Component = function () { | ||
var _a = (0, index_1.useAuth)(), bearerTokenDecoded = _a.bearerTokenDecoded, loading = _a.loading, bearerToken = _a.bearerToken; | ||
var _a = (0, context_1.useAuth)(), bearerTokenDecoded = _a.bearerTokenDecoded, loading = _a.loading, bearerToken = _a.bearerToken; | ||
return ((0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)("h1", __assign({ "data-testid": 'user' }, { children: bearerTokenDecoded === null || bearerTokenDecoded === void 0 ? void 0 : bearerTokenDecoded.name }), void 0), (0, jsx_runtime_1.jsx)("h2", __assign({ "data-testid": 'status' }, { children: loading ? 'loading...' : 'loaded' }), void 0), (0, jsx_runtime_1.jsx)("h2", __assign({ "data-testid": 'bearer-token' }, { children: bearerToken ? bearerToken : 'não tem' }), void 0)] }, void 0)); | ||
@@ -37,3 +37,3 @@ }; | ||
var conditionGenerated = (0, mocks_1.AuthProviderPropsMock)({ condition: condition }); | ||
(0, test_tools_1.render)((0, jsx_runtime_1.jsx)(index_1.AuthProvider, __assign({ config: conditionGenerated }, { children: (0, jsx_runtime_1.jsx)(Component, {}, void 0) }), void 0)); | ||
(0, test_tools_1.render)((0, jsx_runtime_1.jsx)(context_1.AuthProvider, __assign({ config: conditionGenerated }, { children: (0, jsx_runtime_1.jsx)(Component, {}, void 0) }), void 0)); | ||
expect(test_tools_1.screen.getByTestId('status')).toHaveTextContent('loading...'); | ||
@@ -51,3 +51,3 @@ expect(test_tools_1.screen.getByTestId('user')).toHaveTextContent(''); | ||
}; | ||
(0, test_tools_1.render)((0, jsx_runtime_1.jsx)(index_1.AuthProvider, __assign({ config: (0, mocks_1.AuthProviderPropsMock)({ condition: condition }) }, { children: (0, jsx_runtime_1.jsx)(Component, {}, void 0) }), void 0)); | ||
(0, test_tools_1.render)((0, jsx_runtime_1.jsx)(context_1.AuthProvider, __assign({ config: (0, mocks_1.AuthProviderPropsMock)({ condition: condition }) }, { children: (0, jsx_runtime_1.jsx)(Component, {}, void 0) }), void 0)); | ||
expect(test_tools_1.screen.getByTestId('status')).toHaveTextContent('loaded'); | ||
@@ -54,0 +54,0 @@ expect(test_tools_1.screen.getByTestId('user')).toHaveTextContent(bearerTokenDecoded.name); |
@@ -47,2 +47,3 @@ "use strict"; | ||
var utils_1 = require("./utils"); | ||
var bearerTokenInMemory; | ||
function useAuthentication(_a) { | ||
@@ -59,3 +60,3 @@ var _this = this; | ||
var callAccountsLogin = function (_a) { | ||
var callback = _a.tryLogin, saveRefreshTokenOnCookie = _a.saveRefreshTokenOnCookie, loginResponseDefinitions = _a.loginResponseDefinitions; | ||
var callback = _a.tryLogin, saveRefreshTokenOnSessionStorage = _a.saveRefreshTokenOnSessionStorage, loginResponseDefinitions = _a.loginResponseDefinitions; | ||
window.Eduzz.Accounts.login(partnerId, { | ||
@@ -68,3 +69,3 @@ env: env, | ||
accountsToken: accountsToken, | ||
saveRefreshTokenOnCookie: saveRefreshTokenOnCookie, | ||
saveRefreshTokenOnSessionStorage: saveRefreshTokenOnSessionStorage, | ||
loginResponseDefinitions: loginResponseDefinitions, | ||
@@ -75,3 +76,3 @@ }); | ||
var callAccountsLogout = function () { | ||
(0, utils_1.eraseRefreshTokenOnCookie)(); | ||
(0, utils_1.eraseRefreshTokenOnSessionStorage)(); | ||
window.Eduzz.Accounts.logout({ env: env }); | ||
@@ -84,7 +85,7 @@ }; | ||
var tryLogin = function (params) { return __awaiter(_this, void 0, void 0, function () { | ||
var accountsToken, saveRefreshTokenOnCookie, loginResponseDefinitions, tokenKey, refreshTokenKey, mapData, data, mappedData, _a, _b, refreshToken_1, _c, _d, _bearerToken, _bearerTokenDecoded, err_1; | ||
var accountsToken, saveRefreshTokenOnSessionStorage, loginResponseDefinitions, tokenKey, refreshTokenKey, mapData, data, mappedData, _a, _b, refreshToken_1, _c, _d, _bearerToken, _bearerTokenDecoded, err_1; | ||
return __generator(this, function (_e) { | ||
switch (_e.label) { | ||
case 0: | ||
accountsToken = params.accountsToken, saveRefreshTokenOnCookie = params.saveRefreshTokenOnCookie, loginResponseDefinitions = params.loginResponseDefinitions; | ||
accountsToken = params.accountsToken, saveRefreshTokenOnSessionStorage = params.saveRefreshTokenOnSessionStorage, loginResponseDefinitions = params.loginResponseDefinitions; | ||
tokenKey = loginResponseDefinitions.tokenKey, refreshTokenKey = loginResponseDefinitions.refreshTokenKey, mapData = loginResponseDefinitions.mapData; | ||
@@ -104,3 +105,3 @@ _e.label = 1; | ||
_a = mappedData, _b = refreshTokenKey, refreshToken_1 = _a[_b]; | ||
saveRefreshTokenOnCookie(refreshToken_1); | ||
saveRefreshTokenOnSessionStorage(refreshToken_1); | ||
setRefreshToken(refreshToken_1); | ||
@@ -111,2 +112,3 @@ _c = mappedData, _d = tokenKey, _bearerToken = _c[_d]; | ||
setBearerToken(_bearerToken); | ||
bearerTokenInMemory = _bearerToken; | ||
return [3 /*break*/, 4]; | ||
@@ -124,11 +126,11 @@ case 3: | ||
var tryRefreshToken = function (params) { return __awaiter(_this, void 0, void 0, function () { | ||
var eraseRefreshTokenOnCookie, accountsLogout, saveRefreshTokenOnCookie, refreshResponseDefinitions, tokenKey, refreshTokenKey, mapData, data, mappedData, _a, _b, newRefreshToken, _c, _d, _bearerToken, _bearerTokenDecoded, error_1; | ||
return __generator(this, function (_e) { | ||
switch (_e.label) { | ||
var eraseRefreshTokenOnSessionStorage, accountsLogout, saveRefreshTokenOnSessionStorage, refreshResponseDefinitions, tokenKey, refreshTokenKey, mapData, _a, data, status_1, mappedData, _b, _c, newRefreshToken, _d, _e, _bearerToken, _bearerTokenDecoded, error_1; | ||
return __generator(this, function (_f) { | ||
switch (_f.label) { | ||
case 0: | ||
eraseRefreshTokenOnCookie = params.eraseRefreshTokenOnCookie, accountsLogout = params.callAccountsLogout, saveRefreshTokenOnCookie = params.saveRefreshTokenOnCookie, refreshResponseDefinitions = params.refreshResponseDefinitions; | ||
eraseRefreshTokenOnSessionStorage = params.eraseRefreshTokenOnSessionStorage, accountsLogout = params.callAccountsLogout, saveRefreshTokenOnSessionStorage = params.saveRefreshTokenOnSessionStorage, refreshResponseDefinitions = params.refreshResponseDefinitions; | ||
tokenKey = refreshResponseDefinitions.tokenKey, refreshTokenKey = refreshResponseDefinitions.refreshTokenKey, mapData = refreshResponseDefinitions.mapData; | ||
_e.label = 1; | ||
_f.label = 1; | ||
case 1: | ||
_e.trys.push([1, 3, , 4]); | ||
_f.trys.push([1, 3, , 4]); | ||
cleanAccountsTokenURLParam(); | ||
@@ -141,16 +143,19 @@ return [4 /*yield*/, service_1.default.refreshToken({ | ||
case 2: | ||
data = (_e.sent()).data; | ||
_a = _f.sent(), data = _a.data, status_1 = _a.status; | ||
if (status_1 !== 200) | ||
throw new Error('Problema com o token'); | ||
mappedData = (0, utils_1.findTarget)(mapData, data); | ||
_a = mappedData, _b = refreshTokenKey, newRefreshToken = _a[_b]; | ||
saveRefreshTokenOnCookie(newRefreshToken); | ||
_b = mappedData, _c = refreshTokenKey, newRefreshToken = _b[_c]; | ||
saveRefreshTokenOnSessionStorage(newRefreshToken); | ||
setRefreshToken(refreshToken); | ||
_c = mappedData, _d = tokenKey, _bearerToken = _c[_d]; | ||
_d = mappedData, _e = tokenKey, _bearerToken = _d[_e]; | ||
_bearerTokenDecoded = jsonwebtoken_1.default.decode(_bearerToken); | ||
setBearerTokenDecoded(_bearerTokenDecoded); | ||
setBearerToken(_bearerToken); | ||
bearerTokenInMemory = _bearerToken; | ||
setLoading(false); | ||
return [3 /*break*/, 4]; | ||
case 3: | ||
error_1 = _e.sent(); | ||
eraseRefreshTokenOnCookie(); | ||
error_1 = _f.sent(); | ||
eraseRefreshTokenOnSessionStorage(); | ||
accountsLogout(); | ||
@@ -162,32 +167,32 @@ return [3 /*break*/, 4]; | ||
}); }; | ||
var initBearerInterceptor = function (_interceptor) { | ||
interceptors_1.default.bearer({ | ||
bearer: bearerToken, | ||
interceptor: _interceptor, | ||
}); | ||
}; | ||
var initRefreshTokenInterceptor = function (params) { | ||
var _refreshToken = (0, utils_1.getRefreshTokenFromCookie)(); | ||
var initBearerInterceptor = function (_a) { | ||
var _interceptors = _a._interceptors, active = _a.active; | ||
var _refreshToken = (0, utils_1.getRefreshTokenFromSessionStorage)(); | ||
if (_refreshToken) { | ||
interceptors_1.default.refresh({ | ||
interceptor: params._interceptor, | ||
bearerExpirationTimestamp: params.bearerExpirationTimestamp, | ||
updateToken: function () { | ||
return tryRefreshToken({ | ||
saveRefreshTokenOnCookie: utils_1.saveRefreshTokenOnCookie, | ||
eraseRefreshTokenOnCookie: utils_1.eraseRefreshTokenOnCookie, | ||
callAccountsLogout: callAccountsLogout, | ||
refreshToken: _refreshToken, | ||
refreshResponseDefinitions: refresh.response, | ||
interceptors_1.default.bearer({ | ||
bearer: bearerToken, | ||
interceptors: _interceptors, | ||
tryRefreshToken: function () { return __awaiter(_this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, tryRefreshToken({ | ||
saveRefreshTokenOnSessionStorage: utils_1.saveRefreshTokenOnSessionStorage, | ||
eraseRefreshTokenOnSessionStorage: utils_1.eraseRefreshTokenOnSessionStorage, | ||
callAccountsLogout: callAccountsLogout, | ||
refreshToken: _refreshToken, | ||
refreshResponseDefinitions: refresh.response, | ||
})]; | ||
case 1: | ||
_a.sent(); | ||
return [2 /*return*/, Promise.resolve(bearerTokenInMemory)]; | ||
} | ||
}); | ||
}); }, | ||
logout: function () { | ||
callAccountsLogout(); | ||
}, | ||
activeInterceptors: active, | ||
}); | ||
} | ||
}; | ||
var initLogoutInterceptor = function (_interceptor) { | ||
interceptors_1.default.logout({ | ||
interceptor: _interceptor, | ||
logout: function () { return callAccountsLogout(); }, | ||
}); | ||
}; | ||
var initializeAxiosInterceptors = function (_a) { | ||
@@ -201,14 +206,6 @@ var interceptors = _a.interceptors, active = _a.active; | ||
} | ||
if (!active || active.addBearerOnAllRequests !== false) { | ||
initBearerInterceptor(interceptors.request); | ||
} | ||
if (!active || active.refreshWhenBearerTokenIsExpired !== false) { | ||
initRefreshTokenInterceptor({ | ||
_interceptor: interceptors.request, | ||
bearerExpirationTimestamp: bearerTokenDecoded === null || bearerTokenDecoded === void 0 ? void 0 : bearerTokenDecoded.exp, | ||
}); | ||
} | ||
if (!active || active.logoutWhenResponseIsUnauthorized !== false) { | ||
initLogoutInterceptor(interceptors.response); | ||
} | ||
initBearerInterceptor({ | ||
_interceptors: interceptors, | ||
active: active, | ||
}); | ||
}; | ||
@@ -236,4 +233,2 @@ (0, react_1.useEffect)(function () { | ||
bearer: initBearerInterceptor, | ||
refresh: initRefreshTokenInterceptor, | ||
logout: initLogoutInterceptor, | ||
}, | ||
@@ -240,0 +235,0 @@ clientInterceptorsInitialize: clientInterceptorsInitialize, |
@@ -55,9 +55,6 @@ "use strict"; | ||
var jsonwebtoken_1 = __importDefault(require("jsonwebtoken")); | ||
var index_1 = require("./index"); | ||
var hook_1 = __importDefault(require("./hook")); | ||
var mocks_1 = require("./mocks"); | ||
var service_1 = __importDefault(require("./service")); | ||
var utils_1 = require("./utils"); | ||
var interceptors_1 = __importDefault(require("./interceptors")); | ||
var axios_1 = __importDefault(require("axios")); | ||
var date_fns_1 = require("date-fns"); | ||
describe('Context/Authentication/Hook', function () { | ||
@@ -80,3 +77,2 @@ var random = test_tools_1.faker.random, datatype = test_tools_1.faker.datatype, internet = test_tools_1.faker.internet; | ||
email: internet.email(), | ||
exp: (0, date_fns_1.getUnixTime)(new Date()) + 3600, | ||
}; | ||
@@ -104,3 +100,3 @@ var bearerToken = jsonwebtoken_1.default.sign(bearerTokenDecoded, random.word()); | ||
var _a = (0, test_tools_1.renderHook)(function () { | ||
return (0, index_1.authentication)({ accounts: accounts, api: api }); | ||
return (0, hook_1.default)({ accounts: accounts, api: api }); | ||
}), result = _a.result, unmount = _a.unmount; | ||
@@ -128,7 +124,7 @@ expect(result.current.loading).toBe(true); | ||
var _a = (0, test_tools_1.renderHook)(function () { | ||
return (0, index_1.authentication)({ accounts: accounts, api: api }); | ||
return (0, hook_1.default)({ accounts: accounts, api: api }); | ||
}), result = _a.result, unmount = _a.unmount; | ||
result.current.callAccountsLogin({ | ||
tryLogin: mocks_1.tryLoginFn, | ||
saveRefreshTokenOnCookie: mocks_1.saveRefreshTokenOnCookieFn, | ||
saveRefreshTokenOnSessionStorage: mocks_1.saveRefreshTokenOnSessionStorageFn, | ||
loginResponseDefinitions: loginResponseDefinitions, | ||
@@ -159,3 +155,3 @@ }); | ||
var _a = (0, test_tools_1.renderHook)(function () { | ||
return (0, index_1.authentication)({ accounts: __assign(__assign({}, accounts), { env: mockEnv }), api: api }); | ||
return (0, hook_1.default)({ accounts: __assign(__assign({}, accounts), { env: mockEnv }), api: api }); | ||
}), result = _a.result, unmount = _a.unmount; | ||
@@ -170,8 +166,8 @@ result.current.callAccountsLogout(); | ||
var _a = (0, test_tools_1.renderHook)(function () { | ||
return (0, index_1.authentication)({ accounts: accounts, api: api }); | ||
return (0, hook_1.default)({ accounts: accounts, api: api }); | ||
}), result = _a.result, unmount = _a.unmount; | ||
result.current.tryRefreshToken({ | ||
callAccountsLogout: mocks_1.callAccountsLogoutFn, | ||
eraseRefreshTokenOnCookie: utils_1.eraseRefreshTokenOnCookie, | ||
saveRefreshTokenOnCookie: utils_1.saveRefreshTokenOnCookie, | ||
eraseRefreshTokenOnSessionStorage: utils_1.eraseRefreshTokenOnSessionStorage, | ||
saveRefreshTokenOnSessionStorage: utils_1.saveRefreshTokenOnSessionStorage, | ||
refreshToken: refreshToken, | ||
@@ -185,7 +181,7 @@ refreshResponseDefinitions: refreshResponseDefinitions, | ||
var _a = (0, test_tools_1.renderHook)(function () { | ||
return (0, index_1.authentication)({ accounts: accounts, api: api }); | ||
return (0, hook_1.default)({ accounts: accounts, api: api }); | ||
}), result = _a.result, unmount = _a.unmount; | ||
var tryLoginParamsMock = { | ||
accountsToken: accountsToken, | ||
saveRefreshTokenOnCookie: mocks_1.saveRefreshTokenOnCookieFn, | ||
saveRefreshTokenOnSessionStorage: mocks_1.saveRefreshTokenOnSessionStorageFn, | ||
loginResponseDefinitions: loginResponseDefinitions, | ||
@@ -211,3 +207,3 @@ }; | ||
tryLogin: mocks_1.tryLoginFn, | ||
saveRefreshTokenOnCookie: mocks_1.saveRefreshTokenOnCookieFn, | ||
saveRefreshTokenOnSessionStorage: mocks_1.saveRefreshTokenOnSessionStorageFn, | ||
loginResponseDefinitions: loginResponseDefinitions, | ||
@@ -226,3 +222,3 @@ }); | ||
_a = (0, test_tools_1.renderHook)(function () { | ||
return (0, index_1.authentication)({ accounts: accounts, api: api }); | ||
return (0, hook_1.default)({ accounts: accounts, api: api }); | ||
}), result = _a.result, unmount = _a.unmount; | ||
@@ -232,4 +228,4 @@ jest.spyOn(service_1.default, 'refreshToken').mockRejectedValue(new Error()); | ||
callAccountsLogout: mocks_1.callAccountsLogoutFn, | ||
eraseRefreshTokenOnCookie: mocks_1.eraseAccountsLogoutFn, | ||
saveRefreshTokenOnCookie: mocks_1.saveRefreshTokenOnCookieFn, | ||
eraseRefreshTokenOnSessionStorage: mocks_1.eraseAccountsLogoutFn, | ||
saveRefreshTokenOnSessionStorage: utils_1.saveRefreshTokenOnSessionStorage, | ||
refreshToken: refreshToken, | ||
@@ -247,45 +243,2 @@ refreshResponseDefinitions: refreshResponseDefinitions, | ||
}); }); | ||
it('shoud set bearerTokenDecoded, loading and save refresh token on cookie when try refresh is success', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var _a, result, unmount; | ||
var _b; | ||
return __generator(this, function (_c) { | ||
switch (_c.label) { | ||
case 0: | ||
_a = (0, test_tools_1.renderHook)(function () { | ||
return (0, index_1.authentication)({ accounts: accounts, api: api }); | ||
}), result = _a.result, unmount = _a.unmount; | ||
jest.spyOn(service_1.default, 'refreshToken').mockResolvedValue(__assign(__assign({}, response), { data: (_b = {}, | ||
_b[refreshResponseDefinitions.tokenKey] = bearerToken, | ||
_b[refreshResponseDefinitions.refreshTokenKey] = refreshToken, | ||
_b) })); | ||
jest.spyOn(jsonwebtoken_1.default, 'decode').mockReturnValue(bearerToken); | ||
return [4 /*yield*/, (0, test_tools_1.act)(function () { return __awaiter(void 0, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, result.current.tryRefreshToken({ | ||
callAccountsLogout: mocks_1.callAccountsLogoutFn, | ||
eraseRefreshTokenOnCookie: mocks_1.eraseAccountsLogoutFn, | ||
saveRefreshTokenOnCookie: mocks_1.saveRefreshTokenOnCookieFn, | ||
refreshToken: refreshToken, | ||
refreshResponseDefinitions: refreshResponseDefinitions, | ||
})]; | ||
case 1: | ||
_a.sent(); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); })]; | ||
case 1: | ||
_c.sent(); | ||
expect(mocks_1.callAccountsLogoutFn).not.toBeCalled(); | ||
expect(mocks_1.eraseAccountsLogoutFn).not.toBeCalled(); | ||
expect(mocks_1.saveRefreshTokenOnCookieFn).toBeCalledWith(refreshToken); | ||
expect(result.current.bearerTokenDecoded).toBe(bearerToken); | ||
expect(result.current.bearerToken).toBe(bearerToken); | ||
expect(result.current.loading).toBe(false); | ||
unmount(); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
it('should call tryLogin and get error on call Api.login', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
@@ -297,3 +250,3 @@ var _a, result, unmount; | ||
_a = (0, test_tools_1.renderHook)(function () { | ||
return (0, index_1.authentication)({ accounts: accounts, api: api }); | ||
return (0, hook_1.default)({ accounts: accounts, api: api }); | ||
}), result = _a.result, unmount = _a.unmount; | ||
@@ -307,3 +260,3 @@ jest.spyOn(service_1.default, 'login').mockRejectedValue(new Error()); | ||
accountsToken: accountsToken, | ||
saveRefreshTokenOnCookie: mocks_1.saveRefreshTokenOnCookieFn, | ||
saveRefreshTokenOnSessionStorage: mocks_1.saveRefreshTokenOnSessionStorageFn, | ||
loginResponseDefinitions: loginResponseDefinitions, | ||
@@ -319,3 +272,3 @@ })]; | ||
_b.sent(); | ||
expect(mocks_1.saveRefreshTokenOnCookieFn).not.toHaveBeenCalled(); | ||
expect(mocks_1.saveRefreshTokenOnSessionStorageFn).not.toHaveBeenCalled(); | ||
expect(result.current.loading).toBe(false); | ||
@@ -334,3 +287,3 @@ unmount(); | ||
_a = (0, test_tools_1.renderHook)(function () { | ||
return (0, index_1.authentication)({ accounts: accounts, api: api }); | ||
return (0, hook_1.default)({ accounts: accounts, api: api }); | ||
}), result = _a.result, unmount = _a.unmount; | ||
@@ -347,3 +300,3 @@ jest.spyOn(service_1.default, 'login').mockResolvedValue(__assign(__assign({}, response), { data: (_b = {}, | ||
accountsToken: accountsToken, | ||
saveRefreshTokenOnCookie: mocks_1.saveRefreshTokenOnCookieFn, | ||
saveRefreshTokenOnSessionStorage: mocks_1.saveRefreshTokenOnSessionStorageFn, | ||
loginResponseDefinitions: loginResponseDefinitions, | ||
@@ -359,3 +312,3 @@ })]; | ||
_c.sent(); | ||
expect(mocks_1.saveRefreshTokenOnCookieFn).toBeCalledWith(refreshToken); | ||
expect(mocks_1.saveRefreshTokenOnSessionStorageFn).toBeCalledWith(refreshToken); | ||
expect(result.current.bearerTokenDecoded).toBe(bearerTokenDecoded); | ||
@@ -369,39 +322,2 @@ expect(result.current.bearerToken).toBe(bearerToken); | ||
}); }); | ||
it('should call initBearerInterceptor', function () { | ||
var _a; | ||
var _b = (0, test_tools_1.renderHook)(function () { | ||
return (0, index_1.authentication)({ accounts: accounts, api: api }); | ||
}), result = _b.result, unmount = _b.unmount; | ||
var mockFunction = jest.fn(); | ||
jest.spyOn(interceptors_1.default, 'bearer').mockImplementation(mockFunction); | ||
(_a = result.current.initInterceptors) === null || _a === void 0 ? void 0 : _a.bearer(axios_1.default.interceptors.request); | ||
expect(mockFunction).toBeCalled(); | ||
unmount(); | ||
}); | ||
it('should call initRefreshTokenInterceptor', function () { | ||
var _a; | ||
var _b = (0, test_tools_1.renderHook)(function () { | ||
return (0, index_1.authentication)({ accounts: accounts, api: api }); | ||
}), result = _b.result, unmount = _b.unmount; | ||
var mockFunction = jest.fn(); | ||
(0, utils_1.saveRefreshTokenOnCookie)('1234'); | ||
jest.spyOn(interceptors_1.default, 'refresh').mockImplementation(mockFunction); | ||
(_a = result.current.initInterceptors) === null || _a === void 0 ? void 0 : _a.refresh({ | ||
_interceptor: axios_1.default.interceptors.request, | ||
bearerExpirationTimestamp: bearerTokenDecoded.exp, | ||
}); | ||
expect(mockFunction).toBeCalled(); | ||
unmount(); | ||
}); | ||
it('should call initLogoutInterceptor', function () { | ||
var _a; | ||
var _b = (0, test_tools_1.renderHook)(function () { | ||
return (0, index_1.authentication)({ accounts: accounts, api: api }); | ||
}), result = _b.result, unmount = _b.unmount; | ||
var mockFunction = jest.fn(); | ||
jest.spyOn(interceptors_1.default, 'logout').mockImplementation(mockFunction); | ||
(_a = result.current.initInterceptors) === null || _a === void 0 ? void 0 : _a.logout(axios_1.default.interceptors.response); | ||
expect(mockFunction).toBeCalled(); | ||
unmount(); | ||
}); | ||
}); |
@@ -1,3 +0,1 @@ | ||
export * from './context'; | ||
export { default as authentication } from './hook'; | ||
export type { AuthProviderConfig } from './types'; | ||
export * from './exports'; |
"use strict"; | ||
// Durante o desenvolvimento da aplicação, para se testar | ||
// descomente o código abaixo e execute "yarn start" | ||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
@@ -12,9 +14,19 @@ if (k2 === undefined) k2 = k; | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.authentication = void 0; | ||
__exportStar(require("./context"), exports); | ||
var hook_1 = require("./hook"); | ||
Object.defineProperty(exports, "authentication", { enumerable: true, get: function () { return __importDefault(hook_1).default; } }); | ||
/* import React from 'react'; | ||
import ReactDOM from 'react-dom'; | ||
import { AuthProvider } from './context'; | ||
import App from './client/app'; | ||
import { config } from './client/config'; | ||
ReactDOM.render( | ||
<React.StrictMode> | ||
<AuthProvider config={config}> | ||
<App /> | ||
</AuthProvider> | ||
</React.StrictMode>, | ||
document.getElementById('root') | ||
); */ | ||
__exportStar(require("./exports"), exports); |
@@ -1,14 +0,10 @@ | ||
import { AxiosError, AxiosRequestConfig } from 'axios'; | ||
import { InitializeBearerInterceptorConfig, InitializeTryRefreshRequestInterceptorConfig, InitializeLogoutResponseInterceptorConfig, AddBearerOnHeadersProps, CleanUpInterceptorsProps, JoinCallbackBearerInterceptorConfig, AddUpdateTokenOnRefresh, CallLogoutWhenUnauthorized } from './types'; | ||
import { AxiosRequestConfig } from 'axios'; | ||
import { InitializeBearerInterceptorConfig, AddBearerOnHeadersProps, CleanUpInterceptorsProps, JoinCallbackBearerInterceptorConfig } from './types'; | ||
declare const cleanUpInterceptor: ({ countGlobalInterceptorCreation, interceptor, }: CleanUpInterceptorsProps) => void; | ||
declare const addBearerOnRequestHeaders: ({ req, bearer, }: AddBearerOnHeadersProps) => AxiosRequestConfig<any>; | ||
declare const callUpdateTokenIfNecessary: ({ req, bearerExpirationTimestamp, updateToken, }: AddUpdateTokenOnRefresh) => AxiosRequestConfig<any>; | ||
declare const callLogoutWhenUnauthorized: ({ error, logout, conditionToLogout, }: CallLogoutWhenUnauthorized) => AxiosError; | ||
declare const joinCallbackOnBearer: ({ bearer, interceptor, callback, }: JoinCallbackBearerInterceptorConfig) => void; | ||
declare const addBearerOnRequestHeaders: ({ req, bearer, }: AddBearerOnHeadersProps) => AxiosRequestConfig; | ||
declare const joinCallbackOnBearer: ({ bearer, interceptors, callback, tryRefreshToken, logout, activeInterceptors, }: JoinCallbackBearerInterceptorConfig) => void; | ||
declare const interceptors: { | ||
bearer: ({ bearer, interceptor, }: InitializeBearerInterceptorConfig) => void; | ||
refresh: ({ bearerExpirationTimestamp, updateToken, interceptor, }: InitializeTryRefreshRequestInterceptorConfig) => void; | ||
logout: ({ interceptor, logout, }: InitializeLogoutResponseInterceptorConfig) => void; | ||
bearer: ({ bearer, interceptors, tryRefreshToken, logout, activeInterceptors, }: InitializeBearerInterceptorConfig) => void; | ||
}; | ||
export default interceptors; | ||
export { addBearerOnRequestHeaders, cleanUpInterceptor, joinCallbackOnBearer, callUpdateTokenIfNecessary, callLogoutWhenUnauthorized, }; | ||
export { addBearerOnRequestHeaders, cleanUpInterceptor, joinCallbackOnBearer }; |
@@ -13,8 +13,47 @@ "use strict"; | ||
}; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (_) try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.callLogoutWhenUnauthorized = exports.callUpdateTokenIfNecessary = exports.joinCallbackOnBearer = exports.cleanUpInterceptor = exports.addBearerOnRequestHeaders = void 0; | ||
var utils_1 = require("./utils"); | ||
var bearerInterceptor = null; | ||
var refreshInterceptor = null; | ||
var logoutInterceptor = null; | ||
exports.joinCallbackOnBearer = exports.cleanUpInterceptor = exports.addBearerOnRequestHeaders = void 0; | ||
var axios_1 = __importDefault(require("axios")); | ||
var bearerRequestInterceptor = null; | ||
var bearerResponseInterceptor = null; | ||
var retryRefresh = 0; | ||
var cleanUpInterceptor = function (_a) { | ||
@@ -33,30 +72,18 @@ var countGlobalInterceptorCreation = _a.countGlobalInterceptorCreation, interceptor = _a.interceptor; | ||
exports.addBearerOnRequestHeaders = addBearerOnRequestHeaders; | ||
var callUpdateTokenIfNecessary = function (_a) { | ||
var req = _a.req, bearerExpirationTimestamp = _a.bearerExpirationTimestamp, updateToken = _a.updateToken; | ||
if (updateToken && | ||
bearerExpirationTimestamp && | ||
(0, utils_1.isTimestampExpiredWithAntecipation)({ | ||
timestampExpiration: bearerExpirationTimestamp, | ||
antecipation: 60, | ||
})) { | ||
updateToken(); | ||
} | ||
return __assign({}, req); | ||
}; | ||
exports.callUpdateTokenIfNecessary = callUpdateTokenIfNecessary; | ||
var callLogoutWhenUnauthorized = function (_a) { | ||
var error = _a.error, logout = _a.logout, conditionToLogout = _a.conditionToLogout; | ||
if (conditionToLogout && logout) { | ||
logout(); | ||
} | ||
return error; | ||
}; | ||
exports.callLogoutWhenUnauthorized = callLogoutWhenUnauthorized; | ||
var joinCallbackOnBearer = function (_a) { | ||
var bearer = _a.bearer, interceptor = _a.interceptor, callback = _a.callback; | ||
var bearer = _a.bearer, interceptors = _a.interceptors, callback = _a.callback, tryRefreshToken = _a.tryRefreshToken, logout = _a.logout, activeInterceptors = _a.activeInterceptors; | ||
cleanUpInterceptor({ | ||
countGlobalInterceptorCreation: bearerInterceptor, | ||
interceptor: interceptor, | ||
countGlobalInterceptorCreation: bearerRequestInterceptor, | ||
interceptor: interceptors.request, | ||
}); | ||
bearerInterceptor = interceptor.use(function (req) { | ||
bearerRequestInterceptor = interceptors.request.use(function (req) { | ||
var _a, _b; | ||
if ((activeInterceptors === null || activeInterceptors === void 0 ? void 0 : activeInterceptors.addBearerOnAllRequests) === false) | ||
return; | ||
if ((_a = req === null || req === void 0 ? void 0 : req.headers) === null || _a === void 0 ? void 0 : _a.Authorization) { | ||
return callback({ | ||
req: req, | ||
bearer: (_b = req === null || req === void 0 ? void 0 : req.headers) === null || _b === void 0 ? void 0 : _b.Authorization, | ||
}); | ||
} | ||
return callback({ | ||
@@ -67,60 +94,44 @@ bearer: bearer, | ||
}); | ||
cleanUpInterceptor({ | ||
countGlobalInterceptorCreation: bearerResponseInterceptor, | ||
interceptor: interceptors.response, | ||
}); | ||
bearerResponseInterceptor = interceptors.response.use(undefined, function (error) { return __awaiter(void 0, void 0, void 0, function () { | ||
var newBearer, originalRequest; | ||
var _a; | ||
return __generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
if (((_a = error.response) === null || _a === void 0 ? void 0 : _a.status) !== 401) { | ||
return [2 /*return*/, Promise.reject(error)]; | ||
} | ||
if (!(retryRefresh < 3 && | ||
(activeInterceptors === null || activeInterceptors === void 0 ? void 0 : activeInterceptors.refreshWhenBearerTokenIsExpired) !== false)) return [3 /*break*/, 2]; | ||
retryRefresh = retryRefresh + 1; | ||
return [4 /*yield*/, tryRefreshToken()]; | ||
case 1: | ||
newBearer = _b.sent(); | ||
originalRequest = __assign(__assign({}, error.config), { headers: __assign(__assign({}, error.config.headers), { Authorization: "" + newBearer }) }); | ||
axios_1.default.request(originalRequest); | ||
return [3 /*break*/, 3]; | ||
case 2: | ||
Promise.reject(error); | ||
(activeInterceptors === null || activeInterceptors === void 0 ? void 0 : activeInterceptors.logoutWhenResponseIsUnauthorized) !== false && | ||
(logout === null || logout === void 0 ? void 0 : logout()); | ||
_b.label = 3; | ||
case 3: return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
}; | ||
exports.joinCallbackOnBearer = joinCallbackOnBearer; | ||
var bearer = function (_a) { | ||
var bearer = _a.bearer, interceptor = _a.interceptor; | ||
cleanUpInterceptor({ | ||
countGlobalInterceptorCreation: bearerInterceptor, | ||
interceptor: interceptor, | ||
}); | ||
var bearer = _a.bearer, interceptors = _a.interceptors, tryRefreshToken = _a.tryRefreshToken, logout = _a.logout, activeInterceptors = _a.activeInterceptors; | ||
joinCallbackOnBearer({ | ||
bearer: bearer, | ||
interceptor: interceptor, | ||
interceptors: interceptors, | ||
callback: addBearerOnRequestHeaders, | ||
}); | ||
}; | ||
var joinCallbackOnRefresh = function (_a) { | ||
var bearerExpirationTimestamp = _a.bearerExpirationTimestamp, updateToken = _a.updateToken, interceptor = _a.interceptor, callback = _a.callback; | ||
cleanUpInterceptor({ | ||
countGlobalInterceptorCreation: refreshInterceptor, | ||
interceptor: interceptor, | ||
}); | ||
refreshInterceptor = interceptor.use(function (req) { | ||
return callback({ | ||
req: req, | ||
bearerExpirationTimestamp: bearerExpirationTimestamp, | ||
updateToken: updateToken, | ||
}); | ||
}); | ||
}; | ||
var refresh = function (_a) { | ||
var bearerExpirationTimestamp = _a.bearerExpirationTimestamp, updateToken = _a.updateToken, interceptor = _a.interceptor; | ||
joinCallbackOnRefresh({ | ||
bearerExpirationTimestamp: bearerExpirationTimestamp, | ||
callback: callUpdateTokenIfNecessary, | ||
interceptor: interceptor, | ||
updateToken: updateToken, | ||
}); | ||
}; | ||
var joinCallbackOnLogout = function (_a) { | ||
var interceptor = _a.interceptor, logout = _a.logout, callback = _a.callback; | ||
cleanUpInterceptor({ | ||
countGlobalInterceptorCreation: logoutInterceptor, | ||
interceptor: interceptor, | ||
}); | ||
logoutInterceptor = interceptor.use(function (res) { return res; }, function (err) { | ||
var _a; | ||
return callback({ | ||
error: err, | ||
logout: logout, | ||
conditionToLogout: ((_a = err.response) === null || _a === void 0 ? void 0 : _a.status) === 401, | ||
}); | ||
}); | ||
}; | ||
var logout = function (_a) { | ||
var interceptor = _a.interceptor, logout = _a.logout; | ||
joinCallbackOnLogout({ | ||
interceptor: interceptor, | ||
tryRefreshToken: tryRefreshToken, | ||
logout: logout, | ||
callback: callLogoutWhenUnauthorized, | ||
activeInterceptors: activeInterceptors, | ||
}); | ||
@@ -130,5 +141,3 @@ }; | ||
bearer: bearer, | ||
refresh: refresh, | ||
logout: logout, | ||
}; | ||
exports.default = interceptors; |
@@ -62,3 +62,2 @@ "use strict"; | ||
var axios_1 = __importDefault(require("axios")); | ||
var date_fns_1 = require("date-fns"); | ||
var interceptors_1 = __importStar(require("./interceptors")); | ||
@@ -78,54 +77,2 @@ jest.mock('axios'); | ||
}); | ||
it('should call update token if necessary', function () { | ||
var mockedExpiredTimestamp = (0, date_fns_1.getUnixTime)(new Date()) - 1000; | ||
var updateTokenFn = jest.fn(); | ||
var req = (0, interceptors_1.callUpdateTokenIfNecessary)({ | ||
req: {}, | ||
bearerExpirationTimestamp: mockedExpiredTimestamp, | ||
updateToken: updateTokenFn, | ||
}); | ||
expect(req).toBeDefined(); | ||
expect(updateTokenFn).toHaveBeenCalled(); | ||
}); | ||
it('should not call update token if not necessary', function () { | ||
var mockedNotExpiredTimestamp = (0, date_fns_1.getUnixTime)((0, date_fns_1.addDays)(new Date(), 2)); | ||
var updateTokenFn = jest.fn(); | ||
var req = (0, interceptors_1.callUpdateTokenIfNecessary)({ | ||
req: {}, | ||
bearerExpirationTimestamp: mockedNotExpiredTimestamp, | ||
updateToken: updateTokenFn, | ||
}); | ||
expect(req).toBeDefined(); | ||
expect(updateTokenFn).not.toHaveBeenCalled(); | ||
}); | ||
it('should call logout when unauthorized', function () { | ||
var logoutFn = jest.fn(); | ||
var error = { | ||
response: { | ||
status: 401, | ||
}, | ||
}; | ||
var req = (0, interceptors_1.callLogoutWhenUnauthorized)({ | ||
error: error, | ||
logout: logoutFn, | ||
conditionToLogout: error.response.status === 401, | ||
}); | ||
expect(req).toBeDefined(); | ||
expect(logoutFn).toHaveBeenCalled(); | ||
}); | ||
it('should not call logout when is other error than 401', function () { | ||
var logoutFn = jest.fn(); | ||
var error = { | ||
response: { | ||
status: 400, | ||
}, | ||
}; | ||
var req = (0, interceptors_1.callLogoutWhenUnauthorized)({ | ||
error: error, | ||
logout: logoutFn, | ||
conditionToLogout: error.response.status === 401, | ||
}); | ||
expect(req).toBeDefined(); | ||
expect(logoutFn).not.toHaveBeenCalled(); | ||
}); | ||
it('should clean up interceptor works properly', function () { | ||
@@ -144,3 +91,5 @@ var interceptor = axios_1.default.interceptors.request; | ||
bearer: '1234', | ||
interceptor: axios_1.default.interceptors.request, | ||
interceptors: axios_1.default.interceptors, | ||
logout: jest.fn(), | ||
tryRefreshToken: jest.fn(), | ||
}); | ||
@@ -151,18 +100,2 @@ expect(axios_1.default.interceptors.request.use).toHaveBeenCalled(); | ||
}); }); | ||
it('should be able to initialize the refresh interceptor', function () { | ||
interceptors_1.default.refresh({ | ||
interceptor: axios_1.default.interceptors.request, | ||
bearerExpirationTimestamp: new Date().getTime(), | ||
updateToken: jest.fn(), | ||
}); | ||
expect(axios_1.default.interceptors.request.use).toHaveBeenCalled(); | ||
}); | ||
it('should be able to initialize the logout interceptor', function () { | ||
var logoutFn = jest.fn(); | ||
interceptors_1.default.logout({ | ||
interceptor: axios_1.default.interceptors.response, | ||
logout: logoutFn, | ||
}); | ||
expect(axios_1.default.interceptors.response.use).toHaveBeenCalled(); | ||
}); | ||
}); |
@@ -10,3 +10,3 @@ /// <reference types="jest" /> | ||
declare const eraseAccountsLogoutFn: jest.Mock<any, any>; | ||
declare const saveRefreshTokenOnCookieFn: jest.Mock<any, any>; | ||
declare const saveRefreshTokenOnSessionStorageFn: jest.Mock<any, any>; | ||
declare const tryRefreshTokenFn: jest.Mock<any, any>; | ||
@@ -48,2 +48,2 @@ declare const callAccountsLoginFn: jest.Mock<any, any>; | ||
declare const refreshService: RefreshServiceType; | ||
export { mockUrl, subscribeFn, logoutFn, authenticationSpy, loginFn, tryLoginFn, replaceStateFn, callAccountsLogoutFn, eraseAccountsLogoutFn, saveRefreshTokenOnCookieFn, AuthProviderPropsMock, tryRefreshTokenFn, callAccountsLoginFn, loginService, refreshService, }; | ||
export { mockUrl, subscribeFn, logoutFn, authenticationSpy, loginFn, tryLoginFn, replaceStateFn, callAccountsLogoutFn, eraseAccountsLogoutFn, saveRefreshTokenOnSessionStorageFn, AuthProviderPropsMock, tryRefreshTokenFn, callAccountsLoginFn, loginService, refreshService, }; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.refreshService = exports.loginService = exports.callAccountsLoginFn = exports.tryRefreshTokenFn = exports.AuthProviderPropsMock = exports.saveRefreshTokenOnCookieFn = exports.eraseAccountsLogoutFn = exports.callAccountsLogoutFn = exports.replaceStateFn = exports.tryLoginFn = exports.loginFn = exports.authenticationSpy = exports.logoutFn = exports.subscribeFn = exports.mockUrl = void 0; | ||
exports.refreshService = exports.loginService = exports.callAccountsLoginFn = exports.tryRefreshTokenFn = exports.AuthProviderPropsMock = exports.saveRefreshTokenOnSessionStorageFn = exports.eraseAccountsLogoutFn = exports.callAccountsLogoutFn = exports.replaceStateFn = exports.tryLoginFn = exports.loginFn = exports.authenticationSpy = exports.logoutFn = exports.subscribeFn = exports.mockUrl = void 0; | ||
var test_tools_1 = require("./test.tools"); | ||
@@ -20,4 +20,4 @@ var internet = test_tools_1.faker.internet; | ||
exports.eraseAccountsLogoutFn = eraseAccountsLogoutFn; | ||
var saveRefreshTokenOnCookieFn = jest.fn(); | ||
exports.saveRefreshTokenOnCookieFn = saveRefreshTokenOnCookieFn; | ||
var saveRefreshTokenOnSessionStorageFn = jest.fn(); | ||
exports.saveRefreshTokenOnSessionStorageFn = saveRefreshTokenOnSessionStorageFn; | ||
var tryRefreshTokenFn = jest.fn(); | ||
@@ -24,0 +24,0 @@ exports.tryRefreshTokenFn = tryRefreshTokenFn; |
@@ -1,1 +0,1 @@ | ||
import "@testing-library/jest-dom"; | ||
import '@testing-library/jest-dom'; |
/// <reference types="react" /> | ||
import { AxiosInterceptorManager, AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios'; | ||
import { AxiosInterceptorManager, AxiosRequestConfig, AxiosResponse } from 'axios'; | ||
declare module 'axios' { | ||
@@ -32,2 +32,6 @@ interface AxiosInstance { | ||
}; | ||
export declare type InitInterceptors = { | ||
_interceptors: AxiosInterceptors; | ||
active?: ActiveInterceptors; | ||
}; | ||
export declare type BackOfficeConfigType = { | ||
@@ -105,5 +109,3 @@ urlParam: string; | ||
initInterceptors: { | ||
bearer: (interceptors: AxiosInterceptorManager<AxiosRequestConfig>) => void; | ||
refresh: (params: InitRefreshTokenInterceptor) => void; | ||
logout: (interceptors: AxiosInterceptorManager<AxiosResponse<any>>) => void; | ||
bearer: (params: InitInterceptors) => void; | ||
} | null; | ||
@@ -128,3 +130,3 @@ clientInterceptorsInitialize: InitializeAxiosInterceptors | null; | ||
tryLogin: (params: TryLoginParams) => void; | ||
saveRefreshTokenOnCookie: (refreshToken: string) => void; | ||
saveRefreshTokenOnSessionStorage: (refreshToken: string) => void; | ||
loginResponseDefinitions: LoginResponseServiceType; | ||
@@ -134,5 +136,5 @@ }; | ||
callAccountsLogout: () => void; | ||
eraseRefreshTokenOnCookie: () => void; | ||
saveRefreshTokenOnCookie: (newRefreshToken: string) => void; | ||
refreshToken: string | undefined; | ||
eraseRefreshTokenOnSessionStorage: () => void; | ||
saveRefreshTokenOnSessionStorage: (newRefreshToken: string) => void; | ||
refreshToken: string | null; | ||
refreshResponseDefinitions: RefreshResponseServiceType; | ||
@@ -143,10 +145,5 @@ }; | ||
accountsToken: AccountsToken; | ||
saveRefreshTokenOnCookie: (refreshToken: string) => void; | ||
saveRefreshTokenOnSessionStorage: (refreshToken: string) => void; | ||
loginResponseDefinitions: LoginResponseServiceType; | ||
}; | ||
export declare type InitializeTryRefreshRequestInterceptorConfig = { | ||
bearerExpirationTimestamp: number | null; | ||
updateToken: (() => void) | null; | ||
interceptor: AxiosInterceptorManager<AxiosRequestConfig>; | ||
}; | ||
export declare type CallLogoutWhenUnauthorized = { | ||
@@ -158,7 +155,7 @@ error: any; | ||
export declare type AddBearerOnHeadersProps = { | ||
req: AxiosRequestConfig<any>; | ||
req: AxiosRequestConfig; | ||
bearer: string | null; | ||
}; | ||
export declare type AddUpdateTokenOnRefresh = { | ||
req: AxiosRequestConfig<any>; | ||
req: AxiosRequestConfig; | ||
bearerExpirationTimestamp: number | null; | ||
@@ -169,23 +166,19 @@ updateToken: (() => void) | null; | ||
bearer: string | null; | ||
interceptor: AxiosInterceptorManager<AxiosRequestConfig>; | ||
callback: (param: AddBearerOnHeadersProps) => AxiosRequestConfig<any>; | ||
interceptors: AxiosInterceptors; | ||
callback: (param: AddBearerOnHeadersProps) => AxiosRequestConfig; | ||
tryRefreshToken: () => Promise<string | null>; | ||
logout: (() => void) | null; | ||
activeInterceptors?: ActiveInterceptors; | ||
}; | ||
export declare type JoinCallbackOnRefresh = InitializeTryRefreshRequestInterceptorConfig & { | ||
callback: (params: AddUpdateTokenOnRefresh) => AxiosRequestConfig<any>; | ||
}; | ||
export declare type JoinCallbackOnLogout = InitializeLogoutResponseInterceptorConfig & { | ||
callback: (params: CallLogoutWhenUnauthorized) => AxiosError; | ||
}; | ||
export declare type InitializeBearerInterceptorConfig = { | ||
bearer: string | null; | ||
interceptor: AxiosInterceptorManager<AxiosRequestConfig>; | ||
interceptors: AxiosInterceptors; | ||
tryRefreshToken: () => Promise<string | null>; | ||
logout: (() => void) | null; | ||
activeInterceptors?: ActiveInterceptors; | ||
}; | ||
export declare type CleanUpInterceptorsProps = { | ||
countGlobalInterceptorCreation: number | null; | ||
interceptor: AxiosInterceptorManager<AxiosRequestConfig<any>>; | ||
interceptor: AxiosInterceptorManager<AxiosRequestConfig>; | ||
}; | ||
export declare type InitializeLogoutResponseInterceptorConfig = { | ||
logout: (() => void) | null; | ||
interceptor: AxiosInterceptorManager<AxiosResponse<any>>; | ||
}; | ||
export declare type AxiosInterceptors = { | ||
@@ -195,16 +188,13 @@ request: AxiosInterceptorManager<AxiosRequestConfig>; | ||
}; | ||
export declare type ActiveInterceptors = { | ||
addBearerOnAllRequests?: boolean; | ||
refreshWhenBearerTokenIsExpired?: boolean; | ||
logoutWhenResponseIsUnauthorized?: boolean; | ||
}; | ||
export declare type InitializeAxiosInterceptors = { | ||
interceptors: AxiosInterceptors; | ||
active?: { | ||
addBearerOnAllRequests?: boolean; | ||
refreshWhenBearerTokenIsExpired?: boolean; | ||
logoutWhenResponseIsUnauthorized?: boolean; | ||
}; | ||
active?: ActiveInterceptors; | ||
}; | ||
export declare type IsTimestampExpiredWithAntecipation = { | ||
timestampExpiration: number; | ||
antecipation: number; | ||
}; | ||
export declare type TryRefreshTokenCallback = { | ||
token: string | undefined; | ||
token: string | null; | ||
tryRefreshToken: (params: TryRefreshTokenParams) => Promise<void>; | ||
@@ -214,3 +204,3 @@ tryRefreshTokenParams: TryRefreshTokenParams; | ||
export declare type RefreshOrLogin = { | ||
refreshToken?: string; | ||
refreshToken: string | null; | ||
isSupport: boolean; | ||
@@ -220,5 +210,1 @@ callbackRefresh: () => void; | ||
}; | ||
export declare type InitRefreshTokenInterceptor = { | ||
_interceptor: AxiosInterceptorManager<AxiosRequestConfig>; | ||
bearerExpirationTimestamp: number | null; | ||
}; |
@@ -1,9 +0,6 @@ | ||
import { IsTimestampExpiredWithAntecipation } from './types'; | ||
declare function getRefreshTokenFromCookie(): string | undefined; | ||
declare function saveRefreshTokenOnCookie(refreshToken: string): void; | ||
declare function eraseRefreshTokenOnCookie(): void; | ||
declare function getRefreshTokenFromSessionStorage(): string | null; | ||
declare function saveRefreshTokenOnSessionStorage(refreshToken: string): void; | ||
declare function eraseRefreshTokenOnSessionStorage(): void; | ||
declare function findTarget(mapData: undefined | string, apiResultData: any): any; | ||
declare function isComingFromBackOffice(urlParam: string | null | undefined): boolean; | ||
declare function isTimestampExpired(timestampExpiration: number): boolean; | ||
declare function isTimestampExpiredWithAntecipation({ timestampExpiration, antecipation, }: IsTimestampExpiredWithAntecipation): boolean; | ||
export { getRefreshTokenFromCookie, saveRefreshTokenOnCookie, eraseRefreshTokenOnCookie, findTarget, isComingFromBackOffice, isTimestampExpired, isTimestampExpiredWithAntecipation, }; | ||
export { findTarget, isComingFromBackOffice, getRefreshTokenFromSessionStorage, saveRefreshTokenOnSessionStorage, eraseRefreshTokenOnSessionStorage, }; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.isTimestampExpiredWithAntecipation = exports.isTimestampExpired = exports.isComingFromBackOffice = exports.findTarget = exports.eraseRefreshTokenOnCookie = exports.saveRefreshTokenOnCookie = exports.getRefreshTokenFromCookie = void 0; | ||
var date_fns_1 = require("date-fns"); | ||
function getRefreshTokenFromCookie() { | ||
var _a; | ||
var value = "; " + document.cookie; | ||
var parts = value.split("; " + 'refreshToken' + "="); | ||
if (parts.length === 2) | ||
return (_a = parts.pop()) === null || _a === void 0 ? void 0 : _a.split(';').shift(); | ||
exports.eraseRefreshTokenOnSessionStorage = exports.saveRefreshTokenOnSessionStorage = exports.getRefreshTokenFromSessionStorage = exports.isComingFromBackOffice = exports.findTarget = void 0; | ||
function getRefreshTokenFromSessionStorage() { | ||
return sessionStorage.getItem('refreshToken'); | ||
} | ||
exports.getRefreshTokenFromCookie = getRefreshTokenFromCookie; | ||
function saveRefreshTokenOnCookie(refreshToken) { | ||
document.cookie = "refreshToken=" + refreshToken + "; path=/; expires=Session"; | ||
exports.getRefreshTokenFromSessionStorage = getRefreshTokenFromSessionStorage; | ||
function saveRefreshTokenOnSessionStorage(refreshToken) { | ||
sessionStorage.setItem('refreshToken', refreshToken); | ||
} | ||
exports.saveRefreshTokenOnCookie = saveRefreshTokenOnCookie; | ||
function eraseRefreshTokenOnCookie() { | ||
document.cookie = 'refreshToken= ; expires = Thu, 01 Jan 1970 00:00:00 GMT'; | ||
exports.saveRefreshTokenOnSessionStorage = saveRefreshTokenOnSessionStorage; | ||
function eraseRefreshTokenOnSessionStorage() { | ||
sessionStorage.removeItem('refreshToken'); | ||
} | ||
exports.eraseRefreshTokenOnCookie = eraseRefreshTokenOnCookie; | ||
exports.eraseRefreshTokenOnSessionStorage = eraseRefreshTokenOnSessionStorage; | ||
function findTarget(mapData, apiResultData) { | ||
return ((mapData === null || mapData === void 0 ? void 0 : mapData.split('.').reduce(function (acc, curr) { | ||
return (acc === null || acc === void 0 ? void 0 : acc[curr]) || apiResultData[curr]; | ||
var _a; | ||
return ((_a = acc) === null || _a === void 0 ? void 0 : _a[curr]) || apiResultData[curr]; | ||
}, {})) || apiResultData); | ||
@@ -36,18 +32,1 @@ } | ||
exports.isComingFromBackOffice = isComingFromBackOffice; | ||
function isTimestampExpired(timestampExpiration) { | ||
var timestampNow = (0, date_fns_1.getUnixTime)(new Date()); | ||
if (timestampExpiration <= timestampNow) { | ||
return true; | ||
} | ||
return false; | ||
} | ||
exports.isTimestampExpired = isTimestampExpired; | ||
function isTimestampExpiredWithAntecipation(_a) { | ||
var timestampExpiration = _a.timestampExpiration, antecipation = _a.antecipation; | ||
var timestampNow = (0, date_fns_1.getUnixTime)(new Date()); | ||
if (timestampExpiration - antecipation <= timestampNow) { | ||
return true; | ||
} | ||
return false; | ||
} | ||
exports.isTimestampExpiredWithAntecipation = isTimestampExpiredWithAntecipation; |
@@ -15,3 +15,2 @@ "use strict"; | ||
var test_tools_1 = require("./test.tools"); | ||
var date_fns_1 = require("date-fns"); | ||
var utils_1 = require("./utils"); | ||
@@ -22,19 +21,4 @@ var random = test_tools_1.faker.random; | ||
beforeEach(function () { | ||
(0, utils_1.saveRefreshTokenOnCookie)(initialState); | ||
(0, utils_1.saveRefreshTokenOnSessionStorage)(initialState); | ||
}); | ||
var oneDayInSeconds = 86400; | ||
var oneHourInSeconds = 3600; | ||
var tenSecondsInSeconds = 10; | ||
it('should get refresh token on cookie', function () { | ||
expect((0, utils_1.getRefreshTokenFromCookie)()).toBe(initialState); | ||
}); | ||
it('should set refresh token cookie', function () { | ||
var refreshToken = random.word(); | ||
(0, utils_1.saveRefreshTokenOnCookie)(refreshToken); | ||
expect((0, utils_1.getRefreshTokenFromCookie)()).toBe(refreshToken); | ||
}); | ||
it('should erase refresh token on cookie', function () { | ||
(0, utils_1.eraseRefreshTokenOnCookie)(); | ||
expect((0, utils_1.getRefreshTokenFromCookie)()).toBe(undefined); | ||
}); | ||
it('should pass mapData as data.dados.0.map.0 and return mapped object', function () { | ||
@@ -136,52 +120,36 @@ var mapData = 'data.dados.0.map.0'; | ||
}); | ||
it('should return true if timestamp is expired', function () { | ||
var yesterday = (0, date_fns_1.getUnixTime)((0, date_fns_1.subDays)(new Date(), 1)); | ||
var oneHourAgo = (0, date_fns_1.getUnixTime)((0, date_fns_1.subHours)(new Date(), 1)); | ||
var tenSecondsAgo = (0, date_fns_1.getUnixTime)((0, date_fns_1.subSeconds)(new Date(), 10)); | ||
expect((0, utils_1.isTimestampExpired)(yesterday)).toBe(true); | ||
expect((0, utils_1.isTimestampExpired)(oneHourAgo)).toBe(true); | ||
expect((0, utils_1.isTimestampExpired)(tenSecondsAgo)).toBe(true); | ||
it('getRefreshTokenFromSessionStorage', function () { | ||
var refreshToken = random.word(); | ||
Object.assign(window.location, { | ||
pathname: '/other-path', | ||
}); | ||
sessionStorage.setItem('refreshToken', refreshToken); | ||
expect((0, utils_1.getRefreshTokenFromSessionStorage)()).toBe(refreshToken); | ||
}); | ||
it('should return true if timestamp is expired with antecipation', function () { | ||
var tommorrow = (0, date_fns_1.getUnixTime)((0, date_fns_1.addDays)(new Date(), 1)); | ||
var oneHourFromNow = (0, date_fns_1.getUnixTime)((0, date_fns_1.addHours)(new Date(), 1)); | ||
var tenSecondsFromNow = (0, date_fns_1.getUnixTime)((0, date_fns_1.addSeconds)(new Date(), 10)); | ||
expect((0, utils_1.isTimestampExpiredWithAntecipation)({ | ||
timestampExpiration: tommorrow, | ||
antecipation: oneDayInSeconds, | ||
})).toBe(true); | ||
expect((0, utils_1.isTimestampExpiredWithAntecipation)({ | ||
timestampExpiration: oneHourFromNow, | ||
antecipation: oneHourInSeconds, | ||
})).toBe(true); | ||
expect((0, utils_1.isTimestampExpiredWithAntecipation)({ | ||
timestampExpiration: tenSecondsFromNow, | ||
antecipation: tenSecondsInSeconds, | ||
})); | ||
it('saveRefreshTokenOnSessionStorage', function () { | ||
var refreshToken = random.word(); | ||
(0, utils_1.saveRefreshTokenOnSessionStorage)(refreshToken); | ||
expect(sessionStorage.getItem('refreshToken')).toBe(refreshToken); | ||
}); | ||
it('should return false if timestamp is not expired', function () { | ||
var tommorrow = (0, date_fns_1.getUnixTime)((0, date_fns_1.addDays)(new Date(), 1)); | ||
var oneHourFromNow = (0, date_fns_1.getUnixTime)((0, date_fns_1.addHours)(new Date(), 1)); | ||
var tenSecondsFromNow = (0, date_fns_1.getUnixTime)((0, date_fns_1.addSeconds)(new Date(), 10)); | ||
expect((0, utils_1.isTimestampExpired)(tommorrow)).toBe(false); | ||
expect((0, utils_1.isTimestampExpired)(oneHourFromNow)).toBe(false); | ||
expect((0, utils_1.isTimestampExpired)(tenSecondsFromNow)).toBe(false); | ||
it('saveRefreshTokenOnSessionStorage only on main path', function () { | ||
var refreshToken = random.word(); | ||
Object.assign(window.location, { | ||
pathname: '/other-path', | ||
}); | ||
(0, utils_1.saveRefreshTokenOnSessionStorage)(refreshToken); | ||
expect(sessionStorage.getItem('refreshToken')).toBe(refreshToken); | ||
}); | ||
it('should return false if timestamp is not expired with antecipation', function () { | ||
var yesterday = (0, date_fns_1.getUnixTime)((0, date_fns_1.subDays)(new Date(), 1)); | ||
var oneHourAgo = (0, date_fns_1.getUnixTime)((0, date_fns_1.subHours)(new Date(), 1)); | ||
var tenSecondsAgo = (0, date_fns_1.getUnixTime)((0, date_fns_1.subSeconds)(new Date(), 10)); | ||
expect((0, utils_1.isTimestampExpiredWithAntecipation)({ | ||
timestampExpiration: yesterday, | ||
antecipation: -(oneDayInSeconds + 5), | ||
})).toBe(false); | ||
expect((0, utils_1.isTimestampExpiredWithAntecipation)({ | ||
timestampExpiration: oneHourAgo, | ||
antecipation: -(oneHourInSeconds + 5), | ||
})).toBe(false); | ||
expect((0, utils_1.isTimestampExpiredWithAntecipation)({ | ||
timestampExpiration: tenSecondsAgo, | ||
antecipation: -(tenSecondsInSeconds + 5), | ||
})).toBe(false); | ||
it('eraseRefreshTokenOnSessionStorage', function () { | ||
sessionStorage.setItem('refreshToken', random.word()); | ||
(0, utils_1.eraseRefreshTokenOnSessionStorage)(); | ||
expect(sessionStorage.getItem('refreshToken')).toBeNull(); | ||
}); | ||
it('eraseRefreshTokenOnSessionStorage only on main path', function () { | ||
Object.assign(window.location, { | ||
pathname: '/other-path', | ||
}); | ||
sessionStorage.setItem('refreshToken', random.word()); | ||
(0, utils_1.eraseRefreshTokenOnSessionStorage)(); | ||
expect(sessionStorage.getItem('refreshToken')).toBeNull(); | ||
}); | ||
}); |
export function tryRefreshTokenCallback(_a) { | ||
var token = _a.token, tryRefreshToken = _a.tryRefreshToken, tryRefreshTokenParams = _a.tryRefreshTokenParams; | ||
var saveRefreshTokenOnCookie = tryRefreshTokenParams.saveRefreshTokenOnCookie, eraseRefreshTokenOnCookie = tryRefreshTokenParams.eraseRefreshTokenOnCookie, callAccountsLogout = tryRefreshTokenParams.callAccountsLogout, refreshResponseDefinitions = tryRefreshTokenParams.refreshResponseDefinitions; | ||
var saveRefreshTokenOnSessionStorage = tryRefreshTokenParams.saveRefreshTokenOnSessionStorage, eraseRefreshTokenOnSessionStorage = tryRefreshTokenParams.eraseRefreshTokenOnSessionStorage, callAccountsLogout = tryRefreshTokenParams.callAccountsLogout, refreshResponseDefinitions = tryRefreshTokenParams.refreshResponseDefinitions; | ||
tryRefreshToken({ | ||
saveRefreshTokenOnCookie: saveRefreshTokenOnCookie, | ||
eraseRefreshTokenOnCookie: eraseRefreshTokenOnCookie, | ||
saveRefreshTokenOnSessionStorage: saveRefreshTokenOnSessionStorage, | ||
eraseRefreshTokenOnSessionStorage: eraseRefreshTokenOnSessionStorage, | ||
callAccountsLogout: callAccountsLogout, | ||
@@ -8,0 +8,0 @@ refreshToken: token, |
@@ -7,4 +7,4 @@ import { tryRefreshTokenCallback, refreshOrlogin } from './aux'; | ||
var tryRefreshTokenParams = { | ||
saveRefreshTokenOnCookie: jest.fn(), | ||
eraseRefreshTokenOnCookie: jest.fn(), | ||
saveRefreshTokenOnSessionStorage: jest.fn(), | ||
eraseRefreshTokenOnSessionStorage: jest.fn(), | ||
callAccountsLogout: jest.fn(), | ||
@@ -24,4 +24,4 @@ refreshResponseDefinitions: { | ||
expect(tryRefreshToken).toHaveBeenCalledWith({ | ||
saveRefreshTokenOnCookie: tryRefreshTokenParams.saveRefreshTokenOnCookie, | ||
eraseRefreshTokenOnCookie: tryRefreshTokenParams.eraseRefreshTokenOnCookie, | ||
saveRefreshTokenOnSessionStorage: tryRefreshTokenParams.saveRefreshTokenOnSessionStorage, | ||
eraseRefreshTokenOnSessionStorage: tryRefreshTokenParams.eraseRefreshTokenOnSessionStorage, | ||
callAccountsLogout: tryRefreshTokenParams.callAccountsLogout, | ||
@@ -28,0 +28,0 @@ refreshToken: token, |
@@ -14,3 +14,3 @@ var __assign = (this && this.__assign) || function () { | ||
import { createContext, useContext, useEffect } from 'react'; | ||
import { getRefreshTokenFromCookie, eraseRefreshTokenOnCookie, saveRefreshTokenOnCookie, isComingFromBackOffice, } from './utils'; | ||
import { isComingFromBackOffice, getRefreshTokenFromSessionStorage, saveRefreshTokenOnSessionStorage, eraseRefreshTokenOnSessionStorage, } from './utils'; | ||
import { tryRefreshTokenCallback, refreshOrlogin } from './aux'; | ||
@@ -36,3 +36,3 @@ var AuthContext = createContext({ | ||
function initialize() { | ||
var refreshToken = getRefreshTokenFromCookie(); | ||
var refreshToken = getRefreshTokenFromSessionStorage(); | ||
var isSupport = isComingFromBackOffice(backOffice === null || backOffice === void 0 ? void 0 : backOffice.urlParam); | ||
@@ -47,4 +47,4 @@ refreshOrlogin({ | ||
tryRefreshTokenParams: { | ||
saveRefreshTokenOnCookie: saveRefreshTokenOnCookie, | ||
eraseRefreshTokenOnCookie: eraseRefreshTokenOnCookie, | ||
saveRefreshTokenOnSessionStorage: saveRefreshTokenOnSessionStorage, | ||
eraseRefreshTokenOnSessionStorage: eraseRefreshTokenOnSessionStorage, | ||
callAccountsLogout: callAccountsLogout, | ||
@@ -59,3 +59,3 @@ refreshResponseDefinitions: refreshResponseDefinitions, | ||
tryLogin: tryLogin, | ||
saveRefreshTokenOnCookie: saveRefreshTokenOnCookie, | ||
saveRefreshTokenOnSessionStorage: saveRefreshTokenOnSessionStorage, | ||
loginResponseDefinitions: loginResponseDefinitions, | ||
@@ -62,0 +62,0 @@ }); |
@@ -14,3 +14,3 @@ var __assign = (this && this.__assign) || function () { | ||
import { render, screen, faker } from './test.tools'; | ||
import { AuthProvider, useAuth } from './index'; | ||
import { AuthProvider, useAuth } from './context'; | ||
import { AuthProviderPropsMock } from './mocks'; | ||
@@ -17,0 +17,0 @@ var Component = function () { |
@@ -41,3 +41,4 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
import interceptors from './interceptors'; | ||
import { findTarget, getRefreshTokenFromCookie, saveRefreshTokenOnCookie, eraseRefreshTokenOnCookie, } from './utils'; | ||
import { findTarget, saveRefreshTokenOnSessionStorage, eraseRefreshTokenOnSessionStorage, getRefreshTokenFromSessionStorage, } from './utils'; | ||
var bearerTokenInMemory; | ||
function useAuthentication(_a) { | ||
@@ -54,3 +55,3 @@ var _this = this; | ||
var callAccountsLogin = function (_a) { | ||
var callback = _a.tryLogin, saveRefreshTokenOnCookie = _a.saveRefreshTokenOnCookie, loginResponseDefinitions = _a.loginResponseDefinitions; | ||
var callback = _a.tryLogin, saveRefreshTokenOnSessionStorage = _a.saveRefreshTokenOnSessionStorage, loginResponseDefinitions = _a.loginResponseDefinitions; | ||
window.Eduzz.Accounts.login(partnerId, { | ||
@@ -63,3 +64,3 @@ env: env, | ||
accountsToken: accountsToken, | ||
saveRefreshTokenOnCookie: saveRefreshTokenOnCookie, | ||
saveRefreshTokenOnSessionStorage: saveRefreshTokenOnSessionStorage, | ||
loginResponseDefinitions: loginResponseDefinitions, | ||
@@ -70,3 +71,3 @@ }); | ||
var callAccountsLogout = function () { | ||
eraseRefreshTokenOnCookie(); | ||
eraseRefreshTokenOnSessionStorage(); | ||
window.Eduzz.Accounts.logout({ env: env }); | ||
@@ -79,7 +80,7 @@ }; | ||
var tryLogin = function (params) { return __awaiter(_this, void 0, void 0, function () { | ||
var accountsToken, saveRefreshTokenOnCookie, loginResponseDefinitions, tokenKey, refreshTokenKey, mapData, data, mappedData, _a, _b, refreshToken_1, _c, _d, _bearerToken, _bearerTokenDecoded, err_1; | ||
var accountsToken, saveRefreshTokenOnSessionStorage, loginResponseDefinitions, tokenKey, refreshTokenKey, mapData, data, mappedData, _a, _b, refreshToken_1, _c, _d, _bearerToken, _bearerTokenDecoded, err_1; | ||
return __generator(this, function (_e) { | ||
switch (_e.label) { | ||
case 0: | ||
accountsToken = params.accountsToken, saveRefreshTokenOnCookie = params.saveRefreshTokenOnCookie, loginResponseDefinitions = params.loginResponseDefinitions; | ||
accountsToken = params.accountsToken, saveRefreshTokenOnSessionStorage = params.saveRefreshTokenOnSessionStorage, loginResponseDefinitions = params.loginResponseDefinitions; | ||
tokenKey = loginResponseDefinitions.tokenKey, refreshTokenKey = loginResponseDefinitions.refreshTokenKey, mapData = loginResponseDefinitions.mapData; | ||
@@ -99,3 +100,3 @@ _e.label = 1; | ||
_a = mappedData, _b = refreshTokenKey, refreshToken_1 = _a[_b]; | ||
saveRefreshTokenOnCookie(refreshToken_1); | ||
saveRefreshTokenOnSessionStorage(refreshToken_1); | ||
setRefreshToken(refreshToken_1); | ||
@@ -106,2 +107,3 @@ _c = mappedData, _d = tokenKey, _bearerToken = _c[_d]; | ||
setBearerToken(_bearerToken); | ||
bearerTokenInMemory = _bearerToken; | ||
return [3 /*break*/, 4]; | ||
@@ -119,11 +121,11 @@ case 3: | ||
var tryRefreshToken = function (params) { return __awaiter(_this, void 0, void 0, function () { | ||
var eraseRefreshTokenOnCookie, accountsLogout, saveRefreshTokenOnCookie, refreshResponseDefinitions, tokenKey, refreshTokenKey, mapData, data, mappedData, _a, _b, newRefreshToken, _c, _d, _bearerToken, _bearerTokenDecoded, error_1; | ||
return __generator(this, function (_e) { | ||
switch (_e.label) { | ||
var eraseRefreshTokenOnSessionStorage, accountsLogout, saveRefreshTokenOnSessionStorage, refreshResponseDefinitions, tokenKey, refreshTokenKey, mapData, _a, data, status_1, mappedData, _b, _c, newRefreshToken, _d, _e, _bearerToken, _bearerTokenDecoded, error_1; | ||
return __generator(this, function (_f) { | ||
switch (_f.label) { | ||
case 0: | ||
eraseRefreshTokenOnCookie = params.eraseRefreshTokenOnCookie, accountsLogout = params.callAccountsLogout, saveRefreshTokenOnCookie = params.saveRefreshTokenOnCookie, refreshResponseDefinitions = params.refreshResponseDefinitions; | ||
eraseRefreshTokenOnSessionStorage = params.eraseRefreshTokenOnSessionStorage, accountsLogout = params.callAccountsLogout, saveRefreshTokenOnSessionStorage = params.saveRefreshTokenOnSessionStorage, refreshResponseDefinitions = params.refreshResponseDefinitions; | ||
tokenKey = refreshResponseDefinitions.tokenKey, refreshTokenKey = refreshResponseDefinitions.refreshTokenKey, mapData = refreshResponseDefinitions.mapData; | ||
_e.label = 1; | ||
_f.label = 1; | ||
case 1: | ||
_e.trys.push([1, 3, , 4]); | ||
_f.trys.push([1, 3, , 4]); | ||
cleanAccountsTokenURLParam(); | ||
@@ -136,16 +138,19 @@ return [4 /*yield*/, Api.refreshToken({ | ||
case 2: | ||
data = (_e.sent()).data; | ||
_a = _f.sent(), data = _a.data, status_1 = _a.status; | ||
if (status_1 !== 200) | ||
throw new Error('Problema com o token'); | ||
mappedData = findTarget(mapData, data); | ||
_a = mappedData, _b = refreshTokenKey, newRefreshToken = _a[_b]; | ||
saveRefreshTokenOnCookie(newRefreshToken); | ||
_b = mappedData, _c = refreshTokenKey, newRefreshToken = _b[_c]; | ||
saveRefreshTokenOnSessionStorage(newRefreshToken); | ||
setRefreshToken(refreshToken); | ||
_c = mappedData, _d = tokenKey, _bearerToken = _c[_d]; | ||
_d = mappedData, _e = tokenKey, _bearerToken = _d[_e]; | ||
_bearerTokenDecoded = jwt.decode(_bearerToken); | ||
setBearerTokenDecoded(_bearerTokenDecoded); | ||
setBearerToken(_bearerToken); | ||
bearerTokenInMemory = _bearerToken; | ||
setLoading(false); | ||
return [3 /*break*/, 4]; | ||
case 3: | ||
error_1 = _e.sent(); | ||
eraseRefreshTokenOnCookie(); | ||
error_1 = _f.sent(); | ||
eraseRefreshTokenOnSessionStorage(); | ||
accountsLogout(); | ||
@@ -157,32 +162,32 @@ return [3 /*break*/, 4]; | ||
}); }; | ||
var initBearerInterceptor = function (_interceptor) { | ||
interceptors.bearer({ | ||
bearer: bearerToken, | ||
interceptor: _interceptor, | ||
}); | ||
}; | ||
var initRefreshTokenInterceptor = function (params) { | ||
var _refreshToken = getRefreshTokenFromCookie(); | ||
var initBearerInterceptor = function (_a) { | ||
var _interceptors = _a._interceptors, active = _a.active; | ||
var _refreshToken = getRefreshTokenFromSessionStorage(); | ||
if (_refreshToken) { | ||
interceptors.refresh({ | ||
interceptor: params._interceptor, | ||
bearerExpirationTimestamp: params.bearerExpirationTimestamp, | ||
updateToken: function () { | ||
return tryRefreshToken({ | ||
saveRefreshTokenOnCookie: saveRefreshTokenOnCookie, | ||
eraseRefreshTokenOnCookie: eraseRefreshTokenOnCookie, | ||
callAccountsLogout: callAccountsLogout, | ||
refreshToken: _refreshToken, | ||
refreshResponseDefinitions: refresh.response, | ||
interceptors.bearer({ | ||
bearer: bearerToken, | ||
interceptors: _interceptors, | ||
tryRefreshToken: function () { return __awaiter(_this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, tryRefreshToken({ | ||
saveRefreshTokenOnSessionStorage: saveRefreshTokenOnSessionStorage, | ||
eraseRefreshTokenOnSessionStorage: eraseRefreshTokenOnSessionStorage, | ||
callAccountsLogout: callAccountsLogout, | ||
refreshToken: _refreshToken, | ||
refreshResponseDefinitions: refresh.response, | ||
})]; | ||
case 1: | ||
_a.sent(); | ||
return [2 /*return*/, Promise.resolve(bearerTokenInMemory)]; | ||
} | ||
}); | ||
}); }, | ||
logout: function () { | ||
callAccountsLogout(); | ||
}, | ||
activeInterceptors: active, | ||
}); | ||
} | ||
}; | ||
var initLogoutInterceptor = function (_interceptor) { | ||
interceptors.logout({ | ||
interceptor: _interceptor, | ||
logout: function () { return callAccountsLogout(); }, | ||
}); | ||
}; | ||
var initializeAxiosInterceptors = function (_a) { | ||
@@ -196,14 +201,6 @@ var interceptors = _a.interceptors, active = _a.active; | ||
} | ||
if (!active || active.addBearerOnAllRequests !== false) { | ||
initBearerInterceptor(interceptors.request); | ||
} | ||
if (!active || active.refreshWhenBearerTokenIsExpired !== false) { | ||
initRefreshTokenInterceptor({ | ||
_interceptor: interceptors.request, | ||
bearerExpirationTimestamp: bearerTokenDecoded === null || bearerTokenDecoded === void 0 ? void 0 : bearerTokenDecoded.exp, | ||
}); | ||
} | ||
if (!active || active.logoutWhenResponseIsUnauthorized !== false) { | ||
initLogoutInterceptor(interceptors.response); | ||
} | ||
initBearerInterceptor({ | ||
_interceptors: interceptors, | ||
active: active, | ||
}); | ||
}; | ||
@@ -231,4 +228,2 @@ useEffect(function () { | ||
bearer: initBearerInterceptor, | ||
refresh: initRefreshTokenInterceptor, | ||
logout: initLogoutInterceptor, | ||
}, | ||
@@ -235,0 +230,0 @@ clientInterceptorsInitialize: clientInterceptorsInitialize, |
@@ -50,9 +50,6 @@ var __assign = (this && this.__assign) || function () { | ||
import Jwt from 'jsonwebtoken'; | ||
import { authentication } from './index'; | ||
import { logoutFn, loginFn, subscribeFn, tryLoginFn, replaceStateFn, callAccountsLogoutFn, eraseAccountsLogoutFn, saveRefreshTokenOnCookieFn, loginService, refreshService, } from './mocks'; | ||
import authentication from './hook'; | ||
import { logoutFn, loginFn, subscribeFn, tryLoginFn, replaceStateFn, callAccountsLogoutFn, eraseAccountsLogoutFn, saveRefreshTokenOnSessionStorageFn, loginService, refreshService, } from './mocks'; | ||
import Api from './service'; | ||
import { eraseRefreshTokenOnCookie, saveRefreshTokenOnCookie } from './utils'; | ||
import interceptors from './interceptors'; | ||
import axios from 'axios'; | ||
import { getUnixTime } from 'date-fns'; | ||
import { eraseRefreshTokenOnSessionStorage, saveRefreshTokenOnSessionStorage, } from './utils'; | ||
describe('Context/Authentication/Hook', function () { | ||
@@ -75,3 +72,2 @@ var random = faker.random, datatype = faker.datatype, internet = faker.internet; | ||
email: internet.email(), | ||
exp: getUnixTime(new Date()) + 3600, | ||
}; | ||
@@ -126,3 +122,3 @@ var bearerToken = Jwt.sign(bearerTokenDecoded, random.word()); | ||
tryLogin: tryLoginFn, | ||
saveRefreshTokenOnCookie: saveRefreshTokenOnCookieFn, | ||
saveRefreshTokenOnSessionStorage: saveRefreshTokenOnSessionStorageFn, | ||
loginResponseDefinitions: loginResponseDefinitions, | ||
@@ -167,4 +163,4 @@ }); | ||
callAccountsLogout: callAccountsLogoutFn, | ||
eraseRefreshTokenOnCookie: eraseRefreshTokenOnCookie, | ||
saveRefreshTokenOnCookie: saveRefreshTokenOnCookie, | ||
eraseRefreshTokenOnSessionStorage: eraseRefreshTokenOnSessionStorage, | ||
saveRefreshTokenOnSessionStorage: saveRefreshTokenOnSessionStorage, | ||
refreshToken: refreshToken, | ||
@@ -182,3 +178,3 @@ refreshResponseDefinitions: refreshResponseDefinitions, | ||
accountsToken: accountsToken, | ||
saveRefreshTokenOnCookie: saveRefreshTokenOnCookieFn, | ||
saveRefreshTokenOnSessionStorage: saveRefreshTokenOnSessionStorageFn, | ||
loginResponseDefinitions: loginResponseDefinitions, | ||
@@ -204,3 +200,3 @@ }; | ||
tryLogin: tryLoginFn, | ||
saveRefreshTokenOnCookie: saveRefreshTokenOnCookieFn, | ||
saveRefreshTokenOnSessionStorage: saveRefreshTokenOnSessionStorageFn, | ||
loginResponseDefinitions: loginResponseDefinitions, | ||
@@ -224,4 +220,4 @@ }); | ||
callAccountsLogout: callAccountsLogoutFn, | ||
eraseRefreshTokenOnCookie: eraseAccountsLogoutFn, | ||
saveRefreshTokenOnCookie: saveRefreshTokenOnCookieFn, | ||
eraseRefreshTokenOnSessionStorage: eraseAccountsLogoutFn, | ||
saveRefreshTokenOnSessionStorage: saveRefreshTokenOnSessionStorage, | ||
refreshToken: refreshToken, | ||
@@ -239,45 +235,2 @@ refreshResponseDefinitions: refreshResponseDefinitions, | ||
}); }); | ||
it('shoud set bearerTokenDecoded, loading and save refresh token on cookie when try refresh is success', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var _a, result, unmount; | ||
var _b; | ||
return __generator(this, function (_c) { | ||
switch (_c.label) { | ||
case 0: | ||
_a = renderHook(function () { | ||
return authentication({ accounts: accounts, api: api }); | ||
}), result = _a.result, unmount = _a.unmount; | ||
jest.spyOn(Api, 'refreshToken').mockResolvedValue(__assign(__assign({}, response), { data: (_b = {}, | ||
_b[refreshResponseDefinitions.tokenKey] = bearerToken, | ||
_b[refreshResponseDefinitions.refreshTokenKey] = refreshToken, | ||
_b) })); | ||
jest.spyOn(Jwt, 'decode').mockReturnValue(bearerToken); | ||
return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, result.current.tryRefreshToken({ | ||
callAccountsLogout: callAccountsLogoutFn, | ||
eraseRefreshTokenOnCookie: eraseAccountsLogoutFn, | ||
saveRefreshTokenOnCookie: saveRefreshTokenOnCookieFn, | ||
refreshToken: refreshToken, | ||
refreshResponseDefinitions: refreshResponseDefinitions, | ||
})]; | ||
case 1: | ||
_a.sent(); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); })]; | ||
case 1: | ||
_c.sent(); | ||
expect(callAccountsLogoutFn).not.toBeCalled(); | ||
expect(eraseAccountsLogoutFn).not.toBeCalled(); | ||
expect(saveRefreshTokenOnCookieFn).toBeCalledWith(refreshToken); | ||
expect(result.current.bearerTokenDecoded).toBe(bearerToken); | ||
expect(result.current.bearerToken).toBe(bearerToken); | ||
expect(result.current.loading).toBe(false); | ||
unmount(); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
it('should call tryLogin and get error on call Api.login', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
@@ -298,3 +251,3 @@ var _a, result, unmount; | ||
accountsToken: accountsToken, | ||
saveRefreshTokenOnCookie: saveRefreshTokenOnCookieFn, | ||
saveRefreshTokenOnSessionStorage: saveRefreshTokenOnSessionStorageFn, | ||
loginResponseDefinitions: loginResponseDefinitions, | ||
@@ -310,3 +263,3 @@ })]; | ||
_b.sent(); | ||
expect(saveRefreshTokenOnCookieFn).not.toHaveBeenCalled(); | ||
expect(saveRefreshTokenOnSessionStorageFn).not.toHaveBeenCalled(); | ||
expect(result.current.loading).toBe(false); | ||
@@ -337,3 +290,3 @@ unmount(); | ||
accountsToken: accountsToken, | ||
saveRefreshTokenOnCookie: saveRefreshTokenOnCookieFn, | ||
saveRefreshTokenOnSessionStorage: saveRefreshTokenOnSessionStorageFn, | ||
loginResponseDefinitions: loginResponseDefinitions, | ||
@@ -349,3 +302,3 @@ })]; | ||
_c.sent(); | ||
expect(saveRefreshTokenOnCookieFn).toBeCalledWith(refreshToken); | ||
expect(saveRefreshTokenOnSessionStorageFn).toBeCalledWith(refreshToken); | ||
expect(result.current.bearerTokenDecoded).toBe(bearerTokenDecoded); | ||
@@ -359,39 +312,2 @@ expect(result.current.bearerToken).toBe(bearerToken); | ||
}); }); | ||
it('should call initBearerInterceptor', function () { | ||
var _a; | ||
var _b = renderHook(function () { | ||
return authentication({ accounts: accounts, api: api }); | ||
}), result = _b.result, unmount = _b.unmount; | ||
var mockFunction = jest.fn(); | ||
jest.spyOn(interceptors, 'bearer').mockImplementation(mockFunction); | ||
(_a = result.current.initInterceptors) === null || _a === void 0 ? void 0 : _a.bearer(axios.interceptors.request); | ||
expect(mockFunction).toBeCalled(); | ||
unmount(); | ||
}); | ||
it('should call initRefreshTokenInterceptor', function () { | ||
var _a; | ||
var _b = renderHook(function () { | ||
return authentication({ accounts: accounts, api: api }); | ||
}), result = _b.result, unmount = _b.unmount; | ||
var mockFunction = jest.fn(); | ||
saveRefreshTokenOnCookie('1234'); | ||
jest.spyOn(interceptors, 'refresh').mockImplementation(mockFunction); | ||
(_a = result.current.initInterceptors) === null || _a === void 0 ? void 0 : _a.refresh({ | ||
_interceptor: axios.interceptors.request, | ||
bearerExpirationTimestamp: bearerTokenDecoded.exp, | ||
}); | ||
expect(mockFunction).toBeCalled(); | ||
unmount(); | ||
}); | ||
it('should call initLogoutInterceptor', function () { | ||
var _a; | ||
var _b = renderHook(function () { | ||
return authentication({ accounts: accounts, api: api }); | ||
}), result = _b.result, unmount = _b.unmount; | ||
var mockFunction = jest.fn(); | ||
jest.spyOn(interceptors, 'logout').mockImplementation(mockFunction); | ||
(_a = result.current.initInterceptors) === null || _a === void 0 ? void 0 : _a.logout(axios.interceptors.response); | ||
expect(mockFunction).toBeCalled(); | ||
unmount(); | ||
}); | ||
}); |
@@ -1,3 +0,1 @@ | ||
export * from './context'; | ||
export { default as authentication } from './hook'; | ||
export type { AuthProviderConfig } from './types'; | ||
export * from './exports'; |
@@ -1,2 +0,19 @@ | ||
export * from './context'; | ||
export { default as authentication } from './hook'; | ||
// Durante o desenvolvimento da aplicação, para se testar | ||
// descomente o código abaixo e execute "yarn start" | ||
/* import React from 'react'; | ||
import ReactDOM from 'react-dom'; | ||
import { AuthProvider } from './context'; | ||
import App from './client/app'; | ||
import { config } from './client/config'; | ||
ReactDOM.render( | ||
<React.StrictMode> | ||
<AuthProvider config={config}> | ||
<App /> | ||
</AuthProvider> | ||
</React.StrictMode>, | ||
document.getElementById('root') | ||
); */ | ||
export * from './exports'; |
@@ -1,14 +0,10 @@ | ||
import { AxiosError, AxiosRequestConfig } from 'axios'; | ||
import { InitializeBearerInterceptorConfig, InitializeTryRefreshRequestInterceptorConfig, InitializeLogoutResponseInterceptorConfig, AddBearerOnHeadersProps, CleanUpInterceptorsProps, JoinCallbackBearerInterceptorConfig, AddUpdateTokenOnRefresh, CallLogoutWhenUnauthorized } from './types'; | ||
import { AxiosRequestConfig } from 'axios'; | ||
import { InitializeBearerInterceptorConfig, AddBearerOnHeadersProps, CleanUpInterceptorsProps, JoinCallbackBearerInterceptorConfig } from './types'; | ||
declare const cleanUpInterceptor: ({ countGlobalInterceptorCreation, interceptor, }: CleanUpInterceptorsProps) => void; | ||
declare const addBearerOnRequestHeaders: ({ req, bearer, }: AddBearerOnHeadersProps) => AxiosRequestConfig<any>; | ||
declare const callUpdateTokenIfNecessary: ({ req, bearerExpirationTimestamp, updateToken, }: AddUpdateTokenOnRefresh) => AxiosRequestConfig<any>; | ||
declare const callLogoutWhenUnauthorized: ({ error, logout, conditionToLogout, }: CallLogoutWhenUnauthorized) => AxiosError; | ||
declare const joinCallbackOnBearer: ({ bearer, interceptor, callback, }: JoinCallbackBearerInterceptorConfig) => void; | ||
declare const addBearerOnRequestHeaders: ({ req, bearer, }: AddBearerOnHeadersProps) => AxiosRequestConfig; | ||
declare const joinCallbackOnBearer: ({ bearer, interceptors, callback, tryRefreshToken, logout, activeInterceptors, }: JoinCallbackBearerInterceptorConfig) => void; | ||
declare const interceptors: { | ||
bearer: ({ bearer, interceptor, }: InitializeBearerInterceptorConfig) => void; | ||
refresh: ({ bearerExpirationTimestamp, updateToken, interceptor, }: InitializeTryRefreshRequestInterceptorConfig) => void; | ||
logout: ({ interceptor, logout, }: InitializeLogoutResponseInterceptorConfig) => void; | ||
bearer: ({ bearer, interceptors, tryRefreshToken, logout, activeInterceptors, }: InitializeBearerInterceptorConfig) => void; | ||
}; | ||
export default interceptors; | ||
export { addBearerOnRequestHeaders, cleanUpInterceptor, joinCallbackOnBearer, callUpdateTokenIfNecessary, callLogoutWhenUnauthorized, }; | ||
export { addBearerOnRequestHeaders, cleanUpInterceptor, joinCallbackOnBearer }; |
@@ -12,6 +12,42 @@ var __assign = (this && this.__assign) || function () { | ||
}; | ||
import { isTimestampExpiredWithAntecipation } from './utils'; | ||
var bearerInterceptor = null; | ||
var refreshInterceptor = null; | ||
var logoutInterceptor = null; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (_) try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
import axios from 'axios'; | ||
var bearerRequestInterceptor = null; | ||
var bearerResponseInterceptor = null; | ||
var retryRefresh = 0; | ||
var cleanUpInterceptor = function (_a) { | ||
@@ -28,28 +64,18 @@ var countGlobalInterceptorCreation = _a.countGlobalInterceptorCreation, interceptor = _a.interceptor; | ||
}; | ||
var callUpdateTokenIfNecessary = function (_a) { | ||
var req = _a.req, bearerExpirationTimestamp = _a.bearerExpirationTimestamp, updateToken = _a.updateToken; | ||
if (updateToken && | ||
bearerExpirationTimestamp && | ||
isTimestampExpiredWithAntecipation({ | ||
timestampExpiration: bearerExpirationTimestamp, | ||
antecipation: 60, | ||
})) { | ||
updateToken(); | ||
} | ||
return __assign({}, req); | ||
}; | ||
var callLogoutWhenUnauthorized = function (_a) { | ||
var error = _a.error, logout = _a.logout, conditionToLogout = _a.conditionToLogout; | ||
if (conditionToLogout && logout) { | ||
logout(); | ||
} | ||
return error; | ||
}; | ||
var joinCallbackOnBearer = function (_a) { | ||
var bearer = _a.bearer, interceptor = _a.interceptor, callback = _a.callback; | ||
var bearer = _a.bearer, interceptors = _a.interceptors, callback = _a.callback, tryRefreshToken = _a.tryRefreshToken, logout = _a.logout, activeInterceptors = _a.activeInterceptors; | ||
cleanUpInterceptor({ | ||
countGlobalInterceptorCreation: bearerInterceptor, | ||
interceptor: interceptor, | ||
countGlobalInterceptorCreation: bearerRequestInterceptor, | ||
interceptor: interceptors.request, | ||
}); | ||
bearerInterceptor = interceptor.use(function (req) { | ||
bearerRequestInterceptor = interceptors.request.use(function (req) { | ||
var _a, _b; | ||
if ((activeInterceptors === null || activeInterceptors === void 0 ? void 0 : activeInterceptors.addBearerOnAllRequests) === false) | ||
return; | ||
if ((_a = req === null || req === void 0 ? void 0 : req.headers) === null || _a === void 0 ? void 0 : _a.Authorization) { | ||
return callback({ | ||
req: req, | ||
bearer: (_b = req === null || req === void 0 ? void 0 : req.headers) === null || _b === void 0 ? void 0 : _b.Authorization, | ||
}); | ||
} | ||
return callback({ | ||
@@ -60,59 +86,43 @@ bearer: bearer, | ||
}); | ||
cleanUpInterceptor({ | ||
countGlobalInterceptorCreation: bearerResponseInterceptor, | ||
interceptor: interceptors.response, | ||
}); | ||
bearerResponseInterceptor = interceptors.response.use(undefined, function (error) { return __awaiter(void 0, void 0, void 0, function () { | ||
var newBearer, originalRequest; | ||
var _a; | ||
return __generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
if (((_a = error.response) === null || _a === void 0 ? void 0 : _a.status) !== 401) { | ||
return [2 /*return*/, Promise.reject(error)]; | ||
} | ||
if (!(retryRefresh < 3 && | ||
(activeInterceptors === null || activeInterceptors === void 0 ? void 0 : activeInterceptors.refreshWhenBearerTokenIsExpired) !== false)) return [3 /*break*/, 2]; | ||
retryRefresh = retryRefresh + 1; | ||
return [4 /*yield*/, tryRefreshToken()]; | ||
case 1: | ||
newBearer = _b.sent(); | ||
originalRequest = __assign(__assign({}, error.config), { headers: __assign(__assign({}, error.config.headers), { Authorization: "" + newBearer }) }); | ||
axios.request(originalRequest); | ||
return [3 /*break*/, 3]; | ||
case 2: | ||
Promise.reject(error); | ||
(activeInterceptors === null || activeInterceptors === void 0 ? void 0 : activeInterceptors.logoutWhenResponseIsUnauthorized) !== false && | ||
(logout === null || logout === void 0 ? void 0 : logout()); | ||
_b.label = 3; | ||
case 3: return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
}; | ||
var bearer = function (_a) { | ||
var bearer = _a.bearer, interceptor = _a.interceptor; | ||
cleanUpInterceptor({ | ||
countGlobalInterceptorCreation: bearerInterceptor, | ||
interceptor: interceptor, | ||
}); | ||
var bearer = _a.bearer, interceptors = _a.interceptors, tryRefreshToken = _a.tryRefreshToken, logout = _a.logout, activeInterceptors = _a.activeInterceptors; | ||
joinCallbackOnBearer({ | ||
bearer: bearer, | ||
interceptor: interceptor, | ||
interceptors: interceptors, | ||
callback: addBearerOnRequestHeaders, | ||
}); | ||
}; | ||
var joinCallbackOnRefresh = function (_a) { | ||
var bearerExpirationTimestamp = _a.bearerExpirationTimestamp, updateToken = _a.updateToken, interceptor = _a.interceptor, callback = _a.callback; | ||
cleanUpInterceptor({ | ||
countGlobalInterceptorCreation: refreshInterceptor, | ||
interceptor: interceptor, | ||
}); | ||
refreshInterceptor = interceptor.use(function (req) { | ||
return callback({ | ||
req: req, | ||
bearerExpirationTimestamp: bearerExpirationTimestamp, | ||
updateToken: updateToken, | ||
}); | ||
}); | ||
}; | ||
var refresh = function (_a) { | ||
var bearerExpirationTimestamp = _a.bearerExpirationTimestamp, updateToken = _a.updateToken, interceptor = _a.interceptor; | ||
joinCallbackOnRefresh({ | ||
bearerExpirationTimestamp: bearerExpirationTimestamp, | ||
callback: callUpdateTokenIfNecessary, | ||
interceptor: interceptor, | ||
updateToken: updateToken, | ||
}); | ||
}; | ||
var joinCallbackOnLogout = function (_a) { | ||
var interceptor = _a.interceptor, logout = _a.logout, callback = _a.callback; | ||
cleanUpInterceptor({ | ||
countGlobalInterceptorCreation: logoutInterceptor, | ||
interceptor: interceptor, | ||
}); | ||
logoutInterceptor = interceptor.use(function (res) { return res; }, function (err) { | ||
var _a; | ||
return callback({ | ||
error: err, | ||
logout: logout, | ||
conditionToLogout: ((_a = err.response) === null || _a === void 0 ? void 0 : _a.status) === 401, | ||
}); | ||
}); | ||
}; | ||
var logout = function (_a) { | ||
var interceptor = _a.interceptor, logout = _a.logout; | ||
joinCallbackOnLogout({ | ||
interceptor: interceptor, | ||
tryRefreshToken: tryRefreshToken, | ||
logout: logout, | ||
callback: callLogoutWhenUnauthorized, | ||
activeInterceptors: activeInterceptors, | ||
}); | ||
@@ -122,6 +132,4 @@ }; | ||
bearer: bearer, | ||
refresh: refresh, | ||
logout: logout, | ||
}; | ||
export default interceptors; | ||
export { addBearerOnRequestHeaders, cleanUpInterceptor, joinCallbackOnBearer, callUpdateTokenIfNecessary, callLogoutWhenUnauthorized, }; | ||
export { addBearerOnRequestHeaders, cleanUpInterceptor, joinCallbackOnBearer }; |
@@ -38,4 +38,3 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
import axios from 'axios'; | ||
import { addDays, getUnixTime } from 'date-fns'; | ||
import interceptors, { addBearerOnRequestHeaders, cleanUpInterceptor, callUpdateTokenIfNecessary, callLogoutWhenUnauthorized, } from './interceptors'; | ||
import interceptors, { addBearerOnRequestHeaders, cleanUpInterceptor, } from './interceptors'; | ||
jest.mock('axios'); | ||
@@ -54,54 +53,2 @@ describe('Interceptors', function () { | ||
}); | ||
it('should call update token if necessary', function () { | ||
var mockedExpiredTimestamp = getUnixTime(new Date()) - 1000; | ||
var updateTokenFn = jest.fn(); | ||
var req = callUpdateTokenIfNecessary({ | ||
req: {}, | ||
bearerExpirationTimestamp: mockedExpiredTimestamp, | ||
updateToken: updateTokenFn, | ||
}); | ||
expect(req).toBeDefined(); | ||
expect(updateTokenFn).toHaveBeenCalled(); | ||
}); | ||
it('should not call update token if not necessary', function () { | ||
var mockedNotExpiredTimestamp = getUnixTime(addDays(new Date(), 2)); | ||
var updateTokenFn = jest.fn(); | ||
var req = callUpdateTokenIfNecessary({ | ||
req: {}, | ||
bearerExpirationTimestamp: mockedNotExpiredTimestamp, | ||
updateToken: updateTokenFn, | ||
}); | ||
expect(req).toBeDefined(); | ||
expect(updateTokenFn).not.toHaveBeenCalled(); | ||
}); | ||
it('should call logout when unauthorized', function () { | ||
var logoutFn = jest.fn(); | ||
var error = { | ||
response: { | ||
status: 401, | ||
}, | ||
}; | ||
var req = callLogoutWhenUnauthorized({ | ||
error: error, | ||
logout: logoutFn, | ||
conditionToLogout: error.response.status === 401, | ||
}); | ||
expect(req).toBeDefined(); | ||
expect(logoutFn).toHaveBeenCalled(); | ||
}); | ||
it('should not call logout when is other error than 401', function () { | ||
var logoutFn = jest.fn(); | ||
var error = { | ||
response: { | ||
status: 400, | ||
}, | ||
}; | ||
var req = callLogoutWhenUnauthorized({ | ||
error: error, | ||
logout: logoutFn, | ||
conditionToLogout: error.response.status === 401, | ||
}); | ||
expect(req).toBeDefined(); | ||
expect(logoutFn).not.toHaveBeenCalled(); | ||
}); | ||
it('should clean up interceptor works properly', function () { | ||
@@ -120,3 +67,5 @@ var interceptor = axios.interceptors.request; | ||
bearer: '1234', | ||
interceptor: axios.interceptors.request, | ||
interceptors: axios.interceptors, | ||
logout: jest.fn(), | ||
tryRefreshToken: jest.fn(), | ||
}); | ||
@@ -127,18 +76,2 @@ expect(axios.interceptors.request.use).toHaveBeenCalled(); | ||
}); }); | ||
it('should be able to initialize the refresh interceptor', function () { | ||
interceptors.refresh({ | ||
interceptor: axios.interceptors.request, | ||
bearerExpirationTimestamp: new Date().getTime(), | ||
updateToken: jest.fn(), | ||
}); | ||
expect(axios.interceptors.request.use).toHaveBeenCalled(); | ||
}); | ||
it('should be able to initialize the logout interceptor', function () { | ||
var logoutFn = jest.fn(); | ||
interceptors.logout({ | ||
interceptor: axios.interceptors.response, | ||
logout: logoutFn, | ||
}); | ||
expect(axios.interceptors.response.use).toHaveBeenCalled(); | ||
}); | ||
}); |
@@ -10,3 +10,3 @@ /// <reference types="jest" /> | ||
declare const eraseAccountsLogoutFn: jest.Mock<any, any>; | ||
declare const saveRefreshTokenOnCookieFn: jest.Mock<any, any>; | ||
declare const saveRefreshTokenOnSessionStorageFn: jest.Mock<any, any>; | ||
declare const tryRefreshTokenFn: jest.Mock<any, any>; | ||
@@ -48,2 +48,2 @@ declare const callAccountsLoginFn: jest.Mock<any, any>; | ||
declare const refreshService: RefreshServiceType; | ||
export { mockUrl, subscribeFn, logoutFn, authenticationSpy, loginFn, tryLoginFn, replaceStateFn, callAccountsLogoutFn, eraseAccountsLogoutFn, saveRefreshTokenOnCookieFn, AuthProviderPropsMock, tryRefreshTokenFn, callAccountsLoginFn, loginService, refreshService, }; | ||
export { mockUrl, subscribeFn, logoutFn, authenticationSpy, loginFn, tryLoginFn, replaceStateFn, callAccountsLogoutFn, eraseAccountsLogoutFn, saveRefreshTokenOnSessionStorageFn, AuthProviderPropsMock, tryRefreshTokenFn, callAccountsLoginFn, loginService, refreshService, }; |
@@ -10,3 +10,3 @@ import { faker } from './test.tools'; | ||
var eraseAccountsLogoutFn = jest.fn(); | ||
var saveRefreshTokenOnCookieFn = jest.fn(); | ||
var saveRefreshTokenOnSessionStorageFn = jest.fn(); | ||
var tryRefreshTokenFn = jest.fn(); | ||
@@ -95,2 +95,2 @@ var callAccountsLoginFn = jest.fn(); | ||
}; | ||
export { mockUrl, subscribeFn, logoutFn, authenticationSpy, loginFn, tryLoginFn, replaceStateFn, callAccountsLogoutFn, eraseAccountsLogoutFn, saveRefreshTokenOnCookieFn, AuthProviderPropsMock, tryRefreshTokenFn, callAccountsLoginFn, loginService, refreshService, }; | ||
export { mockUrl, subscribeFn, logoutFn, authenticationSpy, loginFn, tryLoginFn, replaceStateFn, callAccountsLogoutFn, eraseAccountsLogoutFn, saveRefreshTokenOnSessionStorageFn, AuthProviderPropsMock, tryRefreshTokenFn, callAccountsLoginFn, loginService, refreshService, }; |
@@ -1,1 +0,1 @@ | ||
import "@testing-library/jest-dom"; | ||
import '@testing-library/jest-dom'; |
@@ -5,2 +5,2 @@ // jest-dom adds custom jest matchers for asserting on DOM nodes. | ||
// learn more: https://github.com/testing-library/jest-dom | ||
import "@testing-library/jest-dom"; | ||
import '@testing-library/jest-dom'; |
/// <reference types="react" /> | ||
import { AxiosInterceptorManager, AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios'; | ||
import { AxiosInterceptorManager, AxiosRequestConfig, AxiosResponse } from 'axios'; | ||
declare module 'axios' { | ||
@@ -32,2 +32,6 @@ interface AxiosInstance { | ||
}; | ||
export declare type InitInterceptors = { | ||
_interceptors: AxiosInterceptors; | ||
active?: ActiveInterceptors; | ||
}; | ||
export declare type BackOfficeConfigType = { | ||
@@ -105,5 +109,3 @@ urlParam: string; | ||
initInterceptors: { | ||
bearer: (interceptors: AxiosInterceptorManager<AxiosRequestConfig>) => void; | ||
refresh: (params: InitRefreshTokenInterceptor) => void; | ||
logout: (interceptors: AxiosInterceptorManager<AxiosResponse<any>>) => void; | ||
bearer: (params: InitInterceptors) => void; | ||
} | null; | ||
@@ -128,3 +130,3 @@ clientInterceptorsInitialize: InitializeAxiosInterceptors | null; | ||
tryLogin: (params: TryLoginParams) => void; | ||
saveRefreshTokenOnCookie: (refreshToken: string) => void; | ||
saveRefreshTokenOnSessionStorage: (refreshToken: string) => void; | ||
loginResponseDefinitions: LoginResponseServiceType; | ||
@@ -134,5 +136,5 @@ }; | ||
callAccountsLogout: () => void; | ||
eraseRefreshTokenOnCookie: () => void; | ||
saveRefreshTokenOnCookie: (newRefreshToken: string) => void; | ||
refreshToken: string | undefined; | ||
eraseRefreshTokenOnSessionStorage: () => void; | ||
saveRefreshTokenOnSessionStorage: (newRefreshToken: string) => void; | ||
refreshToken: string | null; | ||
refreshResponseDefinitions: RefreshResponseServiceType; | ||
@@ -143,10 +145,5 @@ }; | ||
accountsToken: AccountsToken; | ||
saveRefreshTokenOnCookie: (refreshToken: string) => void; | ||
saveRefreshTokenOnSessionStorage: (refreshToken: string) => void; | ||
loginResponseDefinitions: LoginResponseServiceType; | ||
}; | ||
export declare type InitializeTryRefreshRequestInterceptorConfig = { | ||
bearerExpirationTimestamp: number | null; | ||
updateToken: (() => void) | null; | ||
interceptor: AxiosInterceptorManager<AxiosRequestConfig>; | ||
}; | ||
export declare type CallLogoutWhenUnauthorized = { | ||
@@ -158,7 +155,7 @@ error: any; | ||
export declare type AddBearerOnHeadersProps = { | ||
req: AxiosRequestConfig<any>; | ||
req: AxiosRequestConfig; | ||
bearer: string | null; | ||
}; | ||
export declare type AddUpdateTokenOnRefresh = { | ||
req: AxiosRequestConfig<any>; | ||
req: AxiosRequestConfig; | ||
bearerExpirationTimestamp: number | null; | ||
@@ -169,23 +166,19 @@ updateToken: (() => void) | null; | ||
bearer: string | null; | ||
interceptor: AxiosInterceptorManager<AxiosRequestConfig>; | ||
callback: (param: AddBearerOnHeadersProps) => AxiosRequestConfig<any>; | ||
interceptors: AxiosInterceptors; | ||
callback: (param: AddBearerOnHeadersProps) => AxiosRequestConfig; | ||
tryRefreshToken: () => Promise<string | null>; | ||
logout: (() => void) | null; | ||
activeInterceptors?: ActiveInterceptors; | ||
}; | ||
export declare type JoinCallbackOnRefresh = InitializeTryRefreshRequestInterceptorConfig & { | ||
callback: (params: AddUpdateTokenOnRefresh) => AxiosRequestConfig<any>; | ||
}; | ||
export declare type JoinCallbackOnLogout = InitializeLogoutResponseInterceptorConfig & { | ||
callback: (params: CallLogoutWhenUnauthorized) => AxiosError; | ||
}; | ||
export declare type InitializeBearerInterceptorConfig = { | ||
bearer: string | null; | ||
interceptor: AxiosInterceptorManager<AxiosRequestConfig>; | ||
interceptors: AxiosInterceptors; | ||
tryRefreshToken: () => Promise<string | null>; | ||
logout: (() => void) | null; | ||
activeInterceptors?: ActiveInterceptors; | ||
}; | ||
export declare type CleanUpInterceptorsProps = { | ||
countGlobalInterceptorCreation: number | null; | ||
interceptor: AxiosInterceptorManager<AxiosRequestConfig<any>>; | ||
interceptor: AxiosInterceptorManager<AxiosRequestConfig>; | ||
}; | ||
export declare type InitializeLogoutResponseInterceptorConfig = { | ||
logout: (() => void) | null; | ||
interceptor: AxiosInterceptorManager<AxiosResponse<any>>; | ||
}; | ||
export declare type AxiosInterceptors = { | ||
@@ -195,16 +188,13 @@ request: AxiosInterceptorManager<AxiosRequestConfig>; | ||
}; | ||
export declare type ActiveInterceptors = { | ||
addBearerOnAllRequests?: boolean; | ||
refreshWhenBearerTokenIsExpired?: boolean; | ||
logoutWhenResponseIsUnauthorized?: boolean; | ||
}; | ||
export declare type InitializeAxiosInterceptors = { | ||
interceptors: AxiosInterceptors; | ||
active?: { | ||
addBearerOnAllRequests?: boolean; | ||
refreshWhenBearerTokenIsExpired?: boolean; | ||
logoutWhenResponseIsUnauthorized?: boolean; | ||
}; | ||
active?: ActiveInterceptors; | ||
}; | ||
export declare type IsTimestampExpiredWithAntecipation = { | ||
timestampExpiration: number; | ||
antecipation: number; | ||
}; | ||
export declare type TryRefreshTokenCallback = { | ||
token: string | undefined; | ||
token: string | null; | ||
tryRefreshToken: (params: TryRefreshTokenParams) => Promise<void>; | ||
@@ -214,3 +204,3 @@ tryRefreshTokenParams: TryRefreshTokenParams; | ||
export declare type RefreshOrLogin = { | ||
refreshToken?: string; | ||
refreshToken: string | null; | ||
isSupport: boolean; | ||
@@ -220,5 +210,1 @@ callbackRefresh: () => void; | ||
}; | ||
export declare type InitRefreshTokenInterceptor = { | ||
_interceptor: AxiosInterceptorManager<AxiosRequestConfig>; | ||
bearerExpirationTimestamp: number | null; | ||
}; |
@@ -1,9 +0,6 @@ | ||
import { IsTimestampExpiredWithAntecipation } from './types'; | ||
declare function getRefreshTokenFromCookie(): string | undefined; | ||
declare function saveRefreshTokenOnCookie(refreshToken: string): void; | ||
declare function eraseRefreshTokenOnCookie(): void; | ||
declare function getRefreshTokenFromSessionStorage(): string | null; | ||
declare function saveRefreshTokenOnSessionStorage(refreshToken: string): void; | ||
declare function eraseRefreshTokenOnSessionStorage(): void; | ||
declare function findTarget(mapData: undefined | string, apiResultData: any): any; | ||
declare function isComingFromBackOffice(urlParam: string | null | undefined): boolean; | ||
declare function isTimestampExpired(timestampExpiration: number): boolean; | ||
declare function isTimestampExpiredWithAntecipation({ timestampExpiration, antecipation, }: IsTimestampExpiredWithAntecipation): boolean; | ||
export { getRefreshTokenFromCookie, saveRefreshTokenOnCookie, eraseRefreshTokenOnCookie, findTarget, isComingFromBackOffice, isTimestampExpired, isTimestampExpiredWithAntecipation, }; | ||
export { findTarget, isComingFromBackOffice, getRefreshTokenFromSessionStorage, saveRefreshTokenOnSessionStorage, eraseRefreshTokenOnSessionStorage, }; |
@@ -1,18 +0,14 @@ | ||
import { getUnixTime } from 'date-fns'; | ||
function getRefreshTokenFromCookie() { | ||
var _a; | ||
var value = "; " + document.cookie; | ||
var parts = value.split("; " + 'refreshToken' + "="); | ||
if (parts.length === 2) | ||
return (_a = parts.pop()) === null || _a === void 0 ? void 0 : _a.split(';').shift(); | ||
function getRefreshTokenFromSessionStorage() { | ||
return sessionStorage.getItem('refreshToken'); | ||
} | ||
function saveRefreshTokenOnCookie(refreshToken) { | ||
document.cookie = "refreshToken=" + refreshToken + "; path=/; expires=Session"; | ||
function saveRefreshTokenOnSessionStorage(refreshToken) { | ||
sessionStorage.setItem('refreshToken', refreshToken); | ||
} | ||
function eraseRefreshTokenOnCookie() { | ||
document.cookie = 'refreshToken= ; expires = Thu, 01 Jan 1970 00:00:00 GMT'; | ||
function eraseRefreshTokenOnSessionStorage() { | ||
sessionStorage.removeItem('refreshToken'); | ||
} | ||
function findTarget(mapData, apiResultData) { | ||
return ((mapData === null || mapData === void 0 ? void 0 : mapData.split('.').reduce(function (acc, curr) { | ||
return (acc === null || acc === void 0 ? void 0 : acc[curr]) || apiResultData[curr]; | ||
var _a; | ||
return ((_a = acc) === null || _a === void 0 ? void 0 : _a[curr]) || apiResultData[curr]; | ||
}, {})) || apiResultData); | ||
@@ -28,17 +24,2 @@ } | ||
} | ||
function isTimestampExpired(timestampExpiration) { | ||
var timestampNow = getUnixTime(new Date()); | ||
if (timestampExpiration <= timestampNow) { | ||
return true; | ||
} | ||
return false; | ||
} | ||
function isTimestampExpiredWithAntecipation(_a) { | ||
var timestampExpiration = _a.timestampExpiration, antecipation = _a.antecipation; | ||
var timestampNow = getUnixTime(new Date()); | ||
if (timestampExpiration - antecipation <= timestampNow) { | ||
return true; | ||
} | ||
return false; | ||
} | ||
export { getRefreshTokenFromCookie, saveRefreshTokenOnCookie, eraseRefreshTokenOnCookie, findTarget, isComingFromBackOffice, isTimestampExpired, isTimestampExpiredWithAntecipation, }; | ||
export { findTarget, isComingFromBackOffice, getRefreshTokenFromSessionStorage, saveRefreshTokenOnSessionStorage, eraseRefreshTokenOnSessionStorage, }; |
@@ -13,4 +13,3 @@ var __assign = (this && this.__assign) || function () { | ||
import { faker } from './test.tools'; | ||
import { getUnixTime, subDays, subHours, subSeconds, addDays, addHours, addSeconds, } from 'date-fns'; | ||
import { saveRefreshTokenOnCookie, getRefreshTokenFromCookie, eraseRefreshTokenOnCookie, findTarget, isComingFromBackOffice, isTimestampExpired, isTimestampExpiredWithAntecipation, } from './utils'; | ||
import { findTarget, isComingFromBackOffice, getRefreshTokenFromSessionStorage, saveRefreshTokenOnSessionStorage, eraseRefreshTokenOnSessionStorage, } from './utils'; | ||
var random = faker.random; | ||
@@ -20,19 +19,4 @@ var initialState = random.word(); | ||
beforeEach(function () { | ||
saveRefreshTokenOnCookie(initialState); | ||
saveRefreshTokenOnSessionStorage(initialState); | ||
}); | ||
var oneDayInSeconds = 86400; | ||
var oneHourInSeconds = 3600; | ||
var tenSecondsInSeconds = 10; | ||
it('should get refresh token on cookie', function () { | ||
expect(getRefreshTokenFromCookie()).toBe(initialState); | ||
}); | ||
it('should set refresh token cookie', function () { | ||
var refreshToken = random.word(); | ||
saveRefreshTokenOnCookie(refreshToken); | ||
expect(getRefreshTokenFromCookie()).toBe(refreshToken); | ||
}); | ||
it('should erase refresh token on cookie', function () { | ||
eraseRefreshTokenOnCookie(); | ||
expect(getRefreshTokenFromCookie()).toBe(undefined); | ||
}); | ||
it('should pass mapData as data.dados.0.map.0 and return mapped object', function () { | ||
@@ -134,52 +118,36 @@ var mapData = 'data.dados.0.map.0'; | ||
}); | ||
it('should return true if timestamp is expired', function () { | ||
var yesterday = getUnixTime(subDays(new Date(), 1)); | ||
var oneHourAgo = getUnixTime(subHours(new Date(), 1)); | ||
var tenSecondsAgo = getUnixTime(subSeconds(new Date(), 10)); | ||
expect(isTimestampExpired(yesterday)).toBe(true); | ||
expect(isTimestampExpired(oneHourAgo)).toBe(true); | ||
expect(isTimestampExpired(tenSecondsAgo)).toBe(true); | ||
it('getRefreshTokenFromSessionStorage', function () { | ||
var refreshToken = random.word(); | ||
Object.assign(window.location, { | ||
pathname: '/other-path', | ||
}); | ||
sessionStorage.setItem('refreshToken', refreshToken); | ||
expect(getRefreshTokenFromSessionStorage()).toBe(refreshToken); | ||
}); | ||
it('should return true if timestamp is expired with antecipation', function () { | ||
var tommorrow = getUnixTime(addDays(new Date(), 1)); | ||
var oneHourFromNow = getUnixTime(addHours(new Date(), 1)); | ||
var tenSecondsFromNow = getUnixTime(addSeconds(new Date(), 10)); | ||
expect(isTimestampExpiredWithAntecipation({ | ||
timestampExpiration: tommorrow, | ||
antecipation: oneDayInSeconds, | ||
})).toBe(true); | ||
expect(isTimestampExpiredWithAntecipation({ | ||
timestampExpiration: oneHourFromNow, | ||
antecipation: oneHourInSeconds, | ||
})).toBe(true); | ||
expect(isTimestampExpiredWithAntecipation({ | ||
timestampExpiration: tenSecondsFromNow, | ||
antecipation: tenSecondsInSeconds, | ||
})); | ||
it('saveRefreshTokenOnSessionStorage', function () { | ||
var refreshToken = random.word(); | ||
saveRefreshTokenOnSessionStorage(refreshToken); | ||
expect(sessionStorage.getItem('refreshToken')).toBe(refreshToken); | ||
}); | ||
it('should return false if timestamp is not expired', function () { | ||
var tommorrow = getUnixTime(addDays(new Date(), 1)); | ||
var oneHourFromNow = getUnixTime(addHours(new Date(), 1)); | ||
var tenSecondsFromNow = getUnixTime(addSeconds(new Date(), 10)); | ||
expect(isTimestampExpired(tommorrow)).toBe(false); | ||
expect(isTimestampExpired(oneHourFromNow)).toBe(false); | ||
expect(isTimestampExpired(tenSecondsFromNow)).toBe(false); | ||
it('saveRefreshTokenOnSessionStorage only on main path', function () { | ||
var refreshToken = random.word(); | ||
Object.assign(window.location, { | ||
pathname: '/other-path', | ||
}); | ||
saveRefreshTokenOnSessionStorage(refreshToken); | ||
expect(sessionStorage.getItem('refreshToken')).toBe(refreshToken); | ||
}); | ||
it('should return false if timestamp is not expired with antecipation', function () { | ||
var yesterday = getUnixTime(subDays(new Date(), 1)); | ||
var oneHourAgo = getUnixTime(subHours(new Date(), 1)); | ||
var tenSecondsAgo = getUnixTime(subSeconds(new Date(), 10)); | ||
expect(isTimestampExpiredWithAntecipation({ | ||
timestampExpiration: yesterday, | ||
antecipation: -(oneDayInSeconds + 5), | ||
})).toBe(false); | ||
expect(isTimestampExpiredWithAntecipation({ | ||
timestampExpiration: oneHourAgo, | ||
antecipation: -(oneHourInSeconds + 5), | ||
})).toBe(false); | ||
expect(isTimestampExpiredWithAntecipation({ | ||
timestampExpiration: tenSecondsAgo, | ||
antecipation: -(tenSecondsInSeconds + 5), | ||
})).toBe(false); | ||
it('eraseRefreshTokenOnSessionStorage', function () { | ||
sessionStorage.setItem('refreshToken', random.word()); | ||
eraseRefreshTokenOnSessionStorage(); | ||
expect(sessionStorage.getItem('refreshToken')).toBeNull(); | ||
}); | ||
it('eraseRefreshTokenOnSessionStorage only on main path', function () { | ||
Object.assign(window.location, { | ||
pathname: '/other-path', | ||
}); | ||
sessionStorage.setItem('refreshToken', random.word()); | ||
eraseRefreshTokenOnSessionStorage(); | ||
expect(sessionStorage.getItem('refreshToken')).toBeNull(); | ||
}); | ||
}); |
{ | ||
"name": "@eduzz/accounts-react-wrapper", | ||
"version": "1.1.4", | ||
"version": "1.1.5-beta.0", | ||
"main": "./lib/cjs/index.js", | ||
@@ -19,3 +19,4 @@ "module": "./lib/esm/index.js", | ||
"test": "react-scripts test", | ||
"test:ci": "react-scripts test --coverage --watchAll=false" | ||
"test:ci": "react-scripts test --coverage --watchAll=false", | ||
"start": "react-scripts start" | ||
}, | ||
@@ -22,0 +23,0 @@ "devDependencies": { |
@@ -5,10 +5,8 @@ # Eduzz Accounts React Wrapper | ||
**SDK** para fazer **integração de aplicações react** com o **accounts**, sistema de autenticação único da Eduzz. Seu escopo **é autenticação**, e **não autorização**. | ||
## **SDK** para fazer **integração de aplicações react** com o **accounts**, sistema de autenticação único da Eduzz. O SDK também disponibiliza uma funcionalidade de autorização através de interceptors para o axios. | ||
--- | ||
## Pré-requisitos | ||
- [ ] CDN do script fornecido pela Eduzz, adicionado no index.html | ||
- [ ] Frontend em ReactJS | ||
- [ ] Frontend utilizando ReactJS | ||
- [ ] Backend deve disponibilizar duas rotas, uma para login e outra para refresh token. | ||
@@ -38,3 +36,3 @@ | ||
### [1. Colocar o script fornecido pela Eduzz, em root/public/index.html do projeto react.](#script-eduzz) | ||
### [1. Colocar o script fornecido pela Eduzz, em public/index.html do projeto ReactJS](#script-eduzz) | ||
@@ -66,3 +64,3 @@ ```html | ||
```jsx | ||
// Nome de arquivo sugerido: accounts.config.ts | ||
// Nome de arquivo sugerido: config/accounts.ts | ||
// Exemplo: | ||
@@ -168,3 +166,3 @@ import { | ||
import { AuthProvider } from '@eduzz/accounts-react-wrapper'; | ||
import config from './accounts.config.ts'; | ||
import config from './config/accounts.ts'; | ||
@@ -215,2 +213,3 @@ ReactDOM.render( | ||
import { useAuth } from '@eduzz/accounts-react-wrapper'; | ||
import axios from 'axios' | ||
@@ -220,3 +219,2 @@ type ExapledBearerTokenDecoded = { | ||
email: string; | ||
exp: number; | ||
} | ||
@@ -227,5 +225,5 @@ | ||
function tryInitializeInterceptors() { | ||
interceptors?.axios.initialize({ | ||
interceptors: Apis.produtoFisicoApi.instance.interceptors, | ||
useEffect(()=>{ | ||
interceptors?.axios.initialize({ | ||
interceptors: axios.interceptors, | ||
active: { // não obrigatório, se não passar ativa todos os interceptors. | ||
@@ -237,6 +235,2 @@ addBearerOnAllRequests: true, // default | ||
}); | ||
} | ||
useEffect(()=>{ | ||
tryInitializeInterceptors(); | ||
},[bearerToken]) | ||
@@ -259,11 +253,1 @@ | ||
``` | ||
--- | ||
## Tecnologias e ferramentas | ||
- [React](https://pt-br.reactjs.org/) | ||
- [Axios](https://github.com/axios/axios) | ||
- [Jest](https://jestjs.io/pt-BR/) | ||
- [Typescript](https://www.typescriptlang.org/) | ||
- [JSONWebToken](https://www.npmjs.com/package/jsonwebtoken) |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
83
180763
3726
2
245