whodis-react
Version:
React hooks and components for secure, best practices authentication in seconds
53 lines • 2.33 kB
JavaScript
;
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());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getAuthableToken = void 0;
const whodis_client_1 = require("whodis-client");
const refreshToken_1 = require("./refreshToken");
/**
* internal use only
*
* usecase:
* - you need the token for making authenticated requests
*
* action:
* - grabs the token from storage and refreshes it before responding if needed
*
* note:
* - if you need a _sync_ response, see if all you really need is `getTokenData`.
*/
const getAuthableToken = ({ storage, }) => __awaiter(void 0, void 0, void 0, function* () {
// grab the token from storage
const token = yield storage.get();
if (!token)
return null;
// extract data about the token
const expired = (0, whodis_client_1.isTokenExpired)({ token });
const refreshable = (0, whodis_client_1.isTokenRefreshable)({ token });
// if token is not expired, return it
if (!expired)
return token;
// if not refreshable, same thing as not having a token
if (!refreshable)
return null;
// if expired but refreshable, refresh it
try {
const refreshedToken = yield (0, refreshToken_1.refreshToken)({ storage }); // refresh it
yield storage.set(refreshedToken); // save the refreshed token for future calls
return refreshedToken; // and give the refresh token for usage
}
catch (error) {
console.warn('could not refresh token', { error });
return null; // if we had an error refreshing the token, return null
}
});
exports.getAuthableToken = getAuthableToken;
//# sourceMappingURL=getAuthableToken.js.map