Skip to content

Commit

Permalink
Merge pull request #42 from IoTeaTime/feature/41-kan-96-security-cont…
Browse files Browse the repository at this point in the history
…ext-anotation

feat: Security Context에서 로그인한 회원의 ID 정보 조회 구현, Swagger Authorization 헤더 추가
  • Loading branch information
ywonchae1 authored Oct 30, 2024
2 parents 3d172ed + 824c41b commit 7e8cad6
Show file tree
Hide file tree
Showing 6 changed files with 78 additions and 17 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package org.ioteatime.meonghanyangserver.common.utils;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.security.core.annotation.AuthenticationPrincipal;

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@AuthenticationPrincipal(expression = "id == null ? 0L : id")
public @interface LoginMember {}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.info.Contact;
import io.swagger.v3.oas.annotations.info.Info;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.oas.models.servers.Server;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@OpenAPIDefinition(
Expand All @@ -13,4 +20,48 @@
version = "v1",
contact = @Contact(name = "서유진", email = "[email protected]")))
@Configuration
public class OpenApiConfig {}
public class OpenApiConfig {
@Bean
public OpenAPI openAPI() {
SecurityScheme apiKey =
new SecurityScheme()
.type(SecurityScheme.Type.APIKEY)
.in(SecurityScheme.In.HEADER)
.name("Authorization");

SecurityRequirement securityRequirement = new SecurityRequirement().addList("Bearer Token");

Server productionServer = new Server();
productionServer.setDescription("Production Server");
productionServer.setUrl("https://my-server-name.com");

Server localServer = new Server();
localServer.setDescription("Local Server");
localServer.setUrl("http://localhost:8080");

return new OpenAPI()
.addSecurityItem(getSecurityRequirement())
.components(getAuthComponent())
.servers(List.of(productionServer, localServer))
.components(new Components().addSecuritySchemes("Bearer Token", apiKey))
.addSecurityItem(securityRequirement);
}

private SecurityRequirement getSecurityRequirement() {
String jwt = "JWT";
return new SecurityRequirement().addList(jwt);
}

private Components getAuthComponent() {
return new Components()
.addSecuritySchemes(
"JWT",
new SecurityScheme()
.name("JWT")
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")
.in(SecurityScheme.In.HEADER)
.name("Authorization"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.ioteatime.meonghanyangserver.common.api.Api;
import org.ioteatime.meonghanyangserver.common.utils.LoginMember;
import org.ioteatime.meonghanyangserver.user.dto.request.ChangePasswordRequest;
import org.ioteatime.meonghanyangserver.user.dto.response.UserDetailResponse;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;

Expand All @@ -17,9 +17,9 @@ public interface UserApi {
Api<UserDetailResponse> getUserDetail(@PathVariable("userId") Long userId);

@Operation(summary = "회원 정보를 삭제합니다.")
Api<Object> deleteUser(@PathVariable("userId") Long userId);
Api<Object> deleteUser(@LoginMember Long userId);

@Operation(summary = "회원의 비밀번호를 변경합니다.")
Api<Object> changeUserPassword(
Authentication authentication, @RequestBody @Valid ChangePasswordRequest request);
@LoginMember Long userId, @RequestBody @Valid ChangePasswordRequest request);
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.ioteatime.meonghanyangserver.common.api.Api;
import org.ioteatime.meonghanyangserver.common.utils.LoginMember;
import org.ioteatime.meonghanyangserver.user.dto.request.ChangePasswordRequest;
import org.ioteatime.meonghanyangserver.user.dto.response.UserDetailResponse;
import org.ioteatime.meonghanyangserver.user.service.UserService;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

@RestController
Expand All @@ -16,23 +16,21 @@ public class UserController implements UserApi {
private final UserService userService;

@GetMapping("/{userId}")
public Api<UserDetailResponse> getUserDetail(Long userId) {
public Api<UserDetailResponse> getUserDetail(@PathVariable("userId") Long userId) {
UserDetailResponse userDto = userService.getUserDetail(userId);
return Api.OK(userDto);
}

@DeleteMapping("/{userId}")
public Api<Object> deleteUser(Long userId) {
@DeleteMapping
public Api<Object> deleteUser(@LoginMember Long userId) {
userService.deleteUser(userId);
return Api.OK();
}

@PutMapping("/password")
public Api<Object> changeUserPassword(
Authentication authentication, @RequestBody @Valid ChangePasswordRequest request) {

userService.changeUserPassword(authentication, request);

@LoginMember Long userId, @RequestBody @Valid ChangePasswordRequest request) {
userService.changeUserPassword(userId, request);
return Api.OK();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,8 @@ public String getPassword() {
public String getUsername() {
return userEntity.getEmail();
}

public Long getId() {
return userEntity.getId();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,9 @@
import org.ioteatime.meonghanyangserver.common.error.ErrorTypeCode;
import org.ioteatime.meonghanyangserver.common.exception.ApiException;
import org.ioteatime.meonghanyangserver.user.domain.UserEntity;
import org.ioteatime.meonghanyangserver.user.dto.CustomUserDetail;
import org.ioteatime.meonghanyangserver.user.dto.request.ChangePasswordRequest;
import org.ioteatime.meonghanyangserver.user.dto.response.UserDetailResponse;
import org.ioteatime.meonghanyangserver.user.repository.UserRepository;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand All @@ -34,11 +32,9 @@ public void deleteUser(Long userId) {
}

@Transactional
public void changeUserPassword(Authentication authentication, ChangePasswordRequest request) {
public void changeUserPassword(Long userId, ChangePasswordRequest request) {
String currentPassword = request.getCurrentPassword();
String newPassword = request.getNewPassword();
CustomUserDetail userDetails = (CustomUserDetail) authentication.getPrincipal();
Long userId = userDetails.getUserEntity().getId();

UserEntity userEntity =
userRepository
Expand Down

0 comments on commit 7e8cad6

Please sign in to comment.