Skip to content

Commit

Permalink
Merge branch 'release/v1.0.0' into develop
Browse files Browse the repository at this point in the history
  • Loading branch information
kuyoonjo committed Jun 29, 2018
2 parents c1a1bfc + bc3f61c commit 57af631
Show file tree
Hide file tree
Showing 14 changed files with 57 additions and 76 deletions.
6 changes: 3 additions & 3 deletions __tests__/attachAuth-spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { attachAuth, IConfig } from '../src'
import { attachAuth, IConfig } from '../src';

console.error = jest.fn();
console.log = jest.fn();
Expand All @@ -20,7 +20,7 @@ const config: IConfig = {
enableSimpleAuth: true,
defaultRoles: ['user'],
expiresIn: '10y',
}
};

test('should isAuthenticated', async () => {
const auth: any = {
Expand Down Expand Up @@ -112,4 +112,4 @@ test('should notAcceptable', async () => {

await fn(ctx, next);
expect(ctx.body.statusCode).toBe(406);
});
});
22 changes: 10 additions & 12 deletions __tests__/auth-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ describe('Test Auth', () => {
enableSimpleAuth: true,
defaultRoles: ['user'],
expiresIn: '10y',
}
};

const auth = new Auth(config);

Expand All @@ -28,32 +28,30 @@ describe('Test Auth', () => {
providers: [],
roles: [],
};
const JWT = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOjEsInByb3ZpZGVycyI6W10sInJvbGVzIjpbXSwiaWF0IjoxNTMwMjc5OTE2LCJleHAiOjMxMDgxNTk5MTZ9.9lbXuO4kDeDR2YAFItXoj2gOo-OQXmXm6MSvyie7Eeo';
const JWT_EXPIRED = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOjEsInByb3ZpZGVycyI6W10sInJvbGVzIjpbXSwiaWF0IjoxNTMwMjc5ODYxLCJleHAiOjE1MzAyNzk4NjJ9.5K4x86JqbQ5A4s6vCdDc7U66yry5GpoFrni3qtHWm9E';
const JWT =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOjEsInByb3ZpZGVycyI6W10sInJvbGVzIjpbXSwiaWF0IjoxNTMwMjc5OTE2LCJleHAiOjMxMDgxNTk5MTZ9.9lbXuO4kDeDR2YAFItXoj2gOo-OQXmXm6MSvyie7Eeo';
const JWT_EXPIRED =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOjEsInByb3ZpZGVycyI6W10sInJvbGVzIjpbXSwiaWF0IjoxNTMwMjc5ODYxLCJleHAiOjE1MzAyNzk4NjJ9.5K4x86JqbQ5A4s6vCdDc7U66yry5GpoFrni3qtHWm9E';

test('Should sign', () => {
const jwt1 = auth.signToken(DOC, { });
const jwt2 = sign(DOC, auth.config.secret, { });
const jwt1 = auth.signToken(DOC, {});
const jwt2 = sign(DOC, auth.config.secret, {});
expect(jwt1).toBe(jwt2);
});

test('Should verify success', async () => {
try {
expect(await auth.verifyToken(JWT)).toBeTruthy();
} catch(e) {
} catch (e) {
fail(e);
}
});

test('Should verify fail', async () => {
try {
expect(await auth.verifyToken('JWT')).toBeFalsy();
} catch(e) {
} catch (e) {
fail(e);
}
});



})

});
10 changes: 5 additions & 5 deletions __tests__/getHeaderToken-spec.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { getHeaderToken } from '../src'
import { getHeaderToken } from '../src';

test('should get token', () => {
expect(
getHeaderToken({ headers: { authorization: 'xxx' } } as any)
).toBe(null);
expect(getHeaderToken({ headers: { authorization: 'xxx' } } as any)).toBe(
null
);
expect(getHeaderToken({ headers: {} } as any)).toBe(null);
expect(
getHeaderToken({ headers: { authorization: 'Bearer xxx' } } as any)
).toBe('xxx');
});
});
4 changes: 2 additions & 2 deletions __tests__/hasRoles-spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { hasRoles, IConfig } from '../src'
import { hasRoles, IConfig } from '../src';

console.error = jest.fn();
console.log = jest.fn();
Expand All @@ -20,7 +20,7 @@ const config: IConfig = {
enableSimpleAuth: true,
defaultRoles: ['user'],
expiresIn: '10y',
}
};

test('should hasRoles', async () => {
const auth: any = {
Expand Down
6 changes: 3 additions & 3 deletions __tests__/isAuthenticated-spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Auth, isAuthenticated, IConfig } from '../src'
import { Auth, isAuthenticated, IConfig } from '../src';

console.error = jest.fn();
console.log = jest.fn();
Expand All @@ -20,7 +20,7 @@ const config: IConfig = {
enableSimpleAuth: true,
defaultRoles: ['user'],
expiresIn: '10y',
}
};

test('should isAuthenticated', async () => {
const auth: any = {
Expand Down Expand Up @@ -112,4 +112,4 @@ test('should notAcceptable', async () => {

await fn(ctx, next);
expect(ctx.body.statusCode).toBe(406);
});
});
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
"@ycs/error": "^1.0.1",
"@ycs/interfaces": "^1.0.1",
"jsonwebtoken": "^8.3.0",
"koa-compose": "^4.1.0",
"mongoose-unique-validator": "^2.0.1"
},
"devDependencies": {
Expand Down
38 changes: 16 additions & 22 deletions src/Auth.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,22 @@
import { Schema, model, PaginateModel, Document } from "@ycs/db";
import { Boom, handleError } from "@ycs/error";
import { Schema, model, PaginateModel, Document } from '@ycs/db';
import { Boom } from '@ycs/error';
import { SignOptions, sign, verify } from 'jsonwebtoken';
import * as compose from 'koa-compose';
import * as uniqueValidator from 'mongoose-unique-validator';
import { IConfig } from "./IConfig";
import { randomBytes, pbkdf2 } from "crypto";
import { IContext } from "@ycs/interfaces";
import { IConfig } from './IConfig';
import { randomBytes, pbkdf2 } from 'crypto';

function preValidate(config: IConfig) {
return async function (next) {
return async function(next) {
// Handle new/update passwords
if (!this.isModified('password')) return next();

// Password must not be empty if there is no any providers
if (!this.password || !this.password.length) {
if (!this.providers || !this.providers.length)
return next(
Boom.badData(config.messages.errors.invalid_password)
);
return next(Boom.badData(config.messages.errors.invalid_password));
return next();
}

// Make salt
try {
this.salt = await this.makeSalt();
Expand All @@ -30,15 +26,13 @@ function preValidate(config: IConfig) {
} catch (e) {
next(e);
}
}
}
};
}

export class Auth {
schema: Schema;
model: PaginateModel<Document>;
constructor(
public config: IConfig,
) {
constructor(public config: IConfig) {
this.schema = new Schema(
{
password: {
Expand Down Expand Up @@ -119,7 +113,7 @@ export class Auth {
const pwdGen = await this.encryptPassword(password);
return this.password === pwdGen;
},

/**
* Make salt
*
Expand All @@ -138,7 +132,7 @@ export class Auth {
});
});
},

/**
* Encrypt password
*
Expand Down Expand Up @@ -183,7 +177,7 @@ export class Auth {
this.config.secret,
options
);
};
}

verifyToken(token: string): Promise<any> {
if (!token) return Promise.resolve();
Expand All @@ -193,5 +187,5 @@ export class Auth {
resolve(decoded);
});
});
};
}
}
}
2 changes: 1 addition & 1 deletion src/IConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,4 @@ export interface IConfig {
* Token expires in
*/
expiresIn: string;
}
}
10 changes: 4 additions & 6 deletions src/attachAuth.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
import { Boom, handleError } from "@ycs/error";
import { IContext } from "@ycs/interfaces";
import { Boom, handleError } from '@ycs/error';
import { IContext } from '@ycs/interfaces';

export function attachAuth() {
return async (ctx: IContext, next) => {
try {
if (ctx.request.auth) {
const auth = await this.model.findById(ctx.request.auth._id).exec();
if (!auth)
throw Boom.notAcceptable(
this.config.messages.errors.invalid_token
);
throw Boom.notAcceptable(this.config.messages.errors.invalid_token);
}
await next();
} catch (e) {
handleError(ctx, e);
}
};
};
}
4 changes: 2 additions & 2 deletions src/getHeaderToken.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { IContext } from "@ycs/interfaces";
import { IContext } from '@ycs/interfaces';

export function getHeaderToken(ctx: IContext): string | null {
if (
Expand All @@ -7,4 +7,4 @@ export function getHeaderToken(ctx: IContext): string | null {
)
return null;
return ctx.headers.authorization.substring(7);
}
}
10 changes: 4 additions & 6 deletions src/hasRoles.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,16 @@
import { Boom, handleError } from "@ycs/error";
import { IContext } from "@ycs/interfaces";
import { Boom, handleError } from '@ycs/error';
import { IContext } from '@ycs/interfaces';

export function hasRoles(...roles: string[]) {
return async (ctx: IContext, next) => {
try {
for (const role of roles) {
if (!ctx.request.auth.roles.includes(role))
throw Boom.forbidden(
this.config.messages.errors.no_permission
);
throw Boom.forbidden(this.config.messages.errors.no_permission);
}
await next();
} catch (e) {
handleError(ctx, e);
}
};
};
}
10 changes: 4 additions & 6 deletions src/isAuthenticated.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Boom, handleError } from "@ycs/error";
import { IContext } from "@ycs/interfaces";
import { Boom, handleError } from '@ycs/error';
import { IContext } from '@ycs/interfaces';

export function isAuthenticated() {
return async (ctx: IContext, next) => {
Expand All @@ -8,12 +8,10 @@ export function isAuthenticated() {
throw Boom.unauthorized(this.config.messages.errors.unauthorized);
const auth = await this.model.findById(ctx.request.auth._id).exec();
if (!auth)
throw Boom.notAcceptable(
this.config.messages.errors.invalid_token
);
throw Boom.notAcceptable(this.config.messages.errors.invalid_token);
await next();
} catch (e) {
handleError(ctx, e);
}
};
};
}
6 changes: 3 additions & 3 deletions src/midware.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Boom, handleError } from "@ycs/error";
import { IContext } from "@ycs/interfaces";
import { Boom, handleError } from '@ycs/error';
import { IContext } from '@ycs/interfaces';
import * as compose from 'koa-compose';

export function owns(model) {
Expand All @@ -17,4 +17,4 @@ export function owns(model) {
}
},
]);
};
}
4 changes: 0 additions & 4 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2360,10 +2360,6 @@ kind-of@^6.0.0, kind-of@^6.0.2:
version "6.0.2"
resolved "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz#01146b36a6218e64e58f3a8d66de5d7fc6f6d051"

koa-compose@^4.1.0:
version "4.1.0"
resolved "https://registry.npmjs.org/koa-compose/-/koa-compose-4.1.0.tgz#507306b9371901db41121c812e923d0d67d3e877"

lazy-cache@^1.0.3:
version "1.0.4"
resolved "https://registry.npmjs.org/lazy-cache/-/lazy-cache-1.0.4.tgz#a1d78fc3a50474cb80845d3b3b6e1da49a446e8e"
Expand Down

0 comments on commit 57af631

Please sign in to comment.