@coolio/auth-interceptor
Version:
Authentication interceptor for Coolio
74 lines • 3.42 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());
});
};
import { HttpCode, HttpResponseError, isHttpResponseError } from '@coolio/http';
import { SimpleQueue } from './simpleQueue';
import { AuthError } from './authError';
export const hasUnauthorizedResponseCode = (response) => response.status === HttpCode.UNAUTHORIZED;
export const isUnauthorizedError = (error) => isHttpResponseError(error) && hasUnauthorizedResponseCode(error.response);
export class AuthInterceptor {
constructor(options) {
this.options = options;
this.queue = new SimpleQueue();
}
get pendingRequestCount() {
return this.queue.length;
}
onIntercept(request, options) {
if (this.options.canAuthorize(options)) {
return () => this.queue.put(() => __awaiter(this, void 0, void 0, function* () {
yield Promise.resolve(this.options.setAuthorizationData(options));
return yield this.handleUnauthorizedResponse(request, () => __awaiter(this, void 0, void 0, function* () {
yield this.requestReauthorization();
yield Promise.resolve(this.options.setAuthorizationData(options));
return this.handleUnauthorizedResponse(request, error => this.handleAuthorizationError(error));
}));
}));
}
return request;
}
requestReauthorization() {
return __awaiter(this, void 0, void 0, function* () {
try {
yield Promise.resolve(this.options.reauthorize());
}
catch (error) {
yield this.handleAuthorizationError(error);
}
});
}
;
handleAuthorizationError(error) {
return __awaiter(this, void 0, void 0, function* () {
const authError = new AuthError('Reauthorization failed or credentials are invalid.', error);
this.queue.clean(authError);
yield Promise.resolve(this.options.onAuthorizationFailure(authError));
throw authError;
});
}
handleUnauthorizedResponse(request, onUnauthorizedResponse) {
return __awaiter(this, void 0, void 0, function* () {
try {
const response = yield request();
if (hasUnauthorizedResponseCode(response)) {
throw new HttpResponseError(response);
}
return response;
}
catch (error) {
if (!isUnauthorizedError(error)) {
throw error;
}
return yield onUnauthorizedResponse(error);
}
});
}
}
export const createAuthInterceptor = (options) => new AuthInterceptor(options);
//# sourceMappingURL=authInterceptor.js.map