forked from w3tecch/express-typescript-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAuthService.ts
48 lines (38 loc) · 1.53 KB
/
AuthService.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import * as express from 'express';
import { Service } from 'typedi';
import { OrmRepository } from 'typeorm-typedi-extensions';
import { User } from '../api/models/User';
import { UserRepository } from '../api/repositories/UserRepository';
import { Logger, LoggerInterface } from '../decorators/Logger';
@Service()
export class AuthService {
constructor(
@Logger(__filename) private log: LoggerInterface,
@OrmRepository() private userRepository: UserRepository
) { }
public parseBasicAuthFromRequest(req: express.Request): { username: string, password: string } {
const authorization = req.header('authorization');
if (authorization && authorization.split(' ')[0] === 'Basic') {
this.log.info('Credentials provided by the client');
const decodedBase64 = Buffer.from(authorization.split(' ')[1], 'base64').toString('ascii');
const username = decodedBase64.split(':')[0];
const password = decodedBase64.split(':')[1];
if (username && password) {
return { username, password };
}
}
this.log.info('No credentials provided by the client');
return undefined;
}
public async validateUser(username: string, password: string): Promise<User> {
const user = await this.userRepository.findOne({
where: {
username,
},
});
if (await User.comparePassword(user, password)) {
return user;
}
return undefined;
}
}