Skip to content

Commit

Permalink
Merge pull request #32 from GabrielInTheWorld/hashing
Browse files Browse the repository at this point in the history
Adds hashing-service
  • Loading branch information
GabrielInTheWorld committed Oct 12, 2020
2 parents 7c9e8eb + a96d40a commit e400ea3
Show file tree
Hide file tree
Showing 10 changed files with 70 additions and 18 deletions.
1 change: 1 addition & 0 deletions auth/src/api/interfaces/auth-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ export abstract class AuthHandler {
public abstract clearUserSessionById(sessionId: string): Promise<Validation<void>>;
public abstract clearAllSessionsExceptThemselves(sessionId: string): Promise<Validation<void>>;
public abstract toHash(toHash: string): string;
public abstract isEquals(toHash: string, toCompare: string): boolean;
}
16 changes: 16 additions & 0 deletions auth/src/api/interfaces/hashing-handler.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
export abstract class HashingHandler {
/**
* The length of a hashed value, which was hashed by this service.
*/
public static readonly HASHED_LENGTH = 152;

/**
* This function hashes a given value.
*
Expand All @@ -7,4 +12,15 @@ export abstract class HashingHandler {
* @returns The hashed value.
*/
public abstract hash(value: string): string;

/**
* Hashes a given value and compares it with a second one (that is already hashed).
* `toCompare` have to be a hashed value from this service, otherwise `false` is returned.
*
* @param toHash a value that is hashed.
* @param toCompare a value that is compared to the `toHash`.
*
* @returns If the hashed value of `toHash` is equals to `comparingValue`.
*/
public abstract isEquals(toHash: string, toCompare: string): boolean;
}
4 changes: 4 additions & 0 deletions auth/src/api/services/auth-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,8 @@ export class AuthService implements AuthHandler {
public toHash(input: string): string {
return this.hashHandler.hash(input);
}

public isEquals(toHash: string, toCompare: string): boolean {
return this.hashHandler.isEquals(toHash, toCompare);
}
}
18 changes: 16 additions & 2 deletions auth/src/api/services/hashing-service.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,23 @@
import crypto from 'crypto';

import { HashingHandler } from '../interfaces/hashing-handler';
import { Random } from '../../util/helper';

export class HashingService extends HashingHandler {
public hash(input: string): string {
if (!input) {
return '';
}
return this.sha512(input);
}

public isEquals(toHash: string, toCompare: string): boolean {
if (!toHash || !toCompare || toCompare.length !== HashingHandler.HASHED_LENGTH) {
return false;
}
return this.sha512(toHash, toCompare.slice(0, 64)) === toCompare;
}

/**
* This function hashes a given value by `sha512` and adds a salt value.
*
Expand All @@ -15,10 +26,13 @@ export class HashingService extends HashingHandler {
*
* @returns The hashed value.
*/
private sha512(value: string): string {
return crypto
private sha512(value: string, salt?: string): string {
const withSalt = salt ? salt : Random.cryptoKey(64);
const hashValue = crypto
.createHash('sha512')
.update(value)
.update(withSalt)
.digest('base64');
return withSalt + hashValue;
}
}
16 changes: 6 additions & 10 deletions auth/src/api/services/user-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,23 +19,15 @@ export class UserService implements UserHandler {
private readonly userCollection: Map<string, User> = new Map();

public async getUserByCredentials(username: string, password: string): Promise<Validation<any>> {
const userObj = await this.datastore.filter<User>('user', 'username', username, [
'username',
'password',
'default_password',
'id'
]);
const userObj = await this.datastore.filter<User>('user', 'username', username, ['username', 'password', 'id']);
if (Object.keys(userObj).length > 1) {
return { isValid: false, message: 'Multiple users with same credentials!' };
}
const user: User = new User(userObj[Object.keys(userObj)[0]]);
if (!user) {
return { isValid: false, message: 'Username or password is incorrect' };
}
if (
(!user.password && user.default_password.slice(32) !== this.hashingHandler.hash(password)) ||
(user.password && user.password.slice(32) !== this.hashingHandler.hash(password))
) {
if (!this.isPasswordCorrect(password, user.password)) {
return { isValid: false, message: 'Username or password is incorrect' };
}
return { isValid: true, message: 'successful', result: user };
Expand All @@ -54,4 +46,8 @@ export class UserService implements UserHandler {
public getAllUsers(): User[] {
return Array.from(this.userCollection.values());
}

private isPasswordCorrect(input: string, toCompare: string): boolean {
return this.hashingHandler.isEquals(input, toCompare);
}
}
1 change: 0 additions & 1 deletion auth/src/core/models/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ export class User {

public readonly username: string;
public readonly password: string;
public readonly default_password: string;
public readonly id: string;

public constructor(input?: any) {
Expand Down
1 change: 1 addition & 0 deletions auth/src/express/interfaces/route-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,5 @@ export abstract class RouteHandler extends Middleware {
public abstract clearUserSessionById(request: express.Request, response: express.Response): void;
public abstract clearAllSessionsExceptThemselves(request: express.Request, response: express.Response): void;
public abstract hash(request: express.Request, response: express.Response): void;
public abstract isEquals(request: express.Request, response: express.Response): void
}
10 changes: 9 additions & 1 deletion auth/src/express/middleware/route-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,15 @@ export default class RouteService extends RouteHandler {

public hash(request: express.Request, response: express.Response): void {
const toHash = request.body['toHash'];
this.sendResponse(true, this.authHandler.toHash(toHash), response);
this.sendResponse(true, 'Successful', response, 200, { hash: this.authHandler.toHash(toHash) });
}

public isEquals(request: express.Request, response: express.Response): void {
const toHash = request.body['toHash'];
const toCompare = request.body['toCompare'];
this.sendResponse(true, 'Successful', response, 200, {
isEquals: this.authHandler.isEquals(toHash, toCompare)
});
}

public async notFound(request: Request, response: Response): Promise<void> {
Expand Down
3 changes: 3 additions & 0 deletions auth/src/express/routes/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ export default class Routes {
this.routeHandler.whoAmI(request, response)
);
this.app.post(this.getPrivateUrl('/hash'), (request, response) => this.routeHandler.hash(request, response));
this.app.post(this.getPrivateUrl('/is-equals'), (request, response) =>
this.routeHandler.isEquals(request, response)
);
}

private initApiRoutes(): void {
Expand Down
18 changes: 14 additions & 4 deletions auth/test/hash.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,18 @@
import { Utils } from './utils';

test('POST hash', async () => {
const hashValue = await Utils.requestInternalPost('hash', { toHash: 'helloworld' });
expect(hashValue.message).toBe(
'FZQkTVLy2MErFCu2H0e8Lq9QPW2cqEgMrp/PES9m5JZ9xej6mCheNtuK8bj/qLhMsV4PvPg2w964A8E/N2WaYA=='
);
const hashValue = await Utils.requestInternalPost('hash', {
toHash: 'helloworld'
});
expect(hashValue.hash.length).toBe(152);
});

test('POST is-equals', async () => {
const hashValue = await Utils.requestInternalPost('is-equals', {
toHash: 'helloworld',
toCompare:
'316af7b2ddc20ead599c38541fbe87e9a9e4e960d4017d6e59de188b41b2758fww7VCxnNrYsz6Z38Fv+' +
'Wf6o4Ait5IkAE21CyknNS05lHSIzwF5AAObWhjzkeqV+oQ/Xc1y7FPsPg+n8cZnZy6w=='
});
expect(hashValue.isEquals).toBe(true);
});

0 comments on commit e400ea3

Please sign in to comment.