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

Feature/55 add user sms #60

Merged
merged 4 commits into from
Oct 18, 2024
Merged
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
3 changes: 3 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,9 @@ dependencies {

implementation 'com.google.zxing:core:3.4.1'
implementation 'com.google.zxing:javase:3.4.1'

//nurigo ๋ฌธ์ž์ธ์ฆ
implementation 'net.nurigo:sdk:4.3.0'
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

// ๊ฒฝ๋กœ๋ณ„ ์ธ๊ฐ€
http.authorizeHttpRequests((authorize)->
// authorize.requestMatchers("/**").permitAll()
// .requestMatchers("/reissue").permitAll()

authorize.requestMatchers("/login","/", "health","api/users/join").permitAll()
authorize.requestMatchers("/login","/", "health","api/users/join","/sms/**").permitAll()
.requestMatchers("/admin").hasRole("ADMIN")
.requestMatchers("/reissue").permitAll()
.anyRequest().authenticated()
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ public enum ExceptionCode {
NOT_EXIST_REFRESH_TOKEN(400, "๋ฆฌํ”„๋ ˆ์‹œ ํ† ํฐ์ด ์กด์žฌํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค."),
EXPIRED_REFRESH_TOKEN(400, "๋ฆฌํ”„๋ ˆ์‹œ ํ† ํฐ์ด ๋งŒ๋ฃŒ๋˜์—ˆ์Šต๋‹ˆ๋‹ค."),
INVALID_REFRESH_TOKEN(400, "์œ ํšจํ•˜์ง€ ์•Š์€ ๋ฆฌํ”„๋ ˆ์‹œ ํ† ํฐ์ž…๋‹ˆ๋‹ค."),
CURRENT_PASSWORD_NOT_MATCH(400, "ํ˜„์žฌ ๋น„๋ฐ€๋ฒˆํ˜ธ์™€ ์ผ์น˜ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.");
CURRENT_PASSWORD_NOT_MATCH(400, "ํ˜„์žฌ ๋น„๋ฐ€๋ฒˆํ˜ธ์™€ ์ผ์น˜ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค."),
UNAUTHORIZED(401, "์ธ์ฆ์— ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค.");

private final int code;
private final String message;
Expand Down
38 changes: 38 additions & 0 deletions src/main/java/com/sscanner/team/user/SmsCertificationUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.sscanner.team.user;

import jakarta.annotation.PostConstruct;
import net.nurigo.sdk.NurigoApp;
import net.nurigo.sdk.message.model.Message;
import net.nurigo.sdk.message.request.SingleMessageSendingRequest;
import net.nurigo.sdk.message.service.DefaultMessageService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class SmsCertificationUtil {
@Value("${coolsms.api.key}")
private String apiKey;

@Value("${coolsms.api.secret}")
private String apiSecret;

@Value("${coolsms.api.number}")
private String fromNumber;

DefaultMessageService messageService;

@PostConstruct // ์˜์กด์„ฑ ์ฃผ์ž…์ด ์™„๋ฃŒ๋œ ํ›„ ์ดˆ๊ธฐํ™” ์ˆ˜ํ–‰
public void init(){
this.messageService = NurigoApp.INSTANCE.initialize(apiKey, apiSecret, "https://api.coolsms.co.kr");
}

// ๋‹จ์ผ ๋ฉ”์‹œ์ง€ ๋ฐœ์†ก
public void sendSMS(String to, String certificationCode){
Message message = new Message();
message.setFrom(fromNumber);
message.setTo(to);
message.setText("๋ณธ์ธํ™•์ธ ์ธ์ฆ๋ฒˆํ˜ธ๋Š” " + certificationCode + "์ž…๋‹ˆ๋‹ค.");

this.messageService.sendOne(new SingleMessageSendingRequest(message));
}
}
41 changes: 41 additions & 0 deletions src/main/java/com/sscanner/team/user/controller/SmsController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package com.sscanner.team.user.controller;

import com.sscanner.team.global.common.response.ApiResponse;
import com.sscanner.team.global.exception.BadRequestException;
import com.sscanner.team.global.exception.ExceptionCode;
import com.sscanner.team.user.requestdto.SmsRequestDto;
import com.sscanner.team.user.requestdto.SmsVerifyRequestDto;
import com.sscanner.team.user.service.SmsService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
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;

@RestController
@RequiredArgsConstructor
@RequestMapping("/sms")
public class SmsController {

private final SmsService smsService;

@PostMapping("/send")
public ApiResponse<?> SendSMS(@RequestBody @Valid SmsRequestDto smsRequestDto){
smsService.SendSms(smsRequestDto);
return new ApiResponse<>(200,"๋ฌธ์ž๋ฅผ ์ „์†กํ–ˆ์Šต๋‹ˆ๋‹ค",null);
}

@PostMapping("/verify")
public ApiResponse<?> verifyCode(@RequestBody @Valid SmsVerifyRequestDto req) {
boolean verify = smsService.verifyCode(req);
if (verify) {
return new ApiResponse<>(200,"์ธ์ฆ์ด ์™„๋ฃŒ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.",null);
} else {
throw new BadRequestException(ExceptionCode.UNAUTHORIZED);
}
}
}



39 changes: 39 additions & 0 deletions src/main/java/com/sscanner/team/user/repository/SmsRepository.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.sscanner.team.user.repository;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import java.time.Duration;

@RequiredArgsConstructor
@Repository
public class SmsRepository {

private final String PREFIX = "sms:"; // ํ‚ค

private final StringRedisTemplate stringRedisTemplate;

// ์ธ์ฆ ์ •๋ณด ์ €์žฅ
public void createSmsCertification(String phone, String code) {
int LIMIT_TIME = 60 * 120; // ์œ ํšจ์‹œ๊ฐ„ (2๋ถ„)
stringRedisTemplate.opsForValue()
.set(PREFIX + phone, code, Duration.ofSeconds(LIMIT_TIME));
}

// ์ธ์ฆ ์ •๋ณด ์กฐํšŒ
public String getSmsCertification(String phone) {
return stringRedisTemplate.opsForValue().get(PREFIX + phone);
}

//์ธ์ฆ ์ •๋ณด ์‚ญ์ œ
public void deleteSmsCertification(String phone) {
stringRedisTemplate.delete(PREFIX + phone);
}

// ์ธ์ฆ ์ •๋ณด Redis์— ์กด์žฌ ํ™•์ธ
public boolean hasKey(String phone) {
return Boolean.TRUE.equals(stringRedisTemplate.hasKey(PREFIX + phone)); // Redis์—์„œ ํ•ด๋‹น ํ‚ค์˜ ์กด์žฌ ์—ฌ๋ถ€ ํ™•์ธ
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ public interface UserRepository extends JpaRepository<User, String> {
boolean existsByNickname(String nickname);
boolean existsByPhone(String phone);
Optional<User> findByEmail(String email);
Optional<User> findByPhone(String phone);

@Modifying
@Transactional
Expand Down
10 changes: 10 additions & 0 deletions src/main/java/com/sscanner/team/user/requestdto/SmsRequestDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.sscanner.team.user.requestdto;

import jakarta.validation.constraints.NotEmpty;

public record SmsRequestDto(
@NotEmpty(message = "ํœด๋Œ€ํฐ ๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”")
String phoneNum
) {

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.sscanner.team.user.requestdto;

import jakarta.validation.constraints.NotNull;

public record SmsVerifyRequestDto (

@NotNull(message = "ํœด๋Œ€ํฐ ๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”.")
String phoneNum,
@NotNull(message = "์ธ์ฆ๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”.")
String code
){
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@ public record UserJoinRequestDto(
String nickname,

@NotBlank(message = "์ „ํ™”๋ฒˆํ˜ธ๊ฐ€ ๋น„์–ด์žˆ์Šต๋‹ˆ๋‹ค.")
String phone
String phone,

@NotBlank(message = "์ธ์ฆ๋ฒˆํ˜ธ๊ฐ€ ๋น„์–ด์žˆ์Šต๋‹ˆ๋‹ค.")
String smsCode


) {

Expand Down
56 changes: 56 additions & 0 deletions src/main/java/com/sscanner/team/user/service/SmsService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package com.sscanner.team.user.service;

import com.sscanner.team.global.exception.BadRequestException;
import com.sscanner.team.global.exception.ExceptionCode;
import com.sscanner.team.user.SmsCertificationUtil;
import com.sscanner.team.user.repository.SmsRepository;
import com.sscanner.team.user.repository.UserRepository;
import com.sscanner.team.user.requestdto.SmsRequestDto;
import com.sscanner.team.user.requestdto.SmsVerifyRequestDto;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.security.SecureRandom;

@RequiredArgsConstructor
@Service
public class SmsService {

private final SmsCertificationUtil smsCertificationUtil;
private final SmsRepository smsRepository;
private final UserRepository userRepository;

private static final SecureRandom secureRandom = new SecureRandom();

public void SendSms(SmsRequestDto smsRequestDto) {
String phoneNum = smsRequestDto.phoneNum();

if (userRepository.findByPhone(phoneNum).isPresent()) {
throw new BadRequestException(ExceptionCode.DUPLICATED_PHONE);
}

int certificationCode = secureRandom.nextInt(900000) + 100000; // 100000 ~ 999999 ๋ฒ”์œ„์˜ ๋‚œ์ˆ˜
String codeAsString = Integer.toString(certificationCode);

// SMS ์ „์†ก
smsCertificationUtil.sendSMS(phoneNum, codeAsString);

// ์ธ์ฆ ์ฝ”๋“œ ์ €์žฅ
smsRepository.createSmsCertification(phoneNum, codeAsString);

}

public boolean verifyCode(SmsVerifyRequestDto smsVerifyDto) {
if (isVerify(smsVerifyDto.phoneNum(), smsVerifyDto.code())) {
smsRepository.deleteSmsCertification(smsVerifyDto.phoneNum());
return true;
} else {
return false;
}
}

public boolean isVerify(String phoneNum, String code) { // ์ „ํ™”๋ฒˆํ˜ธ์— ๋Œ€ํ•œ ํ‚ค ์กด์žฌ + ์ธ์ฆ์ฝ”๋“œ ์ผ์น˜ ๊ฒ€์ฆ
return smsRepository.hasKey(phoneNum) &&
smsRepository.getSmsCertification(phoneNum).equals(code);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@
import com.sscanner.team.global.exception.ExceptionCode;
import com.sscanner.team.user.repository.UserRepository;
import com.sscanner.team.user.requestdto.UserJoinRequestDto;
import com.sscanner.team.user.requestdto.UserNicknameUpdateRequestDto;
import com.sscanner.team.user.requestdto.UserPasswordChangeRequestDto;
import com.sscanner.team.user.responsedto.*;
import jakarta.transaction.Transactional;
import com.sscanner.team.user.requestdto.SmsVerifyRequestDto;
import com.sscanner.team.user.responsedto.UserJoinResponseDto;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
Expand All @@ -22,6 +23,7 @@ public class UserService {

private final UserRepository userRepository;
private final BCryptPasswordEncoder passwordEncoder;
private final SmsService smsService;
private final UserUtils userUtils;

// ์ด๋ฉ”์ผ ์ค‘๋ณต ์ฒดํฌ
Expand Down Expand Up @@ -68,6 +70,11 @@ public UserJoinResponseDto join(UserJoinRequestDto req){
checkDuplicatedNickname(req.nickname());
checkDuplicatedPhone(req.phone());

if (!smsService.verifyCode(new SmsVerifyRequestDto(req.phone(), req.smsCode()))) {
throw new IllegalArgumentException("ํ•ธ๋“œํฐ ์ธ์ฆ์— ์‹คํŒจํ•˜์˜€์Šต๋‹ˆ๋‹ค."); // ์ธ์ฆ ์‹คํŒจ ์‹œ ์˜ˆ์™ธ ๋˜์ง
}


confirmPassword(req.password(), req.passwordCheck());

User userEntity = req.toEntity(passwordEncoder.encode(req.password()));
Expand Down
5 changes: 5 additions & 0 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -56,5 +56,10 @@ logging:
jwt:
secret: ${JWT_SECRET}

coolsms:
api:
key: "${COOLSMS_API_KEY}"
secret: "${COOLSMS_API_SECRET}"
number: "${COOLSMS_PHONE_NUMBER}"


Loading