Skip to content

Commit

Permalink
Feat: 유저 프로필 수정 정보 추가, 비밀번호 변경 기능
Browse files Browse the repository at this point in the history
  • Loading branch information
saokiritoni committed Oct 8, 2024
1 parent 92a6ae0 commit 434372b
Show file tree
Hide file tree
Showing 9 changed files with 228 additions and 54 deletions.
35 changes: 0 additions & 35 deletions src/main/java/dongguk/osori/domain/user/User.java

This file was deleted.

89 changes: 81 additions & 8 deletions src/main/java/dongguk/osori/domain/user/UserController.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
package dongguk.osori.domain.user;

import dongguk.osori.domain.user.dto.EmailVerificationDto;
import dongguk.osori.domain.user.dto.LoginRequestDto;
import dongguk.osori.domain.user.dto.SignupUserDto;
import dongguk.osori.domain.user.dto.UserProfileDto;
import dongguk.osori.domain.user.dto.*;
import dongguk.osori.domain.user.service.EmailService;
import dongguk.osori.domain.user.service.UserService;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
Expand Down Expand Up @@ -34,7 +33,6 @@ public ResponseEntity<String> sendSignupEmail(@RequestBody Map<String,String> re
return ResponseEntity.ok("인증 코드가 이메일로 전송되었습니다.");
}


// 이메일 인증 코드 확인
@PostMapping("/signup/verify-code")
public ResponseEntity<String> verifyEmailCode(@RequestBody EmailVerificationDto verificationDto) {
Expand All @@ -47,7 +45,6 @@ public ResponseEntity<String> verifyEmailCode(@RequestBody EmailVerificationDto
}
}


// 회원가입
@PostMapping("/signup")
public ResponseEntity<String> signup(@RequestBody SignupUserDto signupUserDto) {
Expand All @@ -66,7 +63,6 @@ public ResponseEntity<String> signup(@RequestBody SignupUserDto signupUserDto) {
}
}


// 유저 프로필 정보 조회
@GetMapping("/profile")
public ResponseEntity<UserProfileDto> getUserProfile(HttpSession session) {
Expand Down Expand Up @@ -96,13 +92,90 @@ public ResponseEntity<String> login(@RequestBody LoginRequestDto loginRequest, H
}
}


// 로그아웃 시 세션 무효화
@PostMapping("/logout")
public ResponseEntity<Void> logout(HttpSession session) {
session.invalidate();
return ResponseEntity.ok().build();
}

// 유저 프로필 수정
@PatchMapping("/profile")
public ResponseEntity<String> updateUserProfile(@RequestBody UserProfileEditDto userProfileEditDto, HttpSession session) {
Long userId = (Long) session.getAttribute("userId");

if (userId == null) {
return ResponseEntity.status(401).body("로그인이 필요합니다.");
}

try {
userService.updateUserProfile(userId, userProfileEditDto);
return ResponseEntity.ok("프로필 수정이 완료되었습니다.");
} catch (IllegalArgumentException e) {
return ResponseEntity.status(400).body(e.getMessage());
} catch (Exception e) {
log.error("Unexpected error during profile update", e);
return ResponseEntity.status(500).body("서버 에러 발생. 나중에 다시 시도해주세요.");
}
}


// 현재 비밀번호 확인
@PostMapping("/verify-password")
public ResponseEntity<String> verifyPassword(@RequestBody PasswordDto passwordDto, HttpSession session) {
Long userId = (Long) session.getAttribute("userId");

if (userId == null) {
return ResponseEntity.status(401).body("로그인이 필요합니다.");
}

if (passwordDto.getPassword() == null || passwordDto.getPassword().isEmpty()) {
return ResponseEntity.status(400).body("비밀번호가 입력되지 않았습니다.");
}

try {
boolean isVerified = userService.verifyPassword(userId, passwordDto);
if (isVerified) {
return ResponseEntity.ok("비밀번호 확인 완료");
} else {
return ResponseEntity.status(400).body("비밀번호가 올바르지 않습니다.");
}
} catch (Exception e) {
log.error("Unexpected error during password verification", e);
return ResponseEntity.status(500).body("서버 에러 발생. 나중에 다시 시도해주세요.");
}
}

// 비밀번호 변경
@PatchMapping("/password")
public ResponseEntity<String> updatePassword(@RequestBody Map<String, String> request, HttpSession session) {
Long userId = (Long) session.getAttribute("userId");

if (userId == null) {
return ResponseEntity.status(401).body("로그인이 필요합니다.");
}

String currentPassword = request.get("currentPassword");
String newPassword = request.get("newPassword");

if (currentPassword == null || newPassword == null || currentPassword.isEmpty() || newPassword.isEmpty()) {
return ResponseEntity.status(400).body("비밀번호가 올바르게 입력되지 않았습니다.");
}

try {
// 현재 비밀번호 확인
boolean isVerified = userService.verifyPassword(userId, new PasswordDto(currentPassword));
if (!isVerified) {
return ResponseEntity.status(400).body("현재 비밀번호가 일치하지 않습니다.");
}

// 비밀번호 변경
userService.updatePassword(userId, new PasswordDto(newPassword));
return ResponseEntity.ok("비밀번호가 성공적으로 변경되었습니다.");
} catch (Exception e) {
log.error("Unexpected error during password update", e);
return ResponseEntity.status(500).body("서버 에러 발생. 나중에 다시 시도해주세요.");
}
}
}

Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package dongguk.osori.domain.user;

import dongguk.osori.domain.user.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

Expand Down
12 changes: 12 additions & 0 deletions src/main/java/dongguk/osori/domain/user/dto/PasswordDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package dongguk.osori.domain.user.dto;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class PasswordDto {
private String password;
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,9 @@ public class UserProfileDto {

private String nickname;
private String email;
private String major;
private int studentNumber;
private String introduce;


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package dongguk.osori.domain.user.dto;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserProfileEditDto {

private String nickname;
private String major;
private int studentNumber;
private String introduce;

}
55 changes: 55 additions & 0 deletions src/main/java/dongguk/osori/domain/user/entity/User.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package dongguk.osori.domain.user.entity;

import jakarta.persistence.*;
import lombok.*;

@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Getter
@Entity
@Table(name = "users")
public class User {

@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long userId;

@Column(nullable = false)
private String nickname;

@Column(nullable = false)
private String email;

@Column(nullable = false)
private String password;

@Column(nullable = true)
private String major;

@Column(nullable = true)
private int studentNumber;

@Column(nullable = true)
private String introduce;
private Integer balance;



public void updateNickName(String nickname) {
this.nickname = nickname;
}
public void updateEmail(String email) { this.email = email; }
public void updatePassword(String password) { this.password = password; }
public void updateMajor(String major) { this.major = major; }
public void updateStudentNumber(int studentNumber) { this.studentNumber = studentNumber; }
public void updateIntroduce(String introduce) { this.introduce = introduce; }
public void updateBalance(int amount) {
if (this.balance == null) {
this.balance = 0;
}
this.balance += amount;
}



}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package dongguk.osori.domain.user;
package dongguk.osori.domain.user.service;

import jakarta.mail.internet.MimeMessage;
import lombok.RequiredArgsConstructor;
Expand Down Expand Up @@ -37,13 +37,12 @@ public MimeMessage createMail(String recipientEmail, int authCode) {
message.setSubject("[Osori] 회원가입을 위한 이메일 인증");

// 이메일 본문
String body = "<h1>안녕하세요. Osori입니다.</h1>"
+ "<h3>회원가입을 위한 요청하신 인증 번호입니다.</h3>"
+ "<div align='center' style='border:1px solid black; font-family:verdana;'>"
+ "<h2>회원가입 인증 코드입니다.</h2>"
+ "<h1 style='color:blue'>" + authCode + "</h1>"
+ "</div>"
+ "<br><h3>감사합니다.</h3>";
String body = "<h1 style='color:#2c2f33;'>안녕하세요, Osori입니다.</h1>"
+ "<h3 style='color:#99aab5;'>회원가입을 위해 요청하신 인증 번호입니다.</h3>"
+ "<div align='center' style='border:1px solid #2c2f33; font-family:verdana;'>"
+ "<h2 style='color:#2c2f33;'>회원가입 인증 코드입니다.</h2>"
+ "<h1 style='color:#7289da'>" + authCode + "</h1>"
+ "</div>";

message.setText(body, "UTF-8", "html");
} catch (Exception e) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
package dongguk.osori.domain.user;
package dongguk.osori.domain.user.service;

import dongguk.osori.domain.user.UserRepository;
import dongguk.osori.domain.user.dto.PasswordDto;
import dongguk.osori.domain.user.dto.SignupUserDto;
import dongguk.osori.domain.user.dto.UserProfileDto;
import dongguk.osori.domain.user.dto.UserProfileEditDto;
import dongguk.osori.domain.user.entity.User;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
Expand Down Expand Up @@ -51,7 +55,7 @@ public Long authenticate(String email, String password) {
return user.getUserId();
}


// 아이디로 프로필 정보 조회
@Transactional(readOnly = true)
public User getUserById(Long userId) {
return userRepository.findById(userId)
Expand All @@ -63,10 +67,54 @@ public UserProfileDto getUserProfile(Long userId) {
.orElseThrow(() -> new IllegalArgumentException("유저 아이디를 찾을 수 없음: " + userId));
return new UserProfileDto(
user.getNickname(),
user.getEmail()
user.getEmail(),
user.getMajor(),
user.getStudentNumber(),
user.getIntroduce()
);
}

// 프로필 수정
@Transactional
public void updateUserProfile(Long userId, UserProfileEditDto userProfileEditDto) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new IllegalArgumentException("유저 아이디를 찾을 수 없음: " + userId));

user.updateNickName(userProfileEditDto.getNickname());
user.updateIntroduce(userProfileEditDto.getIntroduce());
user.updateMajor(userProfileEditDto.getMajor());
user.updateStudentNumber(userProfileEditDto.getStudentNumber());

}

// 현재 비밀번호 확인
@Transactional(readOnly = true)
public boolean verifyPassword(Long userId, PasswordDto passwordDto) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new IllegalArgumentException("유저를 찾을 수 없습니다."));

// 입력된 비밀번호와 해시된 비밀번호 비교
return passwordEncoder.matches(passwordDto.getPassword(), user.getPassword());
}


// 비밀번호 수정
@Transactional
public void updatePassword(Long userId, PasswordDto passwordDto) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new IllegalArgumentException("유저를 찾을 수 없습니다."));

// 입력받은 비밀번호를 암호화
String encodedPassword = passwordEncoder.encode(passwordDto.getPassword());

// 암호화된 비밀번호로 업데이트
user.updatePassword(encodedPassword);

// 업데이트된 유저 정보를 저장
userRepository.save(user);
}




}

0 comments on commit 434372b

Please sign in to comment.