Ошибка в passport-local
Локально все работает, после диплоя на сервер уже нет
auth.service.ts
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { UsersService } from 'src/users/users.service';
import * as bcrypt from 'bcrypt';
@Injectable()
export class AuthService {
constructor(
private readonly usersService: UsersService,
) {}
async validateUser(username: string, password: string) {
const user = await this.usersService.findOne({ where: { username } });
if (!user) {
throw new UnauthorizedException('User not found');
}
const passwordValid = await bcrypt.compare(password, user.password);
if (!passwordValid) {
throw new UnauthorizedException('Invalid pasword');
}
return {
userId: user.id,
username: user.username,
email: user.email,
};
}
authentificated.guard.ts
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
@Injectable()
export class AuthenticatedGuard implements CanActivate {
async canActivate(context: ExecutionContext) {
const request = context.switchToHttp().getRequest();
return request.isAuthenticated();
}
}
local.auth.guard.ts
import {
ExecutionContext,
Injectable,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class LocalAuthGuard extends AuthGuard('local') {
async canActivate(context: ExecutionContext) {
const result = (await super.canActivate(context)) as boolean;
const request = context.switchToHttp().getRequest();
await super.logIn(request);
return result;
}
}
local.strategy.ts
import { Strategy } from 'passport-local';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthService } from './auth.service';
import { ContextIdFactory, ModuleRef } from '@nestjs/core';
import { PassportStrategy } from '@nestjs/passport';
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super();
}
async validate(username: string, password: string, done): Promise<any> {
const user = await this.authService.validateUser(
username.toLowerCase(),
password,
);
if (!user) {
throw new UnauthorizedException();
}
return done(null, user);
}
}
ну и контроллеры
import {
Controller,
Header,
Post,
HttpCode,
Body,
UseGuards,
Request,
Get,
} from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { LocalAuthGuard } from 'src/auth/local.auth.guard';
import { AuthenticatedGuard } from 'src/auth/authentificated.guard';
import { ApiBody, ApiOkResponse } from '@nestjs/swagger';
import {
LoginCheckResponse,
LoginUserRequest,
LoginUserResponse,
LogoutUserResponse,
SignupResponse,
} from './types';
import { UsersService } from './users.service';
@Controller('users')
export class UsersController {
constructor(private readonly UsersService: UsersService) {}
@ApiOkResponse({ type: SignupResponse })
@Post('/singup')
// @UsePipes(new ValidationPipe())
@HttpCode(200)
@Header('Content-type', 'application/json')
createUser(@Body() dto: CreateUserDto) {
return this.UsersService.create(dto);
}
@ApiBody({ type: LoginUserRequest })
@ApiOkResponse({ type: LoginUserResponse })
// @UsePipes(new ValidationPipe())
@Post('/login')
@UseGuards(LocalAuthGuard)
@HttpCode(200)
login(@Request() req) {
return { user: req.user, msg: 'Logged in' };
}
@ApiOkResponse({ type: LoginCheckResponse })
@Get('/login-check')
@UseGuards(AuthenticatedGuard)
async loginCheck(@Request() req) {
return req.user;
}
@ApiOkResponse({ type: LogoutUserResponse })
@Get('/loginout')
loginOut(@Request() req) {
req.session.destroy();
return { msg: 'Сессия завершена' };
}
}
ну и мейн
import { NestFactory } from '@nestjs/core';
import * as session from 'express-session';
import * as passport from 'passport';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.use(
session({
secret: process.env.JWT_SECRET,
resave: false,
saveUninitialized: false,
}),
);
app.use(passport.initialize());
app.use(passport.session());
app.setGlobalPrefix('api')
// app.use(passport.session());
app.enableCors({
credentials: true,
allowedHeaders:
'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, Authorization, Observe',
methods: ['GET', 'POST', 'PATCH', 'DELETE'],
origin: true
});
await app.listen(process.env.PORT || 3001);
}
bootstrap();
Выдает ошибку 403 при проверке на логин чек, логин и регистрация проходят без проблем