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

[FINDY-69] feat: place 도메인 추가 및 @LoginUser 활용 #8

Merged
merged 16 commits into from
Oct 6, 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
8 changes: 8 additions & 0 deletions src/main/java/org/findy/findy_be/FindyBeApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,20 @@
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.servers.Server;

@SpringBootApplication
@EnableJpaAuditing
@EnableConfigurationProperties({
CorsProperties.class,
AppProperties.class
})
@OpenAPIDefinition(
servers = {
@Server(url = "http://localhost:8080", description = "Default Server url")
}
)
public class FindyBeApplication {

public static void main(String[] args) {
Expand Down
16 changes: 2 additions & 14 deletions src/main/java/org/findy/findy_be/auth/api/AuthController.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.util.Date;

import org.findy.findy_be.auth.api.swagger.AuthAPIPresentation;
import org.findy.findy_be.auth.dto.AuthRequestModel;
import org.findy.findy_be.auth.oauth.domain.UserPrincipal;
import org.findy.findy_be.auth.oauth.token.AuthToken;
Expand All @@ -23,9 +24,6 @@
import org.springframework.web.bind.annotation.RestController;

import io.jsonwebtoken.Claims;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
Expand All @@ -34,7 +32,7 @@
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {
public class AuthController implements AuthAPIPresentation {

private final AppProperties appProperties;
private final AuthTokenProvider tokenProvider;
Expand All @@ -44,11 +42,6 @@ public class AuthController {
private final static long THREE_DAYS_MSEC = 259200000;
private final static String REFRESH_TOKEN = "refresh_token";

@Operation(summary = "User login", description = "Authenticate user and return access token.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Successfully logged in"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@PostMapping("/login")
public String login(
HttpServletRequest request,
Expand Down Expand Up @@ -96,11 +89,6 @@ public String login(
return accessToken.getToken();
}

@Operation(summary = "Refresh access token", description = "Refresh the access token using the refresh token.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Successfully refreshed token"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@GetMapping("/refresh")
public void refreshToken(HttpServletRequest request, HttpServletResponse response) {
// access token 확인
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package org.findy.findy_be.auth.api.swagger;

import org.findy.findy_be.auth.dto.AuthRequestModel;
import org.springframework.web.bind.annotation.RequestBody;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;

@Tag(name = "Authentication API", description = "OAuth2 및 일반 로그인 관련 인증 API입니다.")
public interface AuthAPIPresentation {

@Operation(summary = "일반 로그인", description = "사용자 ID와 비밀번호를 통해 로그인을 처리합니다.", responses = {
@ApiResponse(responseCode = "200", description = "성공적으로 로그인 및 토큰 발급"),
@ApiResponse(responseCode = "401", description = "인증 실패")
})
String login(HttpServletRequest request, HttpServletResponse response,
@Valid @RequestBody AuthRequestModel authRequestModel);

@Operation(summary = "액세스 토큰 갱신", description = "Refresh Token을 사용하여 만료된 액세스 토큰을 갱신합니다.", responses = {
@ApiResponse(responseCode = "200", description = "성공적으로 토큰 갱신됨"),
@ApiResponse(responseCode = "401", description = "인증 실패 - 잘못된 또는 만료된 토큰")
})
void refreshToken(HttpServletRequest request, HttpServletResponse response);
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import java.util.stream.Stream;

import org.findy.findy_be.common.entity.BaseEntity;
import org.findy.findy_be.place.domain.MajorCategory;
import org.findy.findy_be.user.domain.User;

import jakarta.persistence.Entity;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ public void doFilter(final ServletRequest req, final ServletResponse res, final
String origin = request.getHeader("Origin");

if (origin != null && (origin.equals("http://localhost:5173") ||
origin.equals("http://localhost:8080") ||
origin.equals("https://nid.naver.com") ||
origin.equals("https://kauth.kakao.com"))) {
response.setHeader("Access-Control-Allow-Origin", origin);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ public WebSecurityCustomizer webSecurityCustomizer() {
public SecurityFilterChain filterChain(HttpSecurity http, HandlerMappingIntrospector introspector) throws
Exception {
http
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
.csrf(AbstractHttpConfigurer::disable)
.formLogin(AbstractHttpConfigurer::disable)
.httpBasic(AbstractHttpConfigurer::disable)
Expand Down Expand Up @@ -168,4 +169,4 @@ public CorsConfigurationSource corsConfigurationSource() {
corsConfigSource.registerCorsConfiguration("/**", corsConfig);
return corsConfigSource;
}
}
}
34 changes: 34 additions & 0 deletions src/main/java/org/findy/findy_be/common/config/WebConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package org.findy.findy_be.common.config;

import java.util.List;

import org.findy.findy_be.common.meta.LoginUserArgumentResolver;
import org.findy.findy_be.user.application.UserService;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import lombok.RequiredArgsConstructor;

@Configuration
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {

private final UserService userService;

@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(new LoginUserArgumentResolver(userService));
}

@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:8080")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.allowCredentials(true);
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public enum ErrorCode {
// 404 error
NOT_FOUND_EMAIL(NOT_FOUND, "해당 이메일이 존재하지 않습니다."),
NOT_FOUND_USER(NOT_FOUND, "해당 이메일을 가진 유저가 존재하지 않습니다."),
NOT_FOUND_USER_BY_ID(NOT_FOUND, "해당 id 가진 유저가 존재하지 않습니다.");
NOT_FOUND_USER_BY_ID(NOT_FOUND, "해당 id : %s를 가진 유저가 존재하지 않습니다.");

// 500 error

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,6 @@

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
@AuthenticationPrincipal(expression = "#this == 'anonymousUser' ? null : user")
@AuthenticationPrincipal(expression = "#this == 'anonymousUser' ? null : username")
public @interface LoginUser {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package org.findy.findy_be.common.meta;

import org.findy.findy_be.user.application.UserService;
import org.findy.findy_be.user.domain.User;
import org.springframework.core.MethodParameter;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
public class LoginUserArgumentResolver implements HandlerMethodArgumentResolver {

private final UserService userService;

@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterAnnotation(LoginUser.class) != null
&& User.class.isAssignableFrom(parameter.getParameterType());
}

@Override
public Object resolveArgument(MethodParameter parameter,
ModelAndViewContainer mavContainer,
NativeWebRequest webRequest,
WebDataBinderFactory binderFactory) throws Exception {
UserDetails principal = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return userService.findUser(principal.getUsername());
}
}
33 changes: 33 additions & 0 deletions src/main/java/org/findy/findy_be/marker/domain/Marker.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package org.findy.findy_be.marker.domain;

import org.findy.findy_be.bookmark.domain.Bookmark;
import org.findy.findy_be.common.entity.BaseEntity;
import org.findy.findy_be.place.domain.Place;

import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@Builder
@AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Entity
@Table(name = "markers")
public class Marker extends BaseEntity {

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "place_id")
private Place place;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "bookmark_id")
private Bookmark bookmark;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package org.findy.findy_be.marker.repository;

import org.findy.findy_be.marker.domain.Marker;
import org.springframework.data.jpa.repository.JpaRepository;

public interface MarkerRepository extends JpaRepository<Marker, Long> {
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.findy.findy_be.bookmark.domain;
package org.findy.findy_be.place.domain;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.findy.findy_be.bookmark.domain;
package org.findy.findy_be.place.domain;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
Expand Down
60 changes: 60 additions & 0 deletions src/main/java/org/findy/findy_be/place/domain/Place.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package org.findy.findy_be.place.domain;

import org.findy.findy_be.common.entity.BaseEntity;
import org.findy.findy_be.marker.domain.Marker;

import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.FetchType;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import jakarta.validation.constraints.NotNull;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@Builder
@AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Entity
@Table(name = "places")
public class Place extends BaseEntity {

@NotNull
private String title;

@NotNull
private String link;

private String description;

private String telephone;

@NotNull
private String address;

@NotNull
private String roadAddress;

@NotNull
private String mapx;

@NotNull
private String mapy;

@Enumerated(EnumType.STRING)
@NotNull
private MajorCategory majorCategory;

@Enumerated(EnumType.STRING)
private MiddleCategory middleCategory;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "marker_id")
private Marker marker;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package org.findy.findy_be.place.repository;

import org.findy.findy_be.place.domain.Place;
import org.springframework.data.jpa.repository.JpaRepository;

public interface PlaceRepository extends JpaRepository<Place, Long> {
}
24 changes: 24 additions & 0 deletions src/main/java/org/findy/findy_be/user/api/UserController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package org.findy.findy_be.user.api;

import org.findy.findy_be.common.meta.LoginUser;
import org.findy.findy_be.user.api.swagger.UserAPIPresentation;
import org.findy.findy_be.user.application.UserService;
import org.findy.findy_be.user.domain.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import lombok.RequiredArgsConstructor;

@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController implements UserAPIPresentation {

private final UserService userService;

@GetMapping
public String getUser(@LoginUser User user) {
return user.getProfileImageUrl();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package org.findy.findy_be.user.api.swagger;

import org.findy.findy_be.common.meta.LoginUser;
import org.findy.findy_be.user.domain.User;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;

@Tag(name = "User API", description = "사용자 관련 API 입니다.")
public interface UserAPIPresentation {

@Operation(summary = "사용자 정보 조회",
description = "현재 로그인한 사용자의 프로필 이미지 URL을 조회합니다.",
responses = {
@ApiResponse(responseCode = "200", description = "사용자 정보 조회 성공"),
@ApiResponse(responseCode = "401", description = "인증 실패"),
@ApiResponse(responseCode = "404", description = "사용자를 찾을 수 없음")
})
String getUser(@LoginUser User user);
}

Loading
Loading