Skip to content

Commit

Permalink
Fix/password (#21)
Browse files Browse the repository at this point in the history
* feat: add dependency spring security

* feat: add DTO for password

* feat: add spring security, improve declare DI
  • Loading branch information
LAPLACE4A authored Sep 2, 2024
1 parent 8c9f151 commit ae3e7ab
Show file tree
Hide file tree
Showing 5 changed files with 83 additions and 20 deletions.
1 change: 1 addition & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ repositories {
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-security'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
Expand Down
28 changes: 28 additions & 0 deletions src/main/java/com/kert/config/SecurityConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.kert.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

// api 테스트용 인증 비활성화 꼭 추후 수정할 것!!!
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(authz -> authz
.anyRequest().permitAll()
);
return http.build();
}

}
21 changes: 13 additions & 8 deletions src/main/java/com/kert/controller/PasswordController.java
Original file line number Diff line number Diff line change
@@ -1,23 +1,26 @@
package com.kert.controller;

import com.kert.dto.PasswordDTO;
import com.kert.model.Password;
import com.kert.service.PasswordService;
import org.springframework.beans.factory.annotation.Autowired;

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequiredArgsConstructor
@RequestMapping("/passwords")
public class PasswordController {

@Autowired
private PasswordService passwordService;
private final PasswordService passwordService;

@PostMapping
public ResponseEntity<Password> createPassword(@RequestBody Password password) {
Password createdPassword = passwordService.createPassword(password.getUserId(), password.getHash());
public ResponseEntity<Password> createPassword(@Valid @RequestBody PasswordDTO passwordDTO) {
Password createdPassword = passwordService.createPassword(passwordDTO);
return ResponseEntity.ok(createdPassword);
}

Expand All @@ -27,15 +30,17 @@ public ResponseEntity<Password> getPassword(@PathVariable("user_id") Long userId
return password.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}

@PutMapping("/{user_id}")
public ResponseEntity<Password> updatePassword(@PathVariable("user_id") Long userId, @RequestBody Password password) {
Password updatedPassword = passwordService.updatePassword(userId, password.getHash());
public ResponseEntity<Password> updatePassword(@PathVariable("user_id") Long userId, @RequestBody PasswordDTO passwordDTO) {
Password updatedPassword = passwordService.updatePassword(userId, passwordDTO);
if (updatedPassword != null) {
return ResponseEntity.ok(updatedPassword);
}
return ResponseEntity.notFound().build();
}

@Transactional
@DeleteMapping("/{user_id}")
public ResponseEntity<Void> deletePassword(@PathVariable("user_id") Long userId) {
passwordService.deletePassword(userId);
Expand Down
19 changes: 19 additions & 0 deletions src/main/java/com/kert/dto/PasswordDTO.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.kert.dto;

import lombok.Data;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class PasswordDTO {
private Long userId;

@NotBlank(message = "비밀번호는 필수 항목입니다.")
@Size(min = 8, message = "비밀번호는 8자 이상이어야 합니다.")
private String password;
private String oldPassword;
}
34 changes: 22 additions & 12 deletions src/main/java/com/kert/service/PasswordService.java
Original file line number Diff line number Diff line change
@@ -1,35 +1,45 @@
package com.kert.service;

import com.kert.dto.PasswordDTO;
import com.kert.model.Password;
import com.kert.repository.PasswordRepository;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
@RequiredArgsConstructor
public class PasswordService {
private final PasswordRepository passwordRepository;
private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

@Autowired
private PasswordRepository passwordRepository;
public Password createPassword(PasswordDTO passwordDTO) {
String hashedPassword = passwordEncoder.encode(passwordDTO.getPassword());

public Password createPassword(Long userId, String hash) {
Password password = new Password();
password.setUserId(userId);
password.setHash(hash);
password.setUserId(passwordDTO.getUserId());
password.setHash(hashedPassword);

return passwordRepository.save(password);
}

public Optional<Password> getPasswordByUserId(Long userId) {
return passwordRepository.findByUserId(userId);
}

public Password updatePassword(Long userId, String newHash) {
Optional<Password> existingPassword = passwordRepository.findByUserId(userId);
if (existingPassword.isPresent()) {
Password password = existingPassword.get();
password.setHash(newHash);
return passwordRepository.save(password);
public Password updatePassword(Long userId, PasswordDTO passwordDTO) {
Optional<Password> existingPasswordOptional = passwordRepository.findByUserId(userId);
if (existingPasswordOptional.isPresent()) {
Password existingPassword = existingPasswordOptional.get();
if (passwordEncoder.matches(passwordDTO.getOldPassword(), existingPassword.getHash())) {
String newHashedPassword = passwordEncoder.encode(passwordDTO.getPassword());
existingPassword.setHash(newHashedPassword);
return passwordRepository.save(existingPassword);
} else {
return null;
}
}
return null;
}
Expand Down

0 comments on commit ae3e7ab

Please sign in to comment.