Skip to content

Commit

Permalink
code cleanup, es6 things
Browse files Browse the repository at this point in the history
  • Loading branch information
panva committed Apr 3, 2017
1 parent 3eab3a4 commit f65a1b3
Show file tree
Hide file tree
Showing 25 changed files with 214 additions and 269 deletions.
3 changes: 2 additions & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"extends": "airbnb-base",
"rules": {
"no-param-reassign": ["error", { "props": true, "ignorePropertyModificationsFor": ["ctx", "opts"] }]
"no-param-reassign": ["error", { "props": true, "ignorePropertyModificationsFor": ["ctx", "opts", "options"] }],
"no-underscore-dangle": ["error", { "allow": ["_claim_names", "_claim_sources"] }],
}
}
5 changes: 1 addition & 4 deletions lib/actions/authorization/check_openid_present.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,6 @@ const { InvalidRequestError } = require('../../helpers/errors');
*/
module.exports = async function checkOpenIdPresent(ctx, next) {
const scopes = ctx.oidc.params.scope.split(' ');

ctx.assert(scopes.indexOf('openid') !== -1,
new InvalidRequestError('openid is required scope'));

ctx.assert(scopes.includes('openid'), new InvalidRequestError('openid is required scope'));
await next();
};
2 changes: 1 addition & 1 deletion lib/actions/authorization/check_pixy.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ module.exports = (provider) => {
const { params } = ctx.oidc;

if (pkce && params.code_challenge_method) {
ctx.assert(ALLOWED.indexOf(params.code_challenge_method) !== -1,
ctx.assert(ALLOWED.includes(params.code_challenge_method),
new InvalidRequestError('not supported value of code_challenge_method'));

ctx.assert(params.code_challenge,
Expand Down
2 changes: 1 addition & 1 deletion lib/actions/authorization/check_prompt.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ module.exports = provider => async function checkPrompt(ctx, next) {
ctx.assert(isEmpty(unsupported), new InvalidRequestError(
`invalid prompt value(s) provided. (${unsupported.join(',')})`));

ctx.assert(prompts.indexOf('none') === -1 || prompts.length === 1,
ctx.assert(!prompts.includes('none') || prompts.length === 1,
new InvalidRequestError('prompt none must only be used alone'));
}

Expand Down
3 changes: 1 addition & 2 deletions lib/actions/authorization/check_response_type.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@ module.exports = provider => async function checkResponseType(ctx, next) {
const { params } = ctx.oidc;
const supported = instance(provider).configuration('responseTypes');

const valid = supported.indexOf(params.response_type) !== -1;
ctx.assert(valid, 400, 'unsupported_response_type', {
ctx.assert(supported.includes(params.response_type), 400, 'unsupported_response_type', {
error_description: `response_type not supported. (${params.response_type})`,
});

Expand Down
7 changes: 3 additions & 4 deletions lib/actions/authorization/check_scope.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@ module.exports = provider => async function checkScope(ctx, next) {
ctx.assert(_.isEmpty(unsupported), new InvalidRequestError(
`invalid scope value(s) provided. (${unsupported.join(',')})`));

ctx.assert(scopes.indexOf('openid') !== -1,
new InvalidRequestError('openid is required scope'));
ctx.assert(scopes.includes('openid'), new InvalidRequestError('openid is required scope'));

/*
* Upon receipt of a scope parameter containing the offline_access value, the Authorization Server
Expand All @@ -27,8 +26,8 @@ module.exports = provider => async function checkScope(ctx, next) {
* would result in an Authorization Code being returned,
*/

if (scopes.indexOf('offline_access') !== -1) {
if (!responseType.includes('code') || prompts.indexOf('consent') === -1) {
if (scopes.includes('offline_access')) {
if (!responseType.includes('code') || !prompts.includes('consent')) {
_.pull(scopes, 'offline_access').join(' ');
}
}
Expand Down
6 changes: 3 additions & 3 deletions lib/actions/authorization/decode_request.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ module.exports = (provider) => {
try {
const header = JWT.header(params.request);

assert(conf('requestObjectEncryptionAlgValues').indexOf(header.alg) !== -1,
assert(conf('requestObjectEncryptionAlgValues').includes(header.alg),
'unsupported encrypted request alg');
assert(conf('requestObjectEncryptionEncValues').indexOf(header.enc) !== -1,
assert(conf('requestObjectEncryptionEncValues').includes(header.enc),
'unsupported encrypted request enc');

const decrypted = await JWT.decrypt(params.request, map.keystore);
Expand Down Expand Up @@ -78,7 +78,7 @@ module.exports = (provider) => {
error_description: 'the preregistered alg must be used in request or request_uri',
});
} else {
ctx.assert(conf('requestObjectSigningAlgValues').indexOf(alg) !== -1, 400,
ctx.assert(conf('requestObjectSigningAlgValues').includes(alg), 400,
'invalid_request_object', { error_description: 'unsupported signed request alg' });
}

Expand Down
13 changes: 6 additions & 7 deletions lib/actions/authorization/interactions.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,26 +54,24 @@ module.exports = (provider) => {
// session subject value differs from the one requested
(ctx) => {
if (_.has(ctx.oidc.claims, 'id_token.sub.value')) {
const subject = Claims.sub(ctx.oidc.session.accountId(), ctx.oidc.client.sectorIdentifier); // eslint-disable-line max-len
const subject = Claims.sub(ctx.oidc.session.accountId(), ctx.oidc.client.sectorIdentifier);
if (ctx.oidc.claims.id_token.sub.value !== subject) {
return {
error: 'login_required',
error_description: 'requested subject could not be obtained',
reason: 'claims_id_token_sub_value',
reason_description:
`${ctx.oidc.client.name || ctx.oidc.client.clientId} asks you to Sign-in with a specific identity.`,
reason_description: `${ctx.oidc.client.name || ctx.oidc.client.clientId} asks you to Sign-in with a specific identity.`,
};
}
}
return false;
},

// none of multiple authentication context class references requested
// are met
// none of multiple authentication context class references requested are met
(ctx) => {
const request = _.get(ctx.oidc.claims, 'id_token.acr', {});
if (request && request.essential && request.values) {
if (request.values.indexOf(ctx.oidc.acr) === -1) {
if (!request.values.includes(ctx.oidc.acr)) {
return {
error: 'login_required',
error_description: 'none of the requested ACRs could not be obtained',
Expand Down Expand Up @@ -125,7 +123,7 @@ module.exports = (provider) => {
const hint = ctx.oidc.params.id_token_hint;
if (hint !== undefined) {
const { client } = ctx.oidc;
const actualSub = Claims.sub(ctx.oidc.session.accountId(), client.sectorIdentifier); // eslint-disable-line max-len
const actualSub = Claims.sub(ctx.oidc.session.accountId(), client.sectorIdentifier);
const { IdToken } = provider;

const decoded = await IdToken.validate(hint, client).catch((err) => {
Expand All @@ -151,6 +149,7 @@ module.exports = (provider) => {
return async function interactions(ctx, next) {
let interaction;

// interaction checks are intended to run sequential and some are async
for (const fn of interactionChecks) { // eslint-disable-line no-restricted-syntax
interaction = await fn(ctx); // eslint-disable-line no-await-in-loop
if (interaction) break;
Expand Down
2 changes: 1 addition & 1 deletion lib/actions/registration.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const FORBIDDEN = [
];

function findMissingKey(value, key) {
return FORBIDDEN.indexOf(key) === -1 && !has(this.oidc.body, key) && value !== undefined;
return !FORBIDDEN.includes(key) && !has(this.oidc.body, key) && value !== undefined;
}

module.exports = function registrationAction(provider) {
Expand Down
4 changes: 2 additions & 2 deletions lib/actions/token/authorization_code.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,9 @@ module.exports.handler = function getAuthorizationCodeHandler(provider) {
const { expiresIn } = AccessToken;

let refreshToken;
const grantPresent = ctx.oidc.client.grantTypes.indexOf('refresh_token') !== -1;
const grantPresent = ctx.oidc.client.grantTypes.includes('refresh_token');
const shouldIssue = instance(provider).configuration('features.alwaysIssueRefresh') ||
code.scope.split(' ').indexOf('offline_access') !== -1;
code.scope.split(' ').includes('offline_access');

if (grantPresent && shouldIssue) {
const rt = new RefreshToken({
Expand Down
2 changes: 0 additions & 2 deletions lib/helpers/claims.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@ module.exports = function getClaims(config) {
.intersection(config.claimsSupported)
.value();

/* eslint-disable no-underscore-dangle */
const claims = _.pick(available, include);

if (available._claim_names && available._claim_sources) {
Expand All @@ -79,7 +78,6 @@ module.exports = function getClaims(config) {
delete claims._claim_sources;
}
}
/* eslint-enable */

if (this.sector && claims.sub) {
claims.sub = this.constructor.sub(claims.sub, this.sector);
Expand Down
41 changes: 19 additions & 22 deletions lib/helpers/client_schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ module.exports = function getSchema(provider) {
token_endpoint_auth_signing_alg: instance(provider).configuration('tokenEndpointAuthSigningAlgValues'),
userinfo_signed_response_alg: () => instance(provider).configuration('userinfoSigningAlgValues'),
id_token_signed_response_alg: (metadata) => {
if (metadata.response_types.join(' ').indexOf('token') === -1) {
if (!metadata.response_types.join(' ').includes('token')) {
return instance(provider).configuration('idTokenSigningAlgValues');
}
return _.without(instance(provider).configuration('idTokenSigningAlgValues'), 'none');
Expand Down Expand Up @@ -235,7 +235,11 @@ module.exports = function getSchema(provider) {
}
}

// CLIENT SECRET LENGHT
if (instance(provider).Client.needsSecret(this) && !this.client_secret) {
invalidate('client_secret is mandatory property');
}

// CLIENT SECRET LENGTH
const hsLengths = SECRET_LENGTH_REQUIRED.map((prop) => {
if (this[prop] && this[prop].startsWith('HS')) {
return parseInt(this[prop].slice(-3) / 8, 10);
Expand All @@ -246,13 +250,6 @@ module.exports = function getSchema(provider) {

const validateSecretLength = _.max(hsLengths);

const validateSecretPresence = validateSecretLength ||
['private_key_jwt', 'none'].indexOf(this.token_endpoint_auth_method) === -1;

if (validateSecretPresence && !this.client_secret) {
invalidate('client_secret is mandatory property');
}

if (validateSecretLength) {
if (this.client_secret.length < validateSecretLength) {
invalidate('insufficient client_secret length');
Expand Down Expand Up @@ -309,7 +306,7 @@ module.exports = function getSchema(provider) {
strings() {
STRING.forEach((prop) => {
if (this[prop] !== undefined) {
const isAry = ARYS.indexOf(prop) !== -1;
const isAry = ARYS.includes(prop);
(isAry ? this[prop] : [this[prop]]).forEach((val) => {
if (typeof val !== 'string' || !val.length) {
invalidate(isAry ?
Expand All @@ -324,9 +321,9 @@ module.exports = function getSchema(provider) {
webUris() {
WEB_URI.forEach((prop) => {
if (this[prop] !== undefined) {
const isAry = ARYS.indexOf(prop) !== -1;
const isAry = ARYS.includes(prop);
(isAry ? this[prop] : [this[prop]]).forEach((val) => {
const method = HTTPS_URI.indexOf(prop) === -1 ? 'isWebUri' : 'isHttpsUri';
const method = HTTPS_URI.includes(prop) ? 'isHttpsUri' : 'isWebUri';
const type = method === 'isWebUri' ? 'web' : 'https';
if (!validUrl[method](val)) {
invalidate(isAry ?
Expand Down Expand Up @@ -387,15 +384,15 @@ module.exports = function getSchema(provider) {
}

if (this[prop] !== undefined) {
const isAry = ARYS.indexOf(prop) !== -1;
const isAry = ARYS.includes(prop);
if (isAry && this[prop].some((val) => {
if (only instanceof Set) {
return !only.has(val);
}
return only.indexOf(val) === -1;
return !only.includes(val);
})) {
invalidate(`${prop} can only contain members [${only}]`);
} else if (!isAry && only.indexOf(this[prop]) === -1) {
} else if (!isAry && !only.includes(this[prop])) {
invalidate(`${prop} must be one of [${only}]`);
}
}
Expand All @@ -409,7 +406,7 @@ module.exports = function getSchema(provider) {
this.redirect_uris = _.map(this.redirect_uris, (redirectUri) => {
const parsed = url.parse(redirectUri);
// remove the port component, making dynamic ports allowed for loopback uris
if (parsed.protocol === 'http:' && LOOPBACKS.indexOf(parsed.hostname) !== -1) {
if (parsed.protocol === 'http:' && LOOPBACKS.includes(parsed.hostname)) {
return url.format(Object.assign(parsed, {
host: null,
port: null,
Expand All @@ -422,7 +419,7 @@ module.exports = function getSchema(provider) {

redirectUris() {
this.redirect_uris.forEach((redirectUri) => {
if (redirectUri.indexOf('#') !== -1) {
if (redirectUri.includes('#')) {
invalidate('redirect_uris must not contain fragments');
}

Expand All @@ -432,11 +429,11 @@ module.exports = function getSchema(provider) {
invalidate('redirect_uris must only contain valid web uris');
}

if (this.grant_types.indexOf('implicit') !== -1 && redirectUri.startsWith('http:')) {
if (this.grant_types.includes('implicit') && redirectUri.startsWith('http:')) {
invalidate('redirect_uris for web clients using implicit flow MUST only register URLs using the https scheme');
}

if (this.grant_types.indexOf('implicit') !== -1 && url.parse(redirectUri).hostname === 'localhost') {
if (this.grant_types.includes('implicit') && url.parse(redirectUri).hostname === 'localhost') {
invalidate('redirect_uris for web clients using implicit flow must not be using localhost');
}
break;
Expand All @@ -450,17 +447,17 @@ module.exports = function getSchema(provider) {

switch (uri.protocol) {
case 'http:': // Loopback URI Redirection
if (LOOPBACKS.indexOf(uri.hostname) === -1) {
if (!LOOPBACKS.includes(uri.hostname)) {
invalidate('redirect_uris for native clients using http as a protocol can only use loopback addresses as hostnames');
}
break;
case 'https:': // App-claimed HTTPS URI Redirection
if (LOOPBACKS.indexOf(uri.hostname) !== -1) {
if (LOOPBACKS.includes(uri.hostname)) {
invalidate(`redirect_uris for native clients using claimed HTTPS URIs must not be using ${uri.hostname} as hostname`);
}
break;
default: // App-declared Custom URI Scheme Redirection
if (uri.protocol.indexOf('.') === -1) {
if (!uri.protocol.includes('.')) {
invalidate('redirect_uris for native clients using Custom URI scheme should use reverse domain name based scheme');
}
}
Expand Down
6 changes: 3 additions & 3 deletions lib/helpers/configuration.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,12 @@ class Configuration {

this.subjectTypes.forEach((type) => {
/* istanbul ignore if */
if (['public', 'pairwise'].indexOf(type) === -1) {
if (!['public', 'pairwise'].includes(type)) {
throw new Error('only public and pairwise subjectTypes are supported');
}
});

if (this.subjectTypes.indexOf('pairwise') !== -1 && !this.pairwiseSalt) {
if (this.subjectTypes.includes('pairwise') && !this.pairwiseSalt) {
throw new Error(
'pairwiseSalt must be configured when pairwise subjectType is to be supported');
}
Expand All @@ -47,7 +47,7 @@ class Configuration {
/* eslint-disable no-restricted-syntax, no-console */
if (process.env.NODE_ENV !== 'test') {
for (const flag in this.features) {
if (this.features[flag] && STABLE_FLAGS.indexOf(flag) === -1) {
if (this.features[flag] && !STABLE_FLAGS.includes(flag)) {
console.info(`NOTICE: a draft/experimental feature (${flag}) enabled, future updates to \
this feature will be released as MINOR releases`);
}
Expand Down
14 changes: 7 additions & 7 deletions lib/helpers/configuration_schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,15 +78,15 @@ module.exports = class ConfigurationSchema {
this.grantTypes = new Set();

this.responseTypes.forEach((responseType) => {
if (responseType.indexOf('token') !== -1) {
if (responseType.includes('token')) {
this.grantTypes.add('implicit');
}
if (responseType.indexOf('code') !== -1) {
if (responseType.includes('code')) {
this.grantTypes.add('authorization_code');
}
});

if (this.features.alwaysIssueRefresh || this.scopes.indexOf('offline_access') !== -1) {
if (this.features.alwaysIssueRefresh || this.scopes.includes('offline_access')) {
this.grantTypes.add('refresh_token');
}

Expand All @@ -102,7 +102,7 @@ module.exports = class ConfigurationSchema {
.value();

scopes.forEach((scope) => {
if (this.scopes.indexOf(scope) === -1) {
if (!this.scopes.includes(scope)) {
this.scopes.push(scope);
}
});
Expand All @@ -121,7 +121,7 @@ module.exports = class ConfigurationSchema {
}

ensureOpenIdSub() {
if (Object.keys(this.claims.openid).indexOf('sub') === -1) {
if (!Object.keys(this.claims.openid).includes('sub')) {
this.claims.openid.sub = null;
}
}
Expand Down Expand Up @@ -155,11 +155,11 @@ module.exports = class ConfigurationSchema {

this.tokenEndpointAuthSigningAlgValues = _.without(fullSig, 'none');

if (this.tokenEndpointAuthMethods.indexOf('client_secret_jwt') === -1) {
if (!this.tokenEndpointAuthMethods.includes('client_secret_jwt')) {
_.remove(this.tokenEndpointAuthSigningAlgValues, alg => alg.startsWith('HS'));
}

if (this.tokenEndpointAuthMethods.indexOf('private_key_jwt') === -1) {
if (!this.tokenEndpointAuthMethods.includes('private_key_jwt')) {
_.remove(this.tokenEndpointAuthSigningAlgValues, alg => alg.match(/^(E|P|R)S/));
}

Expand Down
2 changes: 1 addition & 1 deletion lib/helpers/epoch_time.js
Original file line number Diff line number Diff line change
@@ -1 +1 @@
module.exports = date => (date || Date.now()) / 1000 | 0; // eslint-disable-line no-bitwise
module.exports = (date = Date.now()) => date / 1000 | 0; // eslint-disable-line no-bitwise
2 changes: 1 addition & 1 deletion lib/helpers/initialize_clients.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@ function addClient(client) {
}

module.exports = function initializeClients(clients = []) {
return Promise.all(clients.map(addClient.bind(this)));
return Promise.all(clients.map(addClient, this));
};
Loading

0 comments on commit f65a1b3

Please sign in to comment.