tous les trucs du user sont ok, maintenant refonte des requêtes d'amitiés. C'est bien avancé, reste àa tester deux trois trucs

This commit is contained in:
batche
2022-11-04 18:34:02 +01:00
parent 08d02e709b
commit 7fd8147140
39 changed files with 328 additions and 291 deletions

View File

@@ -13,7 +13,7 @@ export class AuthenticationService {
async validateUser(createUsersDto :CreateUsersDto){
console.log("Validate inside authentication.service.ts");
const user = await this.userService.findOneByFourtyTwoId(createUsersDto.fourtyTwoId);
const user = await this.userService.findOneByFourtyTwoId(createUsersDto.fortyTwoId);
if (user)
return user;
return this.userService.create(createUsersDto);

View File

@@ -18,7 +18,7 @@ export class FortyTwoStrategy extends PassportStrategy(Strategy, "42") {
async validate(accessToken: string, refreshToken: string, profile: Profile, callbackURL: string) {
console.log("Validate inside strategy.ts");
console.log(profile.id, profile.username, profile.phoneNumbers[0].value, profile.emails[0].value, profile.photos[0].value);
const userDTO: CreateUsersDto = { fourtyTwoId: profile.id, username: profile.username, email: profile.emails[0].value, image_url: profile.photos[0].value };
const userDTO: CreateUsersDto = { fortyTwoId: profile.id, username: profile.username, email: profile.emails[0].value, image_url: profile.photos[0].value };
const user = await this.authenticationService.validateUser(userDTO);
if (!user)
throw new UnauthorizedException();

View File

@@ -14,7 +14,7 @@ export class SessionSerializer extends PassportSerializer {
}
async deserializeUser(user : User, done : (err : Error, user : User) => void){
const userDB = await this.authservice.findUser(user.fourtyTwoId);
const userDB = await this.authservice.findUser(user.fortyTwoId);
if (userDB)
done(null, userDB);
else

View File

@@ -17,7 +17,6 @@ export class Friendship {
@CreateDateColumn()
date : Date;
@Column()
@ManyToOne(type => User, user => user.requesterId)
requesterId: string;

View File

@@ -1,7 +1,6 @@
import { Body, Controller, Delete, Get, HttpCode, HttpException, HttpStatus, Param, Patch, Post, UseGuards } from '@nestjs/common';
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 { Body, Controller, Delete, Get, HttpCode, HttpException, HttpStatus, Param, Patch, Post, Query, Req, UseGuards } from '@nestjs/common';
import { AuthenticateGuard } from 'src/auth/42/guards/42guards';
import { User } from 'src/users/entities/user.entity';
import { CreateFriendshipDto } from './dto/create-friendship.dto';
import { UpdateFriendshipDto } from './dto/update-friendship.dto';
import { FriendshipStatus } from './entities/friendship.entity';
@@ -9,54 +8,74 @@ import { FriendshipService } from './friendship.service';
@Controller('network')
export class FriendshipController {
constructor(private readonly friendshipService: FriendshipService) {}
constructor(private readonly friendshipService: FriendshipService) { }
@Get(':userId/friends')
@UseGuards(JwtAuthGuard)
findEmpty(@Param('userId') userId: string) {
return this.friendshipService.findAllFriends(userId);
// GET http://127.0.0.1:3000/api/v2/network/myfriends
@Get('myfriends')
@UseGuards(AuthenticateGuard)
findEmpty(@Req() req) {
const user = req.user;
return this.friendshipService.findAllFriends(user.id);
}
@Get(':userId/blocked')
@UseGuards(JwtAuthGuard)
findAllBlocked(@Param('userId') userId: string) {
return this.friendshipService.findAllBlockedFriends(userId);
// GET http://127.0.0.1:3000/api/v2/network/myfriends/relationshipId
@Get('myfriends/:relationshipId')
@UseGuards(AuthenticateGuard)
findOneFriend(@Param('relationshipId') relationshipId: string, @Req() req) {
const user = req.user;
return this.friendshipService.findOneFriend(relationshipId, user.id);
}
@Get(':userId/pending')
@UseGuards(JwtAuthGuard)
findAllPendantFriendshipRequested(@Param('userId') userId: string) {
return this.friendshipService.findAllPendantRequestsForFriendship(userId);
}
@Get(':userId/received')
@UseGuards(JwtAuthGuard)
findAllPendantFriendshipReceived(@Param('userId') userId: string) {
return this.friendshipService.findAllReceivedRequestsForFriendship(userId);
}
@Get(':userId/myfriends/:friendId')
@UseGuards(JwtAuthGuard)
findOneFriend(@Param('friendId') friendId: string) {
return this.friendshipService.findOneFriend(friendId);
}
@Post()
// POST http://127.0.0.1:3000/api/v2/network/
@Post('myfriends')
@HttpCode(HttpStatus.CREATED)
@UseGuards(JwtAuthGuard)
create(@Body() createFriendshipDto: CreateFriendshipDto) {
return this.friendshipService.create(createFriendshipDto);
@UseGuards(AuthenticateGuard)
create(@Body() createFriendshipDto: CreateFriendshipDto, @Req() req) {
const user = req.user;
console.log(`User id: ${user.id}\n Friend id: ${createFriendshipDto.requesterId}`);
if (user.id === +createFriendshipDto.requesterId)
return this.friendshipService.create(createFriendshipDto, user);
return new HttpException('You can\'t request a frienship for another user', HttpStatus.FORBIDDEN);
}
@Patch(':userId/received/:relationshipId')
@UseGuards(JwtAuthGuard)
update(@Param('friendId') relationshipId: string, @Body() {status}: UpdateFriendshipDto) {
return this.friendshipService.updateFriendship(relationshipId, {status});
// PATCH http://127.0.0.1:3000/api/v2/network/myfriends/relationshipId?status=A
@Patch('myfriends/:relationshipId')
@UseGuards(AuthenticateGuard)
update(@Param('relationshipId') relationshipId: string, @Query('status') status : string, @Req() req)
{
const user : User = req.user;
return this.friendshipService.updateFriendship(relationshipId, user, status);
}
@Delete(':userId/:friendId')
@UseGuards(JwtAuthGuard)
remove(@Param('friendId') friendId: string) {
return this.friendshipService.removeFriendship(friendId);
// DELETE http://127.0.0.1:3000/api/v2/network/myfriends/relationshipId
@Delete('myfriends/:relationshipId')
@UseGuards(AuthenticateGuard)
remove(@Param('relationshipId') relationshipId: string) {
return this.friendshipService.removeFriendship(relationshipId);
}
// GET http://127.0.0.1:3000/api/v2/network/blocked
@Get('blocked')
@UseGuards(AuthenticateGuard)
findAllBlocked(@Req() req) {
const user = req.user;
return this.friendshipService.findAllBlockedFriends(user.id);
}
// GET http://127.0.0.1:3000/api/v2/network/pending
@Get('pending')
@UseGuards(AuthenticateGuard)
findAllPendantFriendshipRequested(@Req() req) {
const user = req.user;
return this.friendshipService.findAllPendantRequestsForFriendship(user.id);
}
// GET http://127.0.0.1:3000/api/v2/network/received
@Get('received')
@UseGuards(AuthenticateGuard)
findAllPendantFriendshipReceived(@Req() req) {
const user = req.user;
return this.friendshipService.findAllReceivedRequestsForFriendship(user.id);
}
}

View File

@@ -14,102 +14,107 @@ export class FriendshipService {
private readonly friendshipRepository: Repository<Friendship>,
@InjectRepository(User)
private readonly userRepository: Repository<User>,
) {}
) { }
async findOneFriend(id: string) {
const friendship = await this.friendshipRepository.find({where: {id: +id, status: FriendshipStatus.ACCEPTED}});
async findOneFriend(friendshipId: string, userId: string) {
const friendship = await this.friendshipRepository.find({ where: { id: +friendshipId, requesterId: userId, status: FriendshipStatus.ACCEPTED } });
if (!friendship)
throw new HttpException(`The requested friend not found.`,HttpStatus.NOT_FOUND);
throw new HttpException(`The requested friend not found.`, HttpStatus.NOT_FOUND);
return friendship;
}
async findOneBlocked(id: string) {
const friendship = await this.friendshipRepository.find({where: {id: +id, status: FriendshipStatus.BLOCKED}});
async findOneBlocked(friendshipId: string) {
const friendship = await this.friendshipRepository.find({ where: { id: +friendshipId, status: FriendshipStatus.BLOCKED } });
if (!friendship)
throw new HttpException(`The requested friend not found.`,HttpStatus.NOT_FOUND);
throw new HttpException(`The requested user not found.`, HttpStatus.NOT_FOUND);
return friendship;
}
async findAllFriends(id: string) {
const user = await this.userRepository.findOneBy({id: +id});
if (!user)
throw new HttpException(`The requested user not found.`,HttpStatus.NOT_FOUND);
const friends = await this.friendshipRepository.find(
{where: {requesterId: id, status: FriendshipStatus.ACCEPTED}});
return friends;
async findAllFriends(userId: string) {
const friendship = await this.friendshipRepository
.createQueryBuilder('friendship')
.where('friendship.status = :status', { status: FriendshipStatus.ACCEPTED })
.andWhere('friendship.addresseeId = :addressee', { addressee: userId })
.orWhere('friendship.requesterId = :requester', { requester: userId })
.andWhere('friendship.status = :status', { status: FriendshipStatus.ACCEPTED })
.getMany();
for (const friend of friendship)
console.log("FRIENDSHIP : " + friend.status);
return friendship;
}
async findAllBlockedFriends(id: string) {
const user = await this.userRepository.findOneBy({id: +id});
if (!user)
throw new HttpException(`The requested user not found.`,HttpStatus.NOT_FOUND);
const blocked = await this.friendshipRepository.find(
{where: {requesterId: id, status: FriendshipStatus.BLOCKED}});
return blocked;
async findAllBlockedFriends(userId: string) {
return await this.friendshipRepository
.createQueryBuilder('friendship')
.where('friendship.requesterId = :requestee', { requestee: userId })
.orWhere('friendship.addresseeId = :addressee', { addressee: userId })
.andWhere('friendship.status = :status', { status: FriendshipStatus.BLOCKED })
.getMany();
}
async findAllPendantRequestsForFriendship(id: string) {
const user = await this.userRepository.findOneBy({id: +id});
if (!user)
throw new HttpException(`The requested user not found.`,HttpStatus.NOT_FOUND);
const requests = await this.friendshipRepository.find({
where:
{requesterId: id, status: FriendshipStatus.REQUESTED},
relations: ['requesterId']});
return requests;
async findAllPendantRequestsForFriendship(userId: string) {
return await this.friendshipRepository
.createQueryBuilder('friendship')
.where('friendship.requesterId = :requestee', { requestee: userId })
.andWhere('friendship.status = :status', { status: FriendshipStatus.REQUESTED })
.getMany();
}
async findAllReceivedRequestsForFriendship(id: string) {
const user = await this.userRepository.findOneBy({id: +id});
if (!user)
throw new HttpException(`The requested user not found.`,HttpStatus.NOT_FOUND);
const requests = await this.friendshipRepository.find({
where:
{addresseeId: id, status: FriendshipStatus.REQUESTED},
relations: ['addresseeId']});
return requests;
async findAllReceivedRequestsForFriendship(userId: string) {
return await this.friendshipRepository
.createQueryBuilder('friendship')
.where('friendship.addresseeId = :addressee', { addressee: userId })
.andWhere('friendship.status = :status', { status: FriendshipStatus.REQUESTED })
.getMany();
}
async create(createFriendshipDto: CreateFriendshipDto) {
const requester = await this.userRepository.findOneBy({id : +createFriendshipDto.requesterId});
if (!requester)
throw new HttpException(`The user does not exist.`,HttpStatus.NOT_FOUND);
const addressee = await this.userRepository.findOneBy({id: +createFriendshipDto.addresseeId});
//GROS CHANTIER
async create(createFriendshipDto: CreateFriendshipDto, creator : User) {
const addressee = await this.userRepository.findOneBy({ id: +createFriendshipDto.addresseeId });
if (!addressee)
throw new HttpException(`The user does not exist.`,HttpStatus.NOT_FOUND);
if (createFriendshipDto.requesterId == createFriendshipDto.addresseeId)
throw new HttpException(`You can't add yourself.`,HttpStatus.NOT_FOUND);
const friendship = await this.friendshipRepository.findOneBy({requesterId: createFriendshipDto.requesterId, addresseeId: createFriendshipDto.addresseeId});
throw new HttpException(`The addressee does not exist.`, HttpStatus.NOT_FOUND);
if (creator.id === addressee.id)
throw new HttpException(`You can't add yourself.`, HttpStatus.NOT_FOUND);
const friendship = await this.friendshipRepository.findOneBy({ requesterId: createFriendshipDto.requesterId, addresseeId: createFriendshipDto.addresseeId });
if (friendship) {
if (friendship.status && friendship.status === FriendshipStatus.ACCEPTED)
throw new HttpException(`The friendship request has already been accepted.`,HttpStatus.OK);
throw new HttpException(`The friendship request has already been accepted.`, HttpStatus.OK);
else if (friendship.status && friendship.status === FriendshipStatus.REQUESTED)
throw new HttpException(`The friendship request has already been sent the ${friendship.date}.`,HttpStatus.OK);
throw new HttpException(`The friendship request has already been sent the ${friendship.date}.`, HttpStatus.OK);
else if (friendship.status && friendship.status === FriendshipStatus.BLOCKED)
throw new HttpException(``,HttpStatus.OK);
throw new HttpException(`We can't do that`, HttpStatus.OK);
else if (friendship.status && friendship.status === FriendshipStatus.DECLINED)
throw new HttpException(`The request has been declined.`,HttpStatus.OK);
throw new HttpException(`The request has been declined.`, HttpStatus.OK);
}
const newFriendship = this.friendshipRepository.create(
{requesterId: createFriendshipDto.requesterId, addresseeId: createFriendshipDto.addresseeId, status: FriendshipStatus.REQUESTED});
{ requesterId: createFriendshipDto.requesterId, addresseeId: createFriendshipDto.addresseeId, status: FriendshipStatus.REQUESTED });
return this.friendshipRepository.save(newFriendship);
}
async updateFriendship(id: string, updateFriendshipDto: UpdateFriendshipDto) {
const friendship = await this.friendshipRepository.preload(
{id: +id,
...updateFriendshipDto});
if (!friendship)
throw new HttpException(`The friendship could not be updated.`,HttpStatus.NOT_FOUND);
return this.friendshipRepository.save(friendship);
async updateFriendship(relationshipId: string, user: User, status: string) {
const relation = await this.friendshipRepository.findOneBy({ id: +relationshipId });
if (!relation)
throw new HttpException(`The requested relationship not found.`, HttpStatus.NOT_FOUND);
// if (+relation.requesterId === user.id) {
// throw new HttpException(`You can't accept your own request.`, HttpStatus.NOT_FOUND);
// }
if (status === FriendshipStatus.ACCEPTED)
relation.status = FriendshipStatus.ACCEPTED;
else if (status === FriendshipStatus.DECLINED)
relation.status = FriendshipStatus.DECLINED;
else if (status === FriendshipStatus.BLOCKED)
relation.status = FriendshipStatus.BLOCKED;
else
throw new HttpException(`The status is not valid.`, HttpStatus.NOT_FOUND);
if (relation.status !== status)
throw new HttpException(`We could not update the status.`, HttpStatus.OK);
return this.friendshipRepository.save(relation);
}
async removeFriendship(id: string) {
const friendship = await this.findOneFriend(id);
async removeFriendship(relationshipId: string) {
const friendship = await this.friendshipRepository.findOneBy({ id: +relationshipId });
if (!friendship)
throw new HttpException(`Your friend could not be deleted.`,HttpStatus.NOT_FOUND);
throw new HttpException(`Your friend could not be deleted.`, HttpStatus.NOT_FOUND);
return this.friendshipRepository.remove(friendship);
}
}

View File

@@ -18,7 +18,7 @@ async function bootstrap() {
client.connect();
const RedisStore = connectRedis(session);
client.on('connect', () => {
console.log("Redis Connected");
console.log("Redis successfully Connected");
});
// module afin de créer un pipe de validation qui va nous aider

View File

@@ -5,7 +5,7 @@ export class CreateUsersDto {
@IsString()
readonly username: string;
@IsString()
readonly fourtyTwoId: string;
readonly fortyTwoId: string;
@IsEmail()
readonly email: string;
@IsString()

View File

@@ -12,7 +12,7 @@ export class User {
id: number;
@Column({unique: true})
fourtyTwoId: string;
fortyTwoId: string;
@Column()
username: string;

View File

@@ -1,6 +1,6 @@
import {
Body, Controller, Delete, Get, HttpCode,
HttpStatus, Patch, Post, Query, Req, UseGuards
HttpStatus, Param, Patch, Post, Query, Req, UseGuards
} from '@nestjs/common';
import { AuthenticateGuard } from 'src/auth/42/guards/42guards';
import { PaginationQueryDto } from 'src/common/dto/pagination-query.dto';
@@ -22,11 +22,18 @@ export class UsersController {
return this.usersService.findAll(paginationquery);
}
////////////////////////////////////////////////////////
///////////////////////// RUD //////////////////////////
////////////////////////////////////////////////////////
/**
* On ne fait de création via une route
* car un utilisateur est crée à la première connexion avec l'Oauth de 42.
*/
@UseGuards(AuthenticateGuard)
@Get()
findOne(@Req() req) {
console.log('INSIDE USER CONTROLLER');
console.log(req.user);
return this.usersService.findOne(req.user.id);
}
@@ -37,14 +44,14 @@ export class UsersController {
return this.usersService.create(createUsersDto);
}
@Patch()
@UseGuards(AuthenticateGuard)
@Patch()
update(@Req() req, @Body() usersUpdateDto: UpdateUsersDto) {
return this.usersService.update(req.user.id, usersUpdateDto);
}
@Delete(':id')
@UseGuards(AuthenticateGuard)
@Delete()
remove(@Req() req) {
return this.usersService.remove(req.user.id);
}

View File

@@ -21,11 +21,8 @@ export class UsersService {
private readonly friendshipRepository: Repository<Friendship>,
) {}
async findOneByFourtyTwoId(fourtytwo_id: string) {
console.log(`Find user with fourtytwo_id ${fourtytwo_id}`);
if (!isNumberString(fourtytwo_id))
throw new HttpException(`The requested user not found.`,HttpStatus.NOT_FOUND);
const user = await this.userRepository.findOneBy({fourtyTwoId: fourtytwo_id});
async findOneByFourtyTwoId(fortytwo_id: string) {
const user = await this.userRepository.findOneBy({fortyTwoId: fortytwo_id});
if (!user)
{
console.log(`The requested user not found.`);
@@ -52,8 +49,7 @@ export class UsersService {
}
async create(createUserDto: CreateUsersDto) {
console.log(`Create user with ${createUserDto}`);
if (await this.userRepository.findOneBy({fourtyTwoId: createUserDto.fourtyTwoId}))
if (await this.userRepository.findOneBy({fortyTwoId: createUserDto.fortyTwoId}))
throw new HttpException(`The user already exists.`,HttpStatus.CONFLICT);
const user = this.userRepository.create(createUserDto);
if (!user)