Skip to content

Commit

Permalink
jwt 시큐리티 적용
Browse files Browse the repository at this point in the history
  • Loading branch information
mintaek22 committed Jan 6, 2024
1 parent 28ef431 commit b40191f
Show file tree
Hide file tree
Showing 34 changed files with 356 additions and 335 deletions.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.Han2m.portLogistics.admin.controller;

import com.Han2m.portLogistics.admin.dto.LoginRequestDto;
import com.Han2m.portLogistics.admin.dto.TokenDto;
import com.Han2m.portLogistics.admin.dto.UserEditPasswordDto;
import com.Han2m.portLogistics.admin.dto.UserRequestDto;
import com.Han2m.portLogistics.admin.service.AccountService;
import com.Han2m.portLogistics.admin.service.LoginService;
import com.Han2m.portLogistics.exception.ApiResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import static com.Han2m.portLogistics.exception.ApiResponse.successResponse;
import static com.Han2m.portLogistics.exception.ApiResponse.successResponseNoContent;

@Tag(name = "관리자 등록/로그인 API")
@RestController
@RequiredArgsConstructor
@RequestMapping("/api")
public class AdminController {
private final LoginService loginService;
private final AccountService accountService;

@Operation(summary = "직원 계정 생성")
@PostMapping("/worker/{workerId}/account")
public ApiResponse<?> addUser(@PathVariable Long workerId, @RequestBody UserRequestDto userRequestDto) {
accountService.addUser(workerId, userRequestDto);
return successResponseNoContent();
}

@Operation(summary = "계정 로그인")
@PostMapping("/login")
public ApiResponse<TokenDto> login(@RequestBody LoginRequestDto loginRequestDto) {
TokenDto token = loginService.login(loginRequestDto);
return successResponse(token);
}

@Operation(summary = "계정 비밀번호 변경")
@PutMapping("/worker/password")
public ApiResponse<?> editPassword(@RequestBody UserEditPasswordDto userEditPasswordDto) {
accountService.editAccount(userEditPasswordDto);
return successResponseNoContent();
}
}

This file was deleted.

This file was deleted.

13 changes: 7 additions & 6 deletions src/main/java/com/Han2m/portLogistics/admin/domain/Account.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@

@Entity
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
Expand All @@ -24,12 +23,14 @@ public class Account {
@ElementCollection(fetch = FetchType.EAGER)
private List<String> roles;

public void updateInfo(String accountId, String password) {
this.accountId = accountId;
@OneToOne(mappedBy = "account", optional = false)
private Worker worker;

public void editPassword(String password) {
this.password = password;
}

@OneToOne(mappedBy = "account")
private Worker worker;

public void setWorker(Worker worker) {
this.worker = worker;
}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.Han2m.portLogistics.admin.dto;

import lombok.Data;

@Data
public class UserEditPasswordDto {
private String password;
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,6 @@
@Repository
public interface AccountRepository extends JpaRepository<Account, Long> {
Optional<Account> findByAccountId(String accountId);

Boolean existsAccountByAccountId(String accountId);
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
package com.Han2m.portLogistics.admin.service;

import com.Han2m.portLogistics.admin.dto.LoginRequestDto;
import com.Han2m.portLogistics.admin.dto.LoginResponseDto;
import com.Han2m.portLogistics.admin.dto.UserRequestDto;
import com.Han2m.portLogistics.admin.domain.Account;
import com.Han2m.portLogistics.admin.dto.UserEditPasswordDto;
import com.Han2m.portLogistics.admin.dto.UserRequestDto;
import com.Han2m.portLogistics.admin.repository.AccountRepository;
import com.Han2m.portLogistics.exception.EntityNotFoundException;
import com.Han2m.portLogistics.exception.CustomException;
import com.Han2m.portLogistics.user.domain.Worker;
import com.Han2m.portLogistics.user.repository.WorkerRepository;
import lombok.RequiredArgsConstructor;
Expand All @@ -26,41 +25,44 @@ public class AccountService {
private final PasswordEncoder passwordEncoder;
private final WorkerRepository workerRepository;

@Transactional(readOnly = true)
public Boolean isAccountPresent(String accountId) {
return accountRepository.existsAccountByAccountId(accountId);
}

// id, pw, role 받아서 관리자가 회원가입을 시키는 것.
public void addUser(Long workerId, UserRequestDto userRequestDto) { // workerId 인자 추가
if (accountRepository.findByAccountId(userRequestDto.getAccountId()).isEmpty()) {
public void addUser(Long workerId, UserRequestDto userRequestDto) {

Worker worker = workerRepository.findById(workerId).orElseThrow(CustomException.EntityNotFoundException::new);

if(!isAccountPresent(userRequestDto.getAccountId())){

Account account = Account.builder()
.accountId(userRequestDto.getAccountId())
.password(passwordEncoder.encode(userRequestDto.getPassword()))
.roles(userRequestDto.getRoles())
.build();

Worker worker = workerRepository.findById(workerId).orElseThrow(EntityNotFoundException::new);
account.setWorker(worker);
// worker.setAccount(account);

accountRepository.save(account);
} else {
throw new RuntimeException("해당 아이디는 이미 존재합니다.");
Account savedAccount = accountRepository.save(account);
worker.setAccount(savedAccount);
}
else {
throw new CustomException.DuplicateIdException();
}
}



// 계정을 바꾸면, 재로그인을 필수적으로 시켜야함 !!
public LoginResponseDto editAccount(LoginRequestDto loginRequestDto) {
public void editAccount(UserEditPasswordDto userEditPasswordDto) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String currentAccountId = auth.getName();

// 아이디 중복 확인
accountRepository.findByAccountId(loginRequestDto.getAccountId()).orElseThrow(() -> new RuntimeException("해당 아이디는 이미 존재합니다."));

// 현재 로그인된 정보 가져오기
Account account = accountRepository.findByAccountId(currentAccountId).orElseThrow(EntityNotFoundException::new);
Account account = accountRepository.findByAccountId(currentAccountId).orElseThrow(CustomException.EntityNotFoundException::new);

// 현재 로그인된 멤버의 정보 변경
account.updateInfo(loginRequestDto.getAccountId(), passwordEncoder.encode(loginRequestDto.getPassword()));

return new LoginResponseDto(account.getAccountId(), account.getPassword());
account.editPassword(passwordEncoder.encode(userEditPasswordDto.getPassword()));
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.Han2m.portLogistics.admin.service;

import com.Han2m.portLogistics.admin.dto.LoginRequestDto;
import com.Han2m.portLogistics.admin.dto.TokenDto;
import com.Han2m.portLogistics.config.JwtTokenProvider;
import lombok.RequiredArgsConstructor;
Expand All @@ -17,20 +18,17 @@ public class LoginService {
private final AuthenticationManagerBuilder authenticationManagerBuilder;
private final JwtTokenProvider jwtTokenProvider;

@Transactional
public TokenDto login(String accountId, String password) {
public TokenDto login(LoginRequestDto loginRequestDto) {

// 1. Login ID/PW 를 기반으로 Authentication 객체 생성
// 이때 authentication 는 인증 여부를 확인하는 authenticated 값이 false
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(accountId, password);
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginRequestDto.getAccountId(), loginRequestDto.getPassword());

// 2. 실제 검증 (사용자 비밀번호 체크)이 이루어지는 부분
// authenticate 매서드가 실행될 때 CustomUserDetailsService 에서 만든 loadUserByUsername 메서드가 실행
Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);

// 3. 인증 정보를 기반으로 JWT 토큰 생성
TokenDto tokenDto = jwtTokenProvider.generateToken(authentication);

return tokenDto;
return jwtTokenProvider.generateToken(authentication);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,26 @@

import com.Han2m.portLogistics.admin.domain.Account;
import com.Han2m.portLogistics.admin.repository.AccountRepository;
import com.Han2m.portLogistics.exception.CustomException;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class SecurityService implements UserDetailsService {



private final AccountRepository accountRepository;

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return accountRepository.findByAccountId(username)
public UserDetails loadUserByUsername(String accountId){
return accountRepository.findByAccountId(accountId)
.map(this::createUserDetails)
.orElseThrow(() -> new UsernameNotFoundException("해당하는 유저를 찾을 수 없습니다."));
.orElseThrow(CustomException.DuplicateIdException::new);
}

// 해당하는 User 의 데이터가 존재한다면 UserDetails 객체로 만들어서 리턴
Expand Down

This file was deleted.

Loading

0 comments on commit b40191f

Please sign in to comment.