Les sessions foncitonnent, reste à pouvoir les sauvegarder, soit via redis ou via type orm. Pour l'instant redis est un échec
This commit is contained in:
@@ -1,21 +1,24 @@
|
||||
import { Controller, Get, Res, UseGuards } from '@nestjs/common';
|
||||
import { FortyTwoAuthGuard } from './guards/guards';
|
||||
import { Controller, Get, Res, UseGuards, Req } from '@nestjs/common';
|
||||
import { AuthenticateGuard, FortyTwoAuthGuard } from './guards/42guards';
|
||||
import { AuthenticationService } from './authentication.service';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { Response } from 'express';
|
||||
|
||||
@Controller('auth')
|
||||
export class AuthenticationController {
|
||||
|
||||
constructor(private readonly authService: AuthenticationService) {}
|
||||
constructor(private authService: AuthenticationService,
|
||||
// private jwtservice: JwtService
|
||||
) {}
|
||||
|
||||
/**
|
||||
* GET /api/v2/auth/login
|
||||
* GET /api/v2/auth
|
||||
* Route pour l'autentification des utilisateurs
|
||||
*/
|
||||
@Get('login')
|
||||
@Get()
|
||||
@UseGuards(FortyTwoAuthGuard)
|
||||
login() {
|
||||
return;
|
||||
return ;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -25,9 +28,8 @@ export class AuthenticationController {
|
||||
*/
|
||||
@Get('redirect')
|
||||
@UseGuards(FortyTwoAuthGuard)
|
||||
redirect(@Res() res: Response) {
|
||||
console.log(`Redirection performed`);
|
||||
res.sendStatus(200);
|
||||
async redirect(@Res() response : Response) {
|
||||
response.send(200);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -36,6 +38,7 @@ export class AuthenticationController {
|
||||
* ou non.
|
||||
*/
|
||||
@Get('status')
|
||||
@UseGuards(AuthenticateGuard)
|
||||
status() {
|
||||
return 'status';
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Friendship } from 'src/friendship/entities/friendship.entity';
|
||||
import { User } from 'src/users/entities/user.entity';
|
||||
@@ -6,12 +8,24 @@ import { UsersModule } from 'src/users/users.module';
|
||||
import { UsersService } from 'src/users/users.service';
|
||||
import { AuthenticationController } from './authentication.controller';
|
||||
import { AuthenticationService } from './authentication.service';
|
||||
import { FortyTwoStrategy } from './strategy/strategy';
|
||||
import { FortyTwoStrategy } from './strategy/42strategy';
|
||||
import { JwtStrategy } from './strategy/jwtStrategy';
|
||||
import { SessionSerializer } from './utils/serializer';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([User, Friendship]), UsersModule],
|
||||
providers: [AuthenticationService, FortyTwoStrategy, UsersService, SessionSerializer],
|
||||
imports: [TypeOrmModule.forFeature([User, Friendship]), UsersModule,
|
||||
// JwtModule.registerAsync({
|
||||
// useFactory: async (configService: ConfigService) => {
|
||||
// return {
|
||||
// signOptions: { expiresIn: '1h' },
|
||||
// secret: process.env.JWT_SECRET,
|
||||
// };
|
||||
// }
|
||||
// })
|
||||
],
|
||||
providers: [AuthenticationService, FortyTwoStrategy, UsersService, SessionSerializer,
|
||||
// JwtStrategy
|
||||
],
|
||||
exports: [AuthenticationService],
|
||||
controllers: [AuthenticationController],
|
||||
})
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { CreateUsersDto } from 'src/users/dto/create-users.dto';
|
||||
import { User } from 'src/users/entities/user.entity';
|
||||
import { Repository } from 'typeorm';
|
||||
import { UsersService } from 'src/users/users.service';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
|
||||
@Injectable()
|
||||
export class AuthenticationService {
|
||||
constructor(
|
||||
private readonly userService: UsersService,
|
||||
// private readonly jwtService: JwtService,
|
||||
) {}
|
||||
|
||||
async validateUser(createUsersDto :CreateUsersDto){
|
||||
@@ -23,4 +23,8 @@ export class AuthenticationService {
|
||||
return await this.userService.findOneByFourtyTwoId(fourtytwo_id);
|
||||
}
|
||||
|
||||
// async login(payload: any) {
|
||||
// return this.jwtService.sign(payload);
|
||||
// }
|
||||
|
||||
}
|
||||
|
||||
@@ -11,3 +11,12 @@ export class FortyTwoAuthGuard extends AuthGuard('42') {
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AuthenticateGuard implements CanActivate {
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest();
|
||||
console.log(request.isAuthenticated());
|
||||
return request.isAuthenticated();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common";
|
||||
import { AuthGuard } from "@nestjs/passport";
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard extends AuthGuard('jwt') {}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { Injectable, UnauthorizedException } from "@nestjs/common";
|
||||
import { PassportStrategy } from "@nestjs/passport";
|
||||
import { ExtractJwt, Strategy as PassportJwtStrategy } from "passport-jwt";
|
||||
import { AuthenticationService } from "../authentication.service";
|
||||
import { Request } from "express";
|
||||
|
||||
@Injectable()
|
||||
export class JwtStrategy extends PassportStrategy(PassportJwtStrategy, "jwt") {
|
||||
constructor(private readonly authenticationService: AuthenticationService) {
|
||||
|
||||
super({
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
ignoreExpiration: false,
|
||||
secretOrKey: process.env.JWT_SECRET,
|
||||
});
|
||||
}
|
||||
async validate(payload: any) {
|
||||
console.log("Validate inside jwtStrategy.ts");
|
||||
const user = await this.authenticationService.findUser(payload.fourtyTwoId);
|
||||
if (!user)
|
||||
throw new UnauthorizedException('You must be logged in to continue.');
|
||||
return { fourtyTwoId: payload.fourtyTwoId, username: payload.username, image_url: payload.image_url };
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
export const constants = {
|
||||
secret: process.env.COOKIE_SECRET,
|
||||
};
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Body, Controller, Delete, Get, HttpCode, HttpException, HttpStatus, Param, Patch, Post, UseGuards } from '@nestjs/common';
|
||||
import { FortyTwoAuthGuard } from 'src/auth/42/guards/guards';
|
||||
import { FortyTwoAuthGuard } from 'src/auth/42/guards/42guards';
|
||||
import { JwtAuthGuard } from 'src/auth/42/guards/jwtGuards';
|
||||
import { CreateUsersDto } from 'src/users/dto/create-users.dto';
|
||||
import { CreateFriendshipDto } from './dto/create-friendship.dto';
|
||||
import { UpdateFriendshipDto } from './dto/update-friendship.dto';
|
||||
@@ -11,50 +12,50 @@ export class FriendshipController {
|
||||
constructor(private readonly friendshipService: FriendshipService) {}
|
||||
|
||||
@Get(':userId/friends')
|
||||
@UseGuards(FortyTwoAuthGuard)
|
||||
@UseGuards(JwtAuthGuard)
|
||||
findEmpty(@Param('userId') userId: string) {
|
||||
return this.friendshipService.findAllFriends(userId);
|
||||
}
|
||||
|
||||
@Get(':userId/blocked')
|
||||
@UseGuards(FortyTwoAuthGuard)
|
||||
@UseGuards(JwtAuthGuard)
|
||||
findAllBlocked(@Param('userId') userId: string) {
|
||||
return this.friendshipService.findAllBlockedFriends(userId);
|
||||
}
|
||||
|
||||
@Get(':userId/pending')
|
||||
@UseGuards(FortyTwoAuthGuard)
|
||||
@UseGuards(JwtAuthGuard)
|
||||
findAllPendantFriendshipRequested(@Param('userId') userId: string) {
|
||||
return this.friendshipService.findAllPendantRequestsForFriendship(userId);
|
||||
}
|
||||
|
||||
@Get(':userId/received')
|
||||
@UseGuards(FortyTwoAuthGuard)
|
||||
@UseGuards(JwtAuthGuard)
|
||||
findAllPendantFriendshipReceived(@Param('userId') userId: string) {
|
||||
return this.friendshipService.findAllReceivedRequestsForFriendship(userId);
|
||||
}
|
||||
|
||||
@Get(':userId/myfriends/:friendId')
|
||||
@UseGuards(FortyTwoAuthGuard)
|
||||
@UseGuards(JwtAuthGuard)
|
||||
findOneFriend(@Param('friendId') friendId: string) {
|
||||
return this.friendshipService.findOneFriend(friendId);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@HttpCode(HttpStatus.CREATED)
|
||||
@UseGuards(FortyTwoAuthGuard)
|
||||
@UseGuards(JwtAuthGuard)
|
||||
create(@Body() createFriendshipDto: CreateFriendshipDto) {
|
||||
return this.friendshipService.create(createFriendshipDto);
|
||||
}
|
||||
|
||||
@Patch(':userId/received/:relationshipId')
|
||||
@UseGuards(FortyTwoAuthGuard)
|
||||
@UseGuards(JwtAuthGuard)
|
||||
update(@Param('friendId') relationshipId: string, @Body() {status}: UpdateFriendshipDto) {
|
||||
return this.friendshipService.updateFriendship(relationshipId, {status});
|
||||
}
|
||||
|
||||
@Delete(':userId/:friendId')
|
||||
@UseGuards(FortyTwoAuthGuard)
|
||||
@UseGuards(JwtAuthGuard)
|
||||
remove(@Param('friendId') friendId: string) {
|
||||
return this.friendshipService.removeFriendship(friendId);
|
||||
}
|
||||
|
||||
@@ -3,10 +3,31 @@ import { ValidationPipe } from '@nestjs/common';
|
||||
import { AppModule } from './app.module';
|
||||
import * as session from 'express-session';
|
||||
import * as passport from 'passport';
|
||||
import { constants } from './conf/constant';
|
||||
import {createClient} from 'redis';
|
||||
import * as connectRedis from 'connect-redis';
|
||||
|
||||
async function bootstrap() {
|
||||
|
||||
const app = await NestFactory.create(AppModule);
|
||||
const client = createClient(
|
||||
{
|
||||
url : process.env.REDIS_URL,
|
||||
}
|
||||
);
|
||||
const RedisStore = connectRedis(session);
|
||||
client
|
||||
.connect()
|
||||
.then(async (res) => {
|
||||
console.log('connected');})
|
||||
.catch((err) => {
|
||||
console.log('err happened' + err);
|
||||
});
|
||||
client.on('error', (err) => {
|
||||
console.log("Redis error: " + err);
|
||||
});
|
||||
client.on('connect', () => {
|
||||
console.log("Redis connected");
|
||||
});
|
||||
// module afin de créer un pipe de validation qui va nous aider
|
||||
// à valider les données qui sont envoyées par les utilisateurs
|
||||
app.useGlobalPipes(
|
||||
@@ -29,9 +50,11 @@ async function bootstrap() {
|
||||
cookie: {
|
||||
maxAge: 3600000 * 24,
|
||||
},
|
||||
secret: constants.secret,
|
||||
secret: process.env.COOKIE_SECRET,
|
||||
resave: false,
|
||||
saveUninitialized: false,
|
||||
store: new RedisStore({ client }),
|
||||
|
||||
}),
|
||||
);
|
||||
app.use(passport.initialize());
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import {
|
||||
Body, Controller, Delete, Get, HttpCode,
|
||||
HttpStatus, Param, Patch, Post, Query, UseGuards
|
||||
HttpStatus, Patch, Post, Query, Req, UseGuards
|
||||
} from '@nestjs/common';
|
||||
import { FortyTwoAuthGuard } from 'src/auth/42/guards/guards';
|
||||
import { AuthenticateGuard } from 'src/auth/42/guards/42guards';
|
||||
import { PaginationQueryDto } from 'src/common/dto/pagination-query.dto';
|
||||
import { CreateUsersDto } from './dto/create-users.dto';
|
||||
import { UpdateUsersDto } from './dto/update-users.dto';
|
||||
@@ -15,36 +15,37 @@ export class UsersController {
|
||||
constructor(private readonly usersService: UsersService) {}
|
||||
// par exemple dans postamn ou insomnia http://localhost:3000/users?limit=10&offset=20
|
||||
|
||||
@UseGuards(AuthenticateGuard)
|
||||
@Get('all')
|
||||
@UseGuards(FortyTwoAuthGuard)
|
||||
findAll(@Query() paginationquery : PaginationQueryDto) {
|
||||
//const { limit, offset } = query;
|
||||
return this.usersService.findAll(paginationquery);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
@UseGuards(FortyTwoAuthGuard)
|
||||
findOne(@Param('id') id: string) {
|
||||
return this.usersService.findOne(id);
|
||||
@UseGuards(AuthenticateGuard)
|
||||
@Get()
|
||||
findOne(@Req() req) {
|
||||
console.log('INSIDE USER CONTROLLER');
|
||||
console.log(req.user);
|
||||
return this.usersService.findOne(req.user.id);
|
||||
}
|
||||
|
||||
@UseGuards(AuthenticateGuard)
|
||||
@Post()
|
||||
@UseGuards(FortyTwoAuthGuard)
|
||||
@HttpCode(HttpStatus.CREATED)
|
||||
create(@Body() createUsersDto : CreateUsersDto ) {
|
||||
console.log(createUsersDto);
|
||||
return this.usersService.create(createUsersDto);
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
@UseGuards(FortyTwoAuthGuard)
|
||||
update(@Param('id') id: string, @Body() usersUpdateDto: UpdateUsersDto) {
|
||||
return this.usersService.update(id, usersUpdateDto);
|
||||
@Patch()
|
||||
@UseGuards(AuthenticateGuard)
|
||||
update(@Req() req, @Body() usersUpdateDto: UpdateUsersDto) {
|
||||
return this.usersService.update(req.user.id, usersUpdateDto);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@UseGuards(FortyTwoAuthGuard)
|
||||
remove(@Param('id') id: string) {
|
||||
return this.usersService.remove(id);
|
||||
@UseGuards(AuthenticateGuard)
|
||||
remove(@Req() req) {
|
||||
return this.usersService.remove(req.user.id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ import { UsersController } from './users.controller';
|
||||
import { User } from './entities/user.entity';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Friendship } from '../friendship/entities/friendship.entity';
|
||||
import { AuthenticationService } from 'src/auth/42/authentication.service';
|
||||
import { AuthenticationModule } from 'src/auth/42/authentication.module';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([User, Friendship,])],
|
||||
|
||||
@@ -36,8 +36,6 @@ export class UsersService {
|
||||
}
|
||||
|
||||
async findOne(id: string) {
|
||||
if (!isNumberString(id))
|
||||
throw new HttpException(`The requested user not found.`,HttpStatus.NOT_FOUND);
|
||||
const user = await this.userRepository.findOneBy({id: +id});
|
||||
if (!user)
|
||||
throw new NotFoundException(`The requested user not found.`);
|
||||
|
||||
Reference in New Issue
Block a user