summaryrefslogtreecommitdiff
path: root/server/controllers/sessions.controller.ts
blob: 3b179adb9f1f56fab141527f215049d250a5a71a (plain)
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 {
  Body,
  Controller,
  HttpException,
  HttpStatus,
  Post,
  Res,
} from '@nestjs/common';
import { Response } from 'express';
import * as jwt from 'jsonwebtoken';
import { UsersService } from 'server/providers/services/users.service';
import { SignInDto } from 'server/dto/sign_in.dto';


// 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')
  async signIn(
    @Body() body: SignInDto,
    @Res({ passthrough: true }) res: Response,
  ) {
    const { verified, user } = await this.usersService.verify(
      body.username,
      body.password,
    );

    if (!verified) {
      throw new HttpException(
        'Invalid email or password.',
        HttpStatus.BAD_REQUEST,
      );
    }
    // 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 };
  }
}