Skip to content

Commit b46e605

Browse files
author
hirsch88
committed
♻️ Refactor basic authentication
1 parent 05cb725 commit b46e605

File tree

3 files changed

+15
-13
lines changed

3 files changed

+15
-13
lines changed

src/api/models/User.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,8 @@ export class User {
3838
return `${this.firstName} ${this.lastName} (${this.email})`;
3939
}
4040

41+
public toBase64(): string {
42+
return Buffer.from(`${this.username}:${this.password}`).toString('base64');
43+
}
44+
4145
}

src/auth/AuthService.ts

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -23,24 +23,22 @@ export class AuthService {
2323
const decodedToken = Buffer.from(authorization.split(' ')[1], 'base64').toString('ascii');
2424
const username = decodedToken.split(':')[0];
2525
const password = decodedToken.split(':')[1];
26-
return { username, password };
26+
if (username && password) {
27+
return { username, password };
28+
}
2729
}
2830

2931
this.log.info('No Token provided by the client');
3032
return undefined;
3133
}
3234

33-
public async validateUser(username: string, password: string): Promise<User> {
34-
const user = await this.userRepository.findOne({
35+
public async findUserByUsernameAndPassword(username: string, password: string): Promise<User> {
36+
return this.userRepository.findOne({
3537
where: {
3638
username,
3739
password,
3840
},
3941
});
40-
if (user) {
41-
return user;
42-
}
43-
throw new Error('Invalid credentials');
4442
}
4543

4644
}

src/auth/authorizationChecker.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,13 @@ export function authorizationChecker(connection: Connection): (action: Action, r
2222
return false;
2323
}
2424

25-
try {
26-
action.request.user = await authService.validateUser(credentials.username, credentials.password);
27-
log.info('Successfully checked credentials');
28-
return true;
29-
} catch (e) {
30-
log.warn(e);
25+
action.request.user = await authService.findUserByUsernameAndPassword(credentials.username, credentials.password);
26+
if (action.request.user === undefined) {
27+
log.warn('Invalid credentials given');
3128
return false;
3229
}
30+
31+
log.info('Successfully checked credentials');
32+
return true;
3333
};
3434
}

0 commit comments

Comments
 (0)