Skip to content

Commit

Permalink
refactor: change firstname and surname to firstName and lastName
Browse files Browse the repository at this point in the history
Make cosmetic changes like changing firstname and surname to firstName and lastName
  • Loading branch information
emonddr committed May 22, 2019
1 parent aedef8f commit 47f2b93
Show file tree
Hide file tree
Showing 6 changed files with 89 additions and 73 deletions.
48 changes: 23 additions & 25 deletions packages/authentication/docs/authentication-system.md
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ interface is implemented by the `value()` function of
`AuthenticateActionProvider` class in `/src/providers/auth-action.provider.ts`.

```ts
class SequenceIncludingAuthentication implements SequenceHandler {
export class SequenceIncludingAuthentication implements SequenceHandler {
constructor(
@inject(SequenceActions.FIND_ROUTE) protected findRoute: FindRoute,
@inject(SequenceActions.PARSE_PARAMS)
Expand All @@ -287,44 +287,42 @@ class SequenceIncludingAuthentication implements SequenceHandler {
const {request, response} = context;
const route = this.findRoute(request);

//call authentication action
await this.authenticateRequest(request);

// Authentication successful, proceed to invoke controller
const args = await this.parseParams(request, route);
const result = await this.invoke(route, args);
this.send(response, result);
} catch (error) {
//
// The authentication action utilizes a strategy resolver to find
// an authentication strategy by name, and then it calls
// strategy.authenticate(request).
//
// The strategy resolver throws a non-http error if it cannot
// resolve the strategy. When the strategy resolver obtains
// a strategy, it calls strategy.authentication(request) which
// a strategy, it calls strategy.authenticate(request) which
// is expected to return a user profile. If the user profile
// is undefined, then it throws a non-http error.
//
// It is necessary to catch these errors
// and rethrow them as http errors (in our REST application example)
// It is necessary to catch these errors and add HTTP-specific status
// code property.
//
// Errors thrown by the strategy implementations are http errors
// (in our REST application example). We simply rethrow them.
// Errors thrown by the strategy implementations already come
// with statusCode set.
//
try {
//call authentication action
await this.authenticateRequest(request);
} catch (e) {
// strategy not found error, or user profile undefined
if (
e.code === AUTHENTICATION_STRATEGY_NOT_FOUND ||
e.code === USER_PROFILE_NOT_FOUND
) {
throw new HttpErrors.Unauthorized(e.message);
} else {
// strategy error
throw e;
}
// In the future, we want to improve `@loopback/rest` to provide
// an extension point allowing `@loopback/authentication` to contribute
// mappings from error codes to HTTP status codes, so that application
// don't have to map codes themselves.
if (
error.code === AUTHENTICATION_STRATEGY_NOT_FOUND ||
error.code === USER_PROFILE_NOT_FOUND
) {
Object.assign(error, {statusCode: 401 /* Unauthorized */});
}

// Authentication successful, proceed to invoke controller
const args = await this.parseParams(request, route);
const result = await this.invoke(route, args);
this.send(response, result);
} catch (error) {
this.reject(context, error);
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,12 +157,12 @@ describe('Basic Authentication', () => {
.expect({
error: {
message: `The strategy 'doesnotexist' is not available.`,
name: 'UnauthorizedError',
name: 'Error',
statusCode: 401,
code: 'AUTHENTICATION_STRATEGY_NOT_FOUND',
},
});
});

it('returns error when undefined user profile returned from authentication strategy', async () => {
class BadBasicStrategy implements AuthenticationStrategy {
name: string = 'badbasic';
Expand All @@ -186,12 +186,12 @@ describe('Basic Authentication', () => {
.expect({
error: {
message: `User profile not returned from strategy's authenticate function`,
name: 'UnauthorizedError',
name: 'Error',
statusCode: 401,
code: 'USER_PROFILE_NOT_FOUND',
},
});
});

async function givenAServer() {
app = getApp();
server = await app.getServer(RestServer);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ describe('JWT Authentication', () => {
let testUsers: UserRepository;
let joeUser: User;
let token: string;
const TOKEN_SECRET_VALUE = 'myjwts3cr3t';
const TOKEN_EXPIRES_IN_VALUE = '600';

beforeEach(givenAServer);
beforeEach(givenAuthenticatedSequence);
Expand Down Expand Up @@ -268,8 +270,7 @@ describe('JWT Authentication', () => {

app.controller(InfoController);

const expiredToken =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEiLCJlbWFpbCI6ImpvZUBleGFtcGxlLmNvbSIsIm5hbWUiOiJqb2Ugam9lbWFuIiwiaWF0IjoxNTU1ODY3NDAzLCJleHAiOjE1NTU4Njc0NjN9.QKmO5qDC8Yg-aK3EedLRsXczL7VQDDnWtA-cpyqszqM';
const expiredToken = await getExpiredToken();

await whenIMakeRequestTo(server)
.get('/whoAmI')
Expand Down Expand Up @@ -402,8 +403,9 @@ describe('JWT Authentication', () => {
.expect({
error: {
message: `The strategy 'doesnotexist' is not available.`,
name: 'UnauthorizedError',
name: 'Error',
statusCode: 401,
code: 'AUTHENTICATION_STRATEGY_NOT_FOUND',
},
});
});
Expand Down Expand Up @@ -431,8 +433,9 @@ describe('JWT Authentication', () => {
.expect({
error: {
message: `User profile not returned from strategy's authenticate function`,
name: 'UnauthorizedError',
name: 'Error',
statusCode: 401,
code: 'USER_PROFILE_NOT_FOUND',
},
});
});
Expand All @@ -442,6 +445,18 @@ describe('JWT Authentication', () => {
server = await app.getServer(RestServer);
}

/**
* Creates an expired token
*
* Specifying a negative value for 'expiresIn' so the
* token is automatically expired
*/
async function getExpiredToken() {
const userProfile = createUserProfile(joeUser);
const tokenService = new JWTService(TOKEN_SECRET_VALUE, '-10');
return await tokenService.generateToken(userProfile);
}

function givenAuthenticatedSequence() {
// bind user defined sequence
server.sequence(MyAuthenticationSequence);
Expand All @@ -452,9 +467,11 @@ describe('JWT Authentication', () => {

server
.bind(JWTAuthenticationStrategyBindings.TOKEN_SECRET)
.to('myjwts3cr3t');
.to(TOKEN_SECRET_VALUE);

server.bind(JWTAuthenticationStrategyBindings.TOKEN_EXPIRES_IN).to('60');
server
.bind(JWTAuthenticationStrategyBindings.TOKEN_EXPIRES_IN)
.to(TOKEN_EXPIRES_IN_VALUE);

server
.bind(JWTAuthenticationStrategyBindings.TOKEN_SERVICE)
Expand Down
26 changes: 15 additions & 11 deletions packages/authentication/src/__tests__/fixtures/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,29 +26,29 @@ export function getUserRepository(): UserRepository {
return new UserRepository({
joe888: {
id: '1',
firstname: 'joe',
surname: 'joeman',
firstName: 'joe',
lastName: 'joeman',
username: 'joe888',
password: 'joepa55w0rd',
},
jill888: {
id: '2',
firstname: 'jill',
surname: 'jillman',
firstName: 'jill',
lastName: 'jillman',
username: 'jill888',
password: 'jillpa55w0rd',
},
jack888: {
id: '3',
firstname: 'jack',
surname: 'jackman',
firstName: 'jack',
lastName: 'jackman',
username: 'jack888',
password: 'jackpa55w0rd',
},
janice888: {
id: '4',
firstname: 'janice',
surname: 'janiceman',
firstName: 'janice',
lastName: 'janiceman',
username: 'janice888',
password: 'janicepa55w0rd',
},
Expand Down Expand Up @@ -104,9 +104,13 @@ export function createBearerAuthorizationHeaderValue(
export function createUserProfile(user: User): UserProfile {
const userProfile = {id: '', name: ''};

if (user && user.id) userProfile.id = user.id;
if (user && user.firstname && user.surname)
userProfile.name = `${user.firstname} ${user.surname}`;
if (user.id) userProfile.id = user.id;

let userName = '';
if (user.firstName) userName = user.firstName;
if (user.lastName)
userName = user.firstName ? `${userName} ${user.lastName}` : user.lastName;
userProfile.name = userName;

return userProfile;
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import {inject} from '@loopback/context';
import {
FindRoute,
HttpErrors,
InvokeMethod,
ParseParams,
Reject,
Expand Down Expand Up @@ -39,44 +38,42 @@ export class MyAuthenticationSequence implements SequenceHandler {
const {request, response} = context;
const route = this.findRoute(request);

//call authentication action
await this.authenticateRequest(request);

// Authentication successful, proceed to invoke controller
const args = await this.parseParams(request, route);
const result = await this.invoke(route, args);
this.send(response, result);
} catch (error) {
//
// The authentication action utilizes a strategy resolver to find
// an authentication strategy by name, and then it calls
// strategy.authenticate(request).
//
// The strategy resolver throws a non-http error if it cannot
// resolve the strategy. When the strategy resolver obtains
// a strategy, it calls strategy.authentication(request) which
// a strategy, it calls strategy.authenticate(request) which
// is expected to return a user profile. If the user profile
// is undefined, then it throws a non-http error.
//
// It is necessary to catch these errors
// and rethrow them as http errors (in our REST application example)
// It is necessary to catch these errors and add HTTP-specific status
// code property.
//
// Errors thrown by the strategy implementations are http errors
// (in our REST application example). We simply rethrow them.
// Errors thrown by the strategy implementations already come
// with statusCode set.
//
try {
//call authentication action
await this.authenticateRequest(request);
} catch (e) {
// strategy not found error, or user profile undefined
if (
e.code === AUTHENTICATION_STRATEGY_NOT_FOUND ||
e.code === USER_PROFILE_NOT_FOUND
) {
throw new HttpErrors.Unauthorized(e.message);
} else {
// strategy error
throw e;
}
// In the future, we want to improve `@loopback/rest` to provide
// an extension point allowing `@loopback/authentication` to contribute
// mappings from error codes to HTTP status codes, so that application
// don't have to map codes themselves.
if (
error.code === AUTHENTICATION_STRATEGY_NOT_FOUND ||
error.code === USER_PROFILE_NOT_FOUND
) {
Object.assign(error, {statusCode: 401 /* Unauthorized */});
}

// Authentication successful, proceed to invoke controller
const args = await this.parseParams(request, route);
const result = await this.invoke(route, args);
this.send(response, result);
} catch (error) {
this.reject(context, error);
return;
}
Expand Down
4 changes: 2 additions & 2 deletions packages/authentication/src/__tests__/fixtures/users/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@ export interface User {
id: string;
username: string;
password: string;
firstname?: string;
surname?: string;
firstName?: string;
lastName?: string;
}

0 comments on commit 47f2b93

Please sign in to comment.