Skip to content

Commit

Permalink
Merge pull request #18 from Timetris-Trendithon/mainPageError
Browse files Browse the repository at this point in the history
🐛Fix: 리다이렉션 오류 수정과 리턴값 추가
  • Loading branch information
jiinkyung authored Feb 19, 2024
2 parents 8cd3721 + f82890a commit 8872a17
Show file tree
Hide file tree
Showing 7 changed files with 55 additions and 22 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,33 +4,33 @@
import com.trendithon.timetris.domain.mainpage.service.MainPageService;
import com.trendithon.timetris.global.auth.jwt.TokenProvider;
import com.trendithon.timetris.global.exception.ApiResponse;
import com.trendithon.timetris.global.exception.CustomException;
import com.trendithon.timetris.global.exception.enums.ErrorStatus;
import com.trendithon.timetris.global.exception.enums.SuccessStatus;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;

@RestController
@RequiredArgsConstructor
@RequestMapping("/main")
@Slf4j
public class MainPageController {

private final MainPageService mainPageService;
private final TokenProvider tokenProvider;

@GetMapping("")
@GetMapping
public ApiResponse<MainPageDTO> getMainPage(HttpServletRequest request) {
String userName = (String) request.getSession().getAttribute("name");
String imgUrl = (String) request.getSession().getAttribute("picture");
//String accessToken = (String) request.getSession().getAttribute("token");

Long userId = tokenProvider.getUserId(request);
Long userId = mainPageService.getUserId(userName, imgUrl);

MainPageDTO mainPageDTO = mainPageService.getMainPage(userId);
MainPageDTO mainPageDTO = mainPageService.getMainPage(userId, request);
return ApiResponse.success(SuccessStatus.OK, mainPageDTO);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import lombok.NoArgsConstructor;

import java.util.List;
import java.util.stream.Collectors;

@Getter
@AllArgsConstructor @NoArgsConstructor
Expand All @@ -17,8 +16,10 @@ public class MainPageDTO {
List<PlanViewDTO> planViewDTOList;
List<DoViewDTO> doViewDTOList;
List<SeeViewDTO> seeViewDTO;
String userName;
String accessToken;

public static MainPageDTO from(List<Plan> planList, List<Do> doList, List<See> seeList){
public static MainPageDTO from(String accessToken, String username, List<Plan> planList, List<Do> doList, List<See> seeList){
List<PlanViewDTO> planViewDTOS = planList.stream()
.map(PlanViewDTO::of)
.toList();
Expand All @@ -29,7 +30,7 @@ public static MainPageDTO from(List<Plan> planList, List<Do> doList, List<See> s
.map(SeeViewDTO::of)
.toList();

return new MainPageDTO(planViewDTOS, doViewDTOS, seeViewDTO1);
return new MainPageDTO(planViewDTOS, doViewDTOS, seeViewDTO1, username, accessToken);

}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
package com.trendithon.timetris.domain.mainpage.service;

import com.trendithon.timetris.domain.mainpage.domain.UserDate;
import com.trendithon.timetris.domain.mainpage.dto.MainPageDTO;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;

import java.time.LocalDate;

@Service
public interface MainPageService {
MainPageDTO getMainPage(long userId);
MainPageDTO getMainPage(long userId, HttpServletRequest request);

Long getUserId(String username, String imgUrl);
void createUserDate();
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import com.trendithon.timetris.domain.mainpage.repository.*;
import com.trendithon.timetris.global.exception.CustomException;
import com.trendithon.timetris.global.exception.enums.ErrorStatus;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
Expand All @@ -29,9 +30,13 @@ public class MainPageServiceImpl implements MainPageService{
private final UserRepository userRepository;

@Override
public MainPageDTO getMainPage(long userId) {
public MainPageDTO getMainPage(long userId, HttpServletRequest request) {
LocalDate localDate = LocalDate.now();
Date date = dateRepository.findByDate(localDate);

String userName = (String) request.getSession().getAttribute("name");
String accessToken = (String) request.getSession().getAttribute("token");

if (userRepository.findById(userId).isEmpty()){
throw new CustomException(ErrorStatus.USER_NOT_FOUND_ERROR);
}
Expand All @@ -41,7 +46,12 @@ public MainPageDTO getMainPage(long userId) {
List<Do> doList = doRepository.findAllByUserDate(userDate);
List<See> see = seeRepository.findByUserDate(userDate);

return MainPageDTO.from(planList, doList, see);
return MainPageDTO.from(accessToken, userName, planList, doList, see);
}
@Override
public Long getUserId(String userName, String imgUrl) {
Optional<User> user = userRepository.findByNameAndProfile(userName, imgUrl);
return user.get().getId();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
Optional<User> findByNameAndProfile(String name, String profile);
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,26 +32,32 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo
CustomOAuth2User oAuth2User = (CustomOAuth2User) authentication.getPrincipal();

String userName = oAuth2User.getAttribute("name");
String imgUrl = oAuth2User.getAttribute("picture");

String accessToken;
if (oAuth2User.getRole() == Role.GUEST) {
String accessToken = tokenProvider.createAccessToken(oAuth2User.getEmail());
accessToken = tokenProvider.createAccessToken(oAuth2User.getEmail());
response.addHeader(tokenProvider.getAccessHeader(), "Bearer " + accessToken);
tokenProvider.sendAccessAndRefreshToken(response, accessToken, null);

} else {
loginSuccess(response, oAuth2User);
accessToken = loginSuccess(response, oAuth2User);
}
request.getSession().setAttribute("token", accessToken);

request.getSession().setAttribute("name", userName);
//response.sendRedirect("/main");
request.getSession().setAttribute("picture", imgUrl);

response.sendRedirect("/main");
//response.sendRedirect(UriComponentsBuilder.fromUriString("http://localhost:3000/").toUriString());

} catch (Exception e) {
throw e;
}

}

private void loginSuccess(HttpServletResponse response, CustomOAuth2User oAuth2User) throws IOException {
private String loginSuccess(HttpServletResponse response, CustomOAuth2User oAuth2User) throws IOException {
String accessToken = tokenProvider.createAccessToken(oAuth2User.getEmail());
String refreshToken = tokenProvider.createRefreshToken();

Expand All @@ -61,5 +67,7 @@ private void loginSuccess(HttpServletResponse response, CustomOAuth2User oAuth2U
tokenProvider.sendAccessAndRefreshToken(response, accessToken, refreshToken);
tokenProvider.updateRefreshToken(oAuth2User.getEmail(), refreshToken);

return accessToken;

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.trendithon.timetris.global.auth.oauth.handler.OAuth2SuccessHandler;
import com.trendithon.timetris.global.auth.oauth.service.CustomOAuthService;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer.FrameOptionsConfig;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
Expand Down Expand Up @@ -51,9 +52,20 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
oauth.userInfoEndpoint(c -> c.userService(customOAuthService))
// 로그인 성공 시 핸들러
.successHandler(oAuth2SuccessHandler)
);
)
// .logout(logout -> logout
// .logoutSuccessUrl("/login")
// .logoutSuccessUrl("/login"));
.logout(logout ->logout
.logoutUrl("/logout") // Customize the logout URL if needed
.logoutSuccessUrl("/login?logout") // Redirect to login page after logout
.invalidateHttpSession(true) // Invalidate HTTP session
.clearAuthentication(true) // Clear user authentication
.deleteCookies("JSESSIONID") // Delete cookies if any
.logoutSuccessHandler((request, response, authentication) -> {
// Perform additional logout actions if needed
response.setStatus(HttpStatus.OK.value());
})
.permitAll()); // Allow all users to logout


return http.build();
Expand Down

0 comments on commit 8872a17

Please sign in to comment.