Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

비밀번호 변경/이메일 인증/카테고리 변경 #16

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
implementation 'org.springframework.boot:spring-boot-starter-mail'
implementation group: 'mysql', name: 'mysql-connector-java', version: '8.0.32'

annotationProcessor "org.springframework.boot:spring-boot-configuration-processor"
Expand Down
51 changes: 51 additions & 0 deletions src/main/java/com/chatbar/domain/email/EmailService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.chatbar.domain.email;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
public class EmailService {
@Autowired
private JavaMailSender mailSender;

private final Map<String, VerificationCode> verificationCodes = new HashMap<>();

public void sendVerificationCode(String email) {
VerificationCode code = new VerificationCode(generateRandomCode(6), 5);
verificationCodes.put(email, code);

SimpleMailMessage message = new SimpleMailMessage();
message.setTo(email);
message.setSubject("Your verification code");
message.setText("Your verification code is: " + code.getCode() + "\nThis code will expire in 5 minutes.");

mailSender.send(message);
}

public boolean verifyCode(String email, String enteredCode) {
VerificationCode correctCode = verificationCodes.get(email);
if (correctCode == null || correctCode.isExpired()) {
return false;
}

return correctCode.getCode().equals(enteredCode);
}

private String generateRandomCode(int length) {
String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
StringBuilder code = new StringBuilder();

for (int i = 0; i < length; i++) {
int randomIndex = new Random().nextInt(characters.length());
code.append(characters.charAt(randomIndex));
}

return code.toString();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.chatbar.domain.email;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/api")
public class EmailVerificationController {
private final EmailService emailService;

public EmailVerificationController(EmailService emailService){
this.emailService = emailService;
}

@PostMapping("/requestVerificationCode")
public ResponseEntity<?> requestVerificationCode(@RequestBody Map<String, Object> payload) {
String email = (String) payload.get("email");
emailService.sendVerificationCode(email);
return ResponseEntity.ok().build();
}

@PostMapping("/verifyCode")
public ResponseEntity<?> verifyCode(@RequestBody Map<String, Object> payload) {
String email = (String) payload.get("email");
String enteredCode = (String) payload.get("enteredCode");

if (emailService.verifyCode(email, enteredCode)) {
return ResponseEntity.ok().body("true");
} else {
return ResponseEntity.ok().body("false");
}
}
}
22 changes: 22 additions & 0 deletions src/main/java/com/chatbar/domain/email/VerificationCode.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.chatbar.domain.email;

import java.time.LocalDateTime;

public class VerificationCode {
private String code;
private LocalDateTime expiryTime;

public VerificationCode(String code, int expiryMinutes) {
this.code = code;
this.expiryTime = LocalDateTime.now().plusMinutes(expiryMinutes);
}

public boolean isExpired() {
return LocalDateTime.now().isAfter(expiryTime);
}

public String getCode() {
return code;
}
}

34 changes: 34 additions & 0 deletions src/main/java/com/chatbar/domain/user/application/UserService.java
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
package com.chatbar.domain.user.application;

import com.chatbar.domain.common.Category;
import com.chatbar.domain.user.domain.User;
import com.chatbar.domain.user.domain.repository.UserRepository;
import com.chatbar.domain.user.dto.UserRes;
import com.chatbar.global.DefaultAssert;
import com.chatbar.global.config.security.token.UserPrincipal;
import com.chatbar.global.payload.ApiResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.EnumSet;
import java.util.NoSuchElementException;
import java.util.Optional;

@Service
Expand All @@ -20,6 +25,9 @@ public class UserService {

private final UserRepository userRepository;

@Autowired
private BCryptPasswordEncoder passwordEncoder;

//유저 조회 (조회 기준 - 유저 id)
public ResponseEntity<?> findUser(UserPrincipal userPrincipal) {

Expand All @@ -42,4 +50,30 @@ public ResponseEntity<?> findUser(UserPrincipal userPrincipal) {
return ResponseEntity.ok(apiResponse);
}


public void updateCategories(UserPrincipal userPrincipal, EnumSet<Category> newCategories){
User user = userRepository.findById(userPrincipal.getId())
.orElseThrow(() -> new NoSuchElementException("User with id " + userPrincipal.getId() + " not found"));
user.updateCategories(newCategories);
}

public UserPrincipal getUserPrincipalByEmail(String email) {
User user = userRepository.findByEmail(email)
.orElseThrow(() -> new NoSuchElementException("User with email " + email + " not found"));
return UserPrincipal.create(user);
}


public void updatePassword(UserPrincipal userPrincipal, String newPassword) {
User user = userRepository.findById(userPrincipal.getId())
.orElseThrow(() -> new NoSuchElementException("User not found"));
user.updatePassword(passwordEncoder.encode(newPassword));
}

public void updatePasswordByEmail(String email, String newPassword) {
User user = userRepository.findByEmail(email)
.orElseThrow(() -> new NoSuchElementException("User with email " + email + " not found"));
user.updatePassword(passwordEncoder.encode(newPassword));
}

}
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
package com.chatbar.domain.user.presentation;

import com.chatbar.domain.common.Category;
import com.chatbar.domain.email.EmailService;
import com.chatbar.domain.user.application.FollowService;
import com.chatbar.domain.user.application.UserService;
import com.chatbar.global.config.security.token.CurrentUser;
import com.chatbar.global.config.security.token.UserPrincipal;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.EnumSet;
import java.util.Map;
import java.util.NoSuchElementException;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/users")
Expand All @@ -16,6 +23,8 @@ public class UserController {
private final UserService userService;
private final FollowService followService;

private final EmailService emailService;

//유저 조회
@GetMapping
public ResponseEntity<?> findUser(
Expand Down Expand Up @@ -54,4 +63,49 @@ public ResponseEntity<?> findFollowing(@CurrentUser UserPrincipal userPrincipal)
return followService.IFollow(userPrincipal);
}

//Set Category of User
@PatchMapping("/categories")
public ResponseEntity<?> updateCategories(@CurrentUser UserPrincipal userPrincipal, @RequestBody EnumSet<Category> newCategories){
try {
userService.updateCategories(userPrincipal, newCategories);
return ResponseEntity.ok().build(); // return 200 OK without body
} catch (NoSuchElementException e) {
return ResponseEntity.notFound().build(); // return 404 Not Found
}
}

@PostMapping("/requestVeri")
public ResponseEntity<?> requestVerificationCode(@RequestBody Map<String, String> emailPayload){
String email = emailPayload.get("email");
try {
emailService.sendVerificationCode(email);
return ResponseEntity.ok().build(); // return 200 OK without body
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}

@PostMapping("/verifyCode")
public ResponseEntity<?> verifyCode(@RequestBody Map<String, String> payload){
String email = payload.get("email");
String code = payload.get("code");
if(emailService.verifyCode(email, code)) {
return ResponseEntity.ok().build();
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
}

@PostMapping("/changePassword")
public ResponseEntity<?> changePassword(@RequestBody Map<String, String> payload){
String email = payload.get("email");
String newPassword = payload.get("newPassword");
try {
userService.updatePasswordByEmail(email, newPassword);
return ResponseEntity.ok().build();
} catch (NoSuchElementException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
}

}