Skip to content

Commit

Permalink
Merge pull request #225 from boostcampwm2023/feature/be-global-final
Browse files Browse the repository at this point in the history
회원가입 후 자동로그인, 마이페이지 사진 수정 판단 구현
  • Loading branch information
LeeTH916 authored Dec 6, 2023
2 parents 5a84f42 + 3648cd6 commit 4a3bb16
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 31 deletions.
20 changes: 12 additions & 8 deletions be/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,20 +57,24 @@ export class AuthService {
}
}

async createTokens(id: number) {
const payload = { id: id };
const accessToken = this.jwtService.sign(payload);
const refreshToken = this.jwtService.sign(payload, {
secret: "nibobnebob",
expiresIn: "7d",
});
await this.authRepository.upsert({ id: id, accessToken: accessToken, refreshToken: refreshToken }, ["id"]);
return { accessToken, refreshToken };
}

async signin(loginRequestUser: any) {
const user = await this.userRepository.findOneBy({
email: loginRequestUser.email,
});

if (user) {
const payload = { id: user.id };
const accessToken = this.jwtService.sign(payload);
const refreshToken = this.jwtService.sign(payload, {
secret: "nibobnebob",
expiresIn: "7d",
});
await this.authRepository.upsert({ id: user.id, accessToken: accessToken, refreshToken: refreshToken }, ["id"]);
return { accessToken, refreshToken };
return await this.createTokens(user.id);
} else {
throw new NotFoundException(
"사용자가 등록되어 있지 않습니다. 회원가입을 진행해주세요"
Expand Down
16 changes: 13 additions & 3 deletions be/src/user/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,8 +210,8 @@ export class UserController {
@ApiQuery({ name: 'limit', required: false, description: '페이지 당 항목 수' })
@ApiResponse({ status: 200, description: "내 맛집 리스트 정보 요청 성공" })
@ApiResponse({ status: 401, description: "인증 실패" })
async getMyWishRestaurantListInfo(@GetUser() tokenInfo: TokenInfo, @Query() sortInfoDto: SortInfoDto) {
return await this.userService.getMyWishRestaurantListInfo(tokenInfo,sortInfoDto);
async getMyWishRestaurantListInfo(@GetUser() tokenInfo: TokenInfo, @Query() sortInfoDto: SortInfoDto) {
return await this.userService.getMyWishRestaurantListInfo(tokenInfo, sortInfoDto);
}

@ApiTags("Home")
Expand Down Expand Up @@ -536,6 +536,7 @@ export class UserController {
birthdate: { type: 'string', example: '1234/56/78', description: 'The birth of the user' },
isMale: { type: 'boolean', example: true, description: 'The gender of the user. true is male, false is female' },
profileImage: { type: 'string', format: 'binary', description: 'The profile image of the user' },
isImageChanged: { type: 'boolean', example: true, description: 'The Boolean Value of ProfileImageChanged' }
},
},
})
Expand All @@ -550,8 +551,17 @@ export class UserController {
@Body() body
) {
const userInfoDto = plainToClass(UserInfoDto, body);
if (body.isImageChanged === "true" || body.isImageChanged === true) {
body.isImageChanged = true;
} else if (body.isImageChanged === "false" || body.isImageChanged === false) {
body.isImageChanged = false;
} else {
throw new BadRequestException();
}


const errors = await validate(userInfoDto);
if (errors.length > 0) throw new BadRequestException(errors);
return await this.userService.updateMypageUserInfo(file, tokenInfo, userInfoDto);
return await this.userService.updateMypageUserInfo(file, tokenInfo, userInfoDto, body.isImageChanged);
}
}
4 changes: 2 additions & 2 deletions be/src/user/user.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export class UserRepository extends Repository<User> {
super(User, dataSource.createEntityManager());
}
async createUser(userentity: User) {
await this.save(userentity);
return await this.save(userentity);
}
async getNickNameAvailability(nickName: UserInfoDto["nickName"]) {
const user = await this.findOne({
Expand Down Expand Up @@ -93,7 +93,7 @@ export class UserRepository extends Repository<User> {
.where("user.id NOT IN (:...idList)", { idList })
.andWhere("user.region = :yourRegion", { yourRegion: curUser.region })
.groupBy("user.id")
.orderBy("\"commonRestaurant\"","DESC")
.orderBy("\"commonRestaurant\"", "DESC")
.limit(10)
.getRawMany();

Expand Down
47 changes: 29 additions & 18 deletions be/src/user/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { User } from "./entities/user.entity";
import { RestaurantInfoEntity } from "src/restaurant/entities/restaurant.entity";
import { AuthService } from "src/auth/auth.service";
import { SortInfoDto } from "src/utils/sortInfo.dto";
import { JwtService } from "@nestjs/jwt";

@Injectable()
export class UserService {
Expand All @@ -29,7 +30,7 @@ export class UserService {
private reviewRepository: ReviewRepository,
private userWishRestaurantListRepository: UserWishRestaurantListRepository,
private awsService: AwsService,
private authService: AuthService
private authService: AuthService,
) { }
async signup(@UploadedFile() file: Express.Multer.File, userInfoDto: UserInfoDto) {
if (userInfoDto.password) userInfoDto.password = await hashPassword(userInfoDto.password);
Expand All @@ -49,16 +50,18 @@ export class UserService {

try {
const newUser = this.usersRepository.create(user);
await this.usersRepository.createUser(newUser);
const result = await this.usersRepository.createUser(newUser);
if (file) {
await this.awsService.uploadToS3(profileImage, file.buffer);
}
return;
return this.authService.createTokens(result.id);
} catch (error) {
if (error.code === "23505") {
throw new ConflictException("Duplicated Value");
}
}


}
async getNickNameAvailability(nickName: UserInfoDto["nickName"]) {
return await this.usersRepository.getNickNameAvailability(nickName);
Expand Down Expand Up @@ -209,15 +212,15 @@ export class UserService {
);
const userIdValues = userIds.map((user) => user.followingUserId);
userIdValues.push(tokenInfo.id);
const result = await this.usersRepository.getRecommendUserListInfo( userIdValues ,tokenInfo.id);
const result = await this.usersRepository.getRecommendUserListInfo(userIdValues, tokenInfo.id);

function getRandomInts(min: number, max: number, count: number): number[] {
const ints = new Set<number>();
while (ints.size < count) {
const rand = Math.floor(Math.random() * (max - min + 1)) + min;
ints.add(rand);
const rand = Math.floor(Math.random() * (max - min + 1)) + min;
ints.add(rand);
}
return [...ints].sort((a,b) => a - b);
return [...ints].sort((a, b) => a - b);
}

const randomIndexes = getRandomInts(0, result.length - 1, 2);
Expand Down Expand Up @@ -386,22 +389,30 @@ export class UserService {
async deleteUserAccount(tokenInfo: TokenInfo) {
return await this.usersRepository.deleteUserAccount(tokenInfo.id);
}
async updateMypageUserInfo(file: Express.Multer.File, tokenInfo: TokenInfo, userInfoDto: UserInfoDto) {
userInfoDto.password = await hashPassword(userInfoDto.password);
let profileImage;
if (file) {
const uuid = v4();
profileImage = `profile/images/${uuid}.png`;
} else {
profileImage = "profile/images/defaultprofile.png";
async updateMypageUserInfo(file: Express.Multer.File, tokenInfo: TokenInfo, userInfoDto: UserInfoDto, isChanged: Boolean) {
const existedInfo = await this.usersRepository.findOne({ select: ["profileImage", "password"], where: { id: tokenInfo.id } })

if (userInfoDto.password) userInfoDto.password = await hashPassword(userInfoDto.password);
else userInfoDto.password = existedInfo.password;

let profileImage = existedInfo.profileImage;
if (isChanged) {
if (file) {
const uuid = v4();
profileImage = `profile/images/${uuid}.png`;
} else {
profileImage = "profile/images/defaultprofile.png";
}
}
const user = {

let user = {
...userInfoDto,
profileImage: profileImage
profileImage
};

const newUser = this.usersRepository.create(user);
const updatedUser = await this.usersRepository.updateMypageUserInfo(tokenInfo.id, newUser);
if (file) {
if (file && isChanged) {
this.awsService.uploadToS3(profileImage, file.buffer);
}
return updatedUser;
Expand Down

0 comments on commit 4a3bb16

Please sign in to comment.