Skip to content

Commit

Permalink
[#72] Fix: Login 버그 수정 (#89)
Browse files Browse the repository at this point in the history
* fix: Fix error about get all rooms

* fix: Fix error about get all rooms

* feat: Make userstory logic with openai

* fire: Fix out port

* fix: Add environment for openai

* fix: Add check left chance

* fix: Fix error

* fix: Fix error

* feat: Make color

* feat: Make login redirect uri

* fix: Fix error

* refactor: Seperate login port

* fix: Redirect

* fix: Fix error

* feat: Fix redirect uri
  • Loading branch information
donggni0712 authored May 19, 2024
1 parent 9c9017e commit 7f69097
Show file tree
Hide file tree
Showing 13 changed files with 139 additions and 78 deletions.
22 changes: 22 additions & 0 deletions src/main/java/com/syncd/AuthControllerProperties.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,33 @@
public class AuthControllerProperties {
private String redirectUrl;

private String redirectUrlDev;

private String redirectUriForGoogle;

private String redirectUriForGoogleDev;


public String getRedirectUrl() {
return redirectUrl;
}

public String getRedirectUrlDev() {
return redirectUrlDev;
}

public String getRedirectUriForGoogle() {return redirectUriForGoogle;}

public String getRedirectUriForGoogleDev() {return redirectUriForGoogleDev;}

public void setRedirectUrl(String redirectUrl) {
this.redirectUrl = redirectUrl;
}
public void setRedirectUrlDev(String redirectUrlDev) {
this.redirectUrlDev = redirectUrlDev;
}

public void setRedirectUriForGoogle(String redirectUriForGoogle) {this.redirectUriForGoogle = redirectUriForGoogle;}

public void setRedirectUriForGoogleDev(String redirectUriForGoogleDev) {this.redirectUriForGoogleDev = redirectUriForGoogleDev;}
}
51 changes: 15 additions & 36 deletions src/main/java/com/syncd/adapter/in/web/AuthController.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,45 +26,24 @@ public class AuthController {

@GetMapping("/code/{registrationId}")
public RedirectView googleLogin(@RequestParam String code,
@PathVariable String registrationId,
HttpServletRequest request,
HttpServletResponse response) {
@PathVariable String registrationId) {
String redirectUri = authControllerProperties.getRedirectUriForGoogle();
String url = authControllerProperties.getRedirectUrl();
TokenDto token = socialLoginUsecase.socialLogin(code, registrationId);

Enumeration<String> reqHeaderNames = request.getHeaderNames();

while (reqHeaderNames.hasMoreElements()) {
String headerName = reqHeaderNames.nextElement();
String headerValue = request.getHeader(headerName);
System.out.println(headerName + ": " + headerValue);
}
String cookies = request.getHeader("cookie");
String referer = request.getHeader("referer");
String refererSubstring="";
if(cookies!=null){
int refererIndex = cookies.indexOf("referer=");
if (refererIndex != -1) {
// 'referer=' 이후의 부분 추출
refererSubstring = cookies.substring(refererIndex + "referer=".length());

// ';' 이전의 부분 추출 (쿠키가 끝날 때까지)
int semicolonIndex = refererSubstring.indexOf(';');
if (semicolonIndex != -1) {
refererSubstring = refererSubstring.substring(0, semicolonIndex);
}
TokenDto token = socialLoginUsecase.socialLogin(code, registrationId,redirectUri);

String redirectUrl = url + token.accessToken();
return new RedirectView(redirectUrl);
}

System.out.println("Referer: " + refererSubstring);
}
} else if (referer!=null) {
System.out.println("Referer from referer");
refererSubstring=referer;
} else {
System.out.println("Referer not found.");
refererSubstring = "https://syncd.i-dear.org/";
}

String redirectUrl = refererSubstring + url + token.accessToken();
@GetMapping("/code/{registrationId}/dev")
public RedirectView googleLoginDev(@RequestParam String code,
@PathVariable String registrationId) {
String url = authControllerProperties.getRedirectUrlDev();
String redirectUri = authControllerProperties.getRedirectUriForGoogleDev();
TokenDto token = socialLoginUsecase.socialLogin(code, registrationId,redirectUri);
String redirectUrl = url + token.accessToken();
System.out.println("redirect: "+redirectUrl);
return new RedirectView(redirectUrl);
}
}
46 changes: 38 additions & 8 deletions src/main/java/com/syncd/adapter/in/web/LoginController.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.syncd.adapter.in.web;

import com.syncd.GoogleOAuth2Properties;
import com.syncd.application.port.in.GetOauthRedirectUrlUsecase;
import com.syncd.application.port.in.SocialLoginUsecase;
import com.syncd.application.port.out.persistence.user.ReadUserPort;
import com.syncd.application.service.LoginService;
Expand All @@ -11,22 +12,51 @@
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;

import java.util.Enumeration;

@RestController
@RequiredArgsConstructor
@RequestMapping("/v1/auth")
public class LoginController {
private final GoogleOAuth2Properties googleOAuth2Properties;
private final GetOauthRedirectUrlUsecase getOauthRedirectUrlUsecase;

@GetMapping("/login/google")
public RedirectView redirectToGoogleOAuth(HttpServletRequest request) {
String redirectUrl = googleOAuth2Properties.getRedirectUri();
String targetUrl = redirectUrl;
String url = "https://accounts.google.com/o/oauth2/auth" +
"?client_id=70988875044-9nmbvd2suleub4ja095mrh83qbi7140j.apps.googleusercontent.com" +
"&redirect_uri=" + targetUrl +
"&response_type=code" +
"&scope=https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile";
String referer = getReferer(request);
String url = getOauthRedirectUrlUsecase.getOauthRedirectUrlUsecase(referer);
System.out.println(url);
return new RedirectView(url);
}

private String getReferer(HttpServletRequest request){

Enumeration<String> reqHeaderNames = request.getHeaderNames();
while (reqHeaderNames.hasMoreElements()) {
String headerName = reqHeaderNames.nextElement();
String headerValue = request.getHeader(headerName);
System.out.println(headerName + ": " + headerValue);
}

String cookies = request.getHeader("cookie");
String referer = request.getHeader("referer");
String refererSubstring="";
if(cookies!=null){
int refererIndex = cookies.indexOf("referer=");
if (refererIndex != -1) {
// 'referer=' 이후의 부분 추출
refererSubstring = cookies.substring(refererIndex + "referer=".length());

// ';' 이전의 부분 추출 (쿠키가 끝날 때까지)
int semicolonIndex = refererSubstring.indexOf(';');
if (semicolonIndex != -1) {
refererSubstring = refererSubstring.substring(0, semicolonIndex);
}
}
} else if (referer!=null) {
refererSubstring=referer;
} else {
refererSubstring = "https://syncd.i-dear.org/";
}
return refererSubstring;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,12 @@ public interface CreateProjectUsecase {
record CreateProjectRequestDto(
@NotBlank(message = ValidationMessages.NAME_NOT_BLANK)
String name,
@NotBlank(message = ValidationMessages.DESCRIPTION_NOT_BLANK)
String description,
MultipartFile img,
@NotNull(message = ValidationMessages.USERS_NOT_NULL)
@Size(min = 1, message = ValidationMessages.USERS_SIZE)
List<String> userEmails
) {
}

) {}
record CreateProjectResponseDto(
String projectId
) {
}
) {}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.syncd.application.port.in;

import com.syncd.exceptions.ValidationMessages;
import jakarta.validation.constraints.NotBlank;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

public interface GetOauthRedirectUrlUsecase {
// ======================================
// METHOD
// ======================================
String getOauthRedirectUrlUsecase(String referer);

}
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@
import com.syncd.dto.TokenDto;

public interface SocialLoginUsecase {
TokenDto socialLogin(String code, String registrationId);
TokenDto socialLogin(String code, String registrationId, String redirectionUri);
}
43 changes: 32 additions & 11 deletions src/main/java/com/syncd/application/service/LoginService.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package com.syncd.application.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.syncd.GoogleOAuth2Properties;
import com.syncd.application.port.in.GenerateTokenUsecase;
import com.syncd.application.port.in.GetOauthRedirectUrlUsecase;
import com.syncd.application.port.in.SocialLoginUsecase;
import com.syncd.application.port.out.persistence.user.ReadUserPort;
import com.syncd.application.port.out.persistence.user.WriteUserPort;
Expand All @@ -19,35 +21,33 @@
@Service
@Primary
@RequiredArgsConstructor
public class LoginService implements SocialLoginUsecase {
public class LoginService implements SocialLoginUsecase, GetOauthRedirectUrlUsecase {
private final RestTemplate restTemplate;
@Value("${spring.security.oauth2.client.registration.google.client-id}")
private String clientId ;
@Value("${spring.security.oauth2.client.registration.google.client-secret}")
private String clientSecret;
@Value("${spring.security.oauth2.client.registration.google.redirect-uri}")
private String redirectUri;

@Value("${spring.security.oauth2.client.provider.google.token-uri}")
private String tokenUri;
@Value("${spring.security.oauth2.client.provider.google.user-info-uri}")
private String resourceUri;
private final WriteUserPort writeUserPort;

private final GoogleOAuth2Properties googleOAuth2Properties;

private final GenerateTokenUsecase generateTokenUsecase;

private final ReadUserPort readUserPort;
@Override
public TokenDto socialLogin(String code, String registrationId) {
String googleAccessToken = getAccessToken(code, registrationId);
public TokenDto socialLogin(String code, String registrationId, String redirectionUri) {
String googleAccessToken = getAccessToken(code, registrationId,redirectionUri);
System.out.println("accesstoken"+googleAccessToken);
JsonNode userResourceNode = getUserResource(googleAccessToken, registrationId);
System.out.println("userResourceNode = " + userResourceNode);

String userEmail = userResourceNode.get("email").asText();
String userName = userResourceNode.get("name").asText();
String userProfileImg = userResourceNode.get("picture").asText();
System.out.println("id = " + userName);
System.out.println("email = " + userEmail);
System.out.println("img = " + userProfileImg);

User user = new User();
user.setName(userName);
Expand All @@ -64,8 +64,8 @@ public TokenDto socialLogin(String code, String registrationId) {
return new TokenDto(accessToken,"");
}

private String getAccessToken(String authorizationCode, String registrationId) {

private String getAccessToken(String authorizationCode, String registrationId, String redirectUri) {
System.out.println(redirectUri);
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("code", authorizationCode);
params.add("client_id", clientId);
Expand All @@ -90,4 +90,25 @@ private JsonNode getUserResource(String accessToken, String registrationId) {
HttpEntity entity = new HttpEntity(headers);
return restTemplate.exchange(resourceUri, HttpMethod.GET, entity, JsonNode.class).getBody();
}

@Override
public String getOauthRedirectUrlUsecase(String referer) {

String redirectUrl = googleOAuth2Properties.getRedirectUri();

String url = "https://accounts.google.com/o/oauth2/auth" +
"?client_id=448582571570-km2g33b06432q3ahl8pathc0tln7g0i4.apps.googleusercontent.com" +
"&redirect_uri=" + redirectUrl +
"&response_type=code" +
"&scope=https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile";

if(referer.contains("localhost")){
url = "https://accounts.google.com/o/oauth2/auth" +
"?client_id=448582571570-km2g33b06432q3ahl8pathc0tln7g0i4.apps.googleusercontent.com" +
"&redirect_uri=" + redirectUrl + "/dev"+
"&response_type=code" +
"&scope=https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile";
}
return url;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,11 @@ public class ProjectService implements CreateProjectUsecase, GetAllRoomsByUserId

@Override
public CreateProjectResponseDto createProject(String hostId, String hostName, String projectName, String description, MultipartFile img, List<String> userEmails){
List<User> users = readUserPort.usersFromEmails(userEmails);
List<User> users = new ArrayList<>();
if(userEmails!=null){
users = readUserPort.usersFromEmails(userEmails);
}


String imgURL = "";
if (img != null && !img.isEmpty()) {
Expand All @@ -55,7 +59,7 @@ public CreateProjectResponseDto createProject(String hostId, String hostName, St
}

Project project = new Project();
project = project.createProjectDomain(projectName, description, imgURL, hostId, null);
project = project.createProjectDomain(projectName, description, imgURL, hostId);
sendMailPort.sendIviteMailBatch(hostName, projectName, users,project.getId());
return new CreateProjectResponseDto(writeProjectPort.CreateProject(project));
}
Expand Down Expand Up @@ -128,7 +132,6 @@ public InviteUserInProjectResponseDto inviteUserInProject(String userId, String
.map(email -> createUserInProjectWithRoleMember(email, host.getName(), project.getName(), projectId))
.collect(Collectors.toList());


return new InviteUserInProjectResponseDto(projectId);
}

Expand Down
10 changes: 4 additions & 6 deletions src/main/java/com/syncd/domain/project/Project.java
Original file line number Diff line number Diff line change
Expand Up @@ -69,21 +69,19 @@ public void subLeftChanceForUserstory(){
// this.progress = 0;
// this.lastModifiedDate = LocalDateTime.now().toString();
// }
public Project createProjectDomain(String projectName, String description, String img, String hostId, List<User> users){
public Project createProjectDomain(String projectName, String description, String img, String hostId){
Project project = new Project();
project.setImg(img);
project.setUsers( userInProjectsFromUsers(hostId,users));
project.setUsers( userInProjectsFromUsers(hostId));
project.setName(projectName);
project.setDescription(description);
project.setProgress(0);
project.setLastModifiedDate(LocalDateTime.now().toString());
project.setLeftChanceForUserstory(3);
return project;
}
private List<UserInProject> userInProjectsFromUsers(String hostId, List<User> members){
if (members == null) {
return Collections.emptyList(); // 호스트는 존재하지만 멤버는 없을 수 있음
}
private List<UserInProject> userInProjectsFromUsers(String hostId){
List<User> members = new ArrayList<>();
return Stream.concat(
Stream.of(new UserInProject(hostId, Role.HOST)), // 호스트 사용자
members.stream().map(el -> new UserInProject(el.getId(), Role.MEMBER))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ void setup() {
String hostId = "hostId";
List<User> userList = new ArrayList<>();
project = new Project();
project = project.createProjectDomain("Project Name", "Description", "img", hostId, userList);
project = project.createProjectDomain("Project Name", "Description", "img", hostId);
project.setId("1");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ void setUp(){
String hostId = "hostUserId";
List<User> emptyUserList = new ArrayList<>();
project = new Project();
project = project.createProjectDomain("Project Name", "Description", "img", hostId, emptyUserList);
project = project.createProjectDomain("Project Name", "Description", "img", hostId);
project.setId("1");
project.setLastModifiedDate(LocalDateTime.now().toString());
project.setProgress(0);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,8 @@ public class WriteProjectPortTest {
@BeforeEach
void setUp(){
String hostId = "hostUserId";
List<User> userList = new ArrayList<>();
project = new Project();
project = project.createProjectDomain("Project Name", "Description", "img", hostId, userList);
project = project.createProjectDomain("Project Name", "Description", "img", hostId);
project.setId("1");
}
@Test
Expand Down
2 changes: 1 addition & 1 deletion src/test/java/domain/project/ProjectTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ void setup() {
userList.add(user2);

project = new Project();
project = project.createProjectDomain("Project Name", "syncd", "img", hostId, userList);
project = project.createProjectDomain("Project Name", "syncd", "img", hostId);
project.setId("1");
}

Expand Down

0 comments on commit 7f69097

Please sign in to comment.