2021-11-20 20:18:58 -05:00
|
|
|
import {
|
|
|
|
Body,
|
|
|
|
Controller,
|
|
|
|
HttpException,
|
|
|
|
HttpStatus,
|
|
|
|
Post,
|
|
|
|
Res,
|
|
|
|
} from '@nestjs/common';
|
2021-11-16 21:14:46 -05:00
|
|
|
import { Response } from 'express';
|
2021-11-20 20:18:58 -05:00
|
|
|
import * as jwt from 'jsonwebtoken';
|
|
|
|
import { UsersService } from 'server/providers/services/users.service';
|
|
|
|
import { SignInDto } from 'server/dto/sign_in.dto';
|
|
|
|
|
|
|
|
|
2021-11-16 21:14:46 -05:00
|
|
|
// this is kind of a misnomer because we are doing token based auth
|
|
|
|
// instead of session based auth
|
|
|
|
@Controller()
|
|
|
|
export class SessionsController {
|
|
|
|
constructor(private usersService: UsersService) {}
|
|
|
|
|
|
|
|
@Post('/sign_in')
|
2021-11-20 20:18:58 -05:00
|
|
|
async signIn(
|
|
|
|
@Body() body: SignInDto,
|
|
|
|
@Res({ passthrough: true }) res: Response,
|
|
|
|
) {
|
|
|
|
const { verified, user } = await this.usersService.verify(
|
2021-11-16 21:14:46 -05:00
|
|
|
body.username,
|
|
|
|
body.password,
|
|
|
|
);
|
|
|
|
|
|
|
|
if (!verified) {
|
2021-11-20 20:18:58 -05:00
|
|
|
throw new HttpException(
|
|
|
|
'Invalid email or password.',
|
|
|
|
HttpStatus.BAD_REQUEST,
|
|
|
|
);
|
2021-11-16 21:14:46 -05:00
|
|
|
}
|
2021-11-20 20:18:58 -05:00
|
|
|
// Write JWT to cookie and send with response.
|
|
|
|
const token = jwt.sign(
|
|
|
|
{
|
|
|
|
user_id: user.id,
|
|
|
|
},
|
|
|
|
process.env.ENCRYPTION_KEY,
|
|
|
|
{ expiresIn: '1h' },
|
|
|
|
);
|
|
|
|
res.cookie('_token', token);
|
|
|
|
return { token };
|
2021-11-16 21:14:46 -05:00
|
|
|
}
|
|
|
|
}
|