Skip to content

Commit

Permalink
Merge pull request #106 from HaegyeongKim01/week11-haegyeong
Browse files Browse the repository at this point in the history
refactor: 명함 UI 및 로직 변경 (frontend & backend)
  • Loading branch information
HaegyeongKim01 authored Nov 14, 2024
2 parents 32fa518 + bca75db commit 044cd71
Show file tree
Hide file tree
Showing 21 changed files with 958 additions and 849 deletions.
196 changes: 101 additions & 95 deletions src/main/java/com/devcard/devcard/auth/service/OauthService.java
Original file line number Diff line number Diff line change
@@ -1,96 +1,102 @@
package com.devcard.devcard.auth.service;

import com.devcard.devcard.auth.entity.Member;
import com.devcard.devcard.auth.model.OauthMemberDetails;
import com.devcard.devcard.auth.repository.MemberRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

@Service
public class OauthService extends DefaultOAuth2UserService {

@Autowired
private MemberRepository memberRepository;

@Override
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException{
OAuth2User oAuth2User = super.loadUser(userRequest);

Map<String, Object> attributes = oAuth2User.getAttributes();
Integer githubIdInt = (Integer) attributes.get("id");
String githubId = String.valueOf(githubIdInt);

String email = fetchEmailFromGitHub(userRequest);

// 데이터베이스에 이미 등록된 사용자인지 확인
Member member = memberRepository.findByGithubId(githubId);
if (member == null) {
// 사용자가 없으면 새로 저장
member = new Member(
githubId,
email,
(String) attributes.get("avatar_url"),
(String) attributes.get("name"),
(String) attributes.get("login"),
"ROLE_USER", // 기본 역할 설정
new Timestamp(System.currentTimeMillis())
);
memberRepository.save(member);
} else {
// 기존 회원 정보 업데이트
member.updateFromAttributes(attributes);
memberRepository.save(member);
}



// OauthMemberDetails 반환
return new OauthMemberDetails(member, attributes);
}

// 이메일 정보를 가져오는 메서드 추가
private String fetchEmailFromGitHub(OAuth2UserRequest userRequest) {
String uri = "https://api.github.com/user/emails";
String accessToken = userRequest.getAccessToken().getTokenValue();

HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "token " + accessToken);
HttpEntity<?> entity = new HttpEntity<>(headers);

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<List<Map<String, Object>>> response = restTemplate.exchange(
uri,
HttpMethod.GET,
entity,
new ParameterizedTypeReference<List<Map<String, Object>>>() {}
);

List<Map<String, Object>> emails = response.getBody();

if (emails != null) {
for (Map<String, Object> emailInfo : emails) {
Boolean primary = (Boolean) emailInfo.get("primary");
Boolean verified = (Boolean) emailInfo.get("verified");
if (primary != null && primary && verified != null && verified) {
return (String) emailInfo.get("email");
}
}
}

return null;
}
package com.devcard.devcard.auth.service;

import com.devcard.devcard.auth.entity.Member;
import com.devcard.devcard.auth.model.OauthMemberDetails;
import com.devcard.devcard.auth.repository.MemberRepository;
import com.devcard.devcard.card.service.CardService;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

@Service
public class OauthService extends DefaultOAuth2UserService {

private final MemberRepository memberRepository;
private final CardService cardService;

public OauthService(MemberRepository memberRepository, CardService cardService) {
this.memberRepository = memberRepository;
this.cardService = cardService;
}

@Override
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException{
OAuth2User oAuth2User = super.loadUser(userRequest);

Map<String, Object> attributes = oAuth2User.getAttributes();
Integer githubIdInt = (Integer) attributes.get("id");
String githubId = String.valueOf(githubIdInt);

String email = fetchEmailFromGitHub(userRequest);

// 데이터베이스에 이미 등록된 사용자인지 확인
Member member = memberRepository.findByGithubId(githubId);
if (member == null) {
// 사용자가 없으면 새로 저장
member = new Member(
githubId,
email,
(String) attributes.get("avatar_url"),
(String) attributes.get("name"),
(String) attributes.get("login"),
"ROLE_USER", // 기본 역할 설정
new Timestamp(System.currentTimeMillis())
);
memberRepository.save(member);

// 회원가입시 멤버 정보로 명함 자동 생성
cardService.createCardWithDefaultInfo(member);
} else {
// 기존 회원 정보 업데이트
member.updateFromAttributes(attributes);
memberRepository.save(member);
}

// OauthMemberDetails 반환
return new OauthMemberDetails(member, attributes);
}

// 이메일 정보를 가져오는 메서드 추가
private String fetchEmailFromGitHub(OAuth2UserRequest userRequest) {
String uri = "https://api.github.com/user/emails";
String accessToken = userRequest.getAccessToken().getTokenValue();

HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "token " + accessToken);
HttpEntity<?> entity = new HttpEntity<>(headers);

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<List<Map<String, Object>>> response = restTemplate.exchange(
uri,
HttpMethod.GET,
entity,
new ParameterizedTypeReference<List<Map<String, Object>>>() {}
);

List<Map<String, Object>> emails = response.getBody();

if (emails != null) {
for (Map<String, Object> emailInfo : emails) {
Boolean primary = (Boolean) emailInfo.get("primary");
Boolean verified = (Boolean) emailInfo.get("verified");
if (primary != null && primary && verified != null && verified) {
return (String) emailInfo.get("email");
}
}
}

return null;
}
}
12 changes: 10 additions & 2 deletions src/main/java/com/devcard/devcard/card/dto/CardRequestDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,27 @@ public class CardRequestDto {

@Pattern(regexp = "^[+]?[0-9\\-\\s]+$", message = "유효한 전화번호 형식을 입력하세요.")
private final String phone;

private final String bio;
private final String email;
private final String cardName;
private final String profileImg;

public CardRequestDto(String company, String position, String phone, String bio) {
public CardRequestDto(String company, String position, String phone, String bio, String email, String cardName, String profileImg) {
this.company = company;
this.position = position;
this.phone = phone;
this.bio = bio;
this.email = email;
this.cardName = cardName;
this.profileImg = profileImg;
}

public String getCompany() { return company; }
public String getPosition() { return position; }
public String getPhone() { return phone; }
public String getBio() { return bio; }
public String getEmail() { return email; }
public String getCardName() { return cardName; }
public String getProfileImg() { return profileImg; }

}
138 changes: 72 additions & 66 deletions src/main/java/com/devcard/devcard/card/dto/CardResponseDto.java
Original file line number Diff line number Diff line change
@@ -1,66 +1,72 @@
package com.devcard.devcard.card.dto;

import com.devcard.devcard.auth.entity.Member;
import com.devcard.devcard.card.entity.Card;

import java.time.LocalDateTime;

public class CardResponseDto {

private final Long id;
private final String name;
private final String company;
private final String position;
private final String email;
private final String phone;
private final String githubId;
private final String bio;
private final String profilePicture;
private final LocalDateTime createdAt;
private final LocalDateTime updatedAt;

public CardResponseDto(Long id, String name, String company, String position, String email, String phone,
String githubId, String bio, String profilePicture,
LocalDateTime createdAt, LocalDateTime updatedAt) {
this.id = id;
this.name = name;
this.company = company;
this.position = position;
this.email = email;
this.phone = phone;
this.githubId = githubId;
this.bio = bio;
this.profilePicture = profilePicture;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
}

public Long getId() { return id; }
public String getName() { return name; }
public String getCompany() { return company; }
public String getPosition() { return position; }
public String getEmail() { return email; }
public String getPhone() { return phone; }
public String getGithubId() { return githubId; }
public String getBio() { return bio; }
public String getProfilePicture() { return profilePicture; }
public LocalDateTime getCreatedAt() { return createdAt; }
public LocalDateTime getUpdatedAt() { return updatedAt; }

public static CardResponseDto fromEntity(Card card) {
Member member = card.getMember();
return new CardResponseDto(
card.getId(),
member.getUsername(),
card.getCompany(),
card.getPosition(),
member.getEmail(),
card.getPhone(),
member.getGithubId(),
card.getBio(),
member.getProfileImg(),
card.getCreatedAt(),
card.getUpdatedAt()
);
}
}
package com.devcard.devcard.card.dto;

import com.devcard.devcard.auth.entity.Member;
import com.devcard.devcard.card.entity.Card;
import com.fasterxml.jackson.annotation.JsonInclude;

import java.time.LocalDateTime;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class CardResponseDto {

private final Long id;
private final String name;
private final String nickname;
private final String company;
private final String position;
private final String email;
private final String phone;
private final String githubId;
private final String bio;
private final String profileImg;
private final LocalDateTime createdAt;
private final LocalDateTime updatedAt;

public CardResponseDto(Long id, String name, String nickname, String company, String position, String email,
String phone, String githubId, String bio, String profileImg,
LocalDateTime createdAt, LocalDateTime updatedAt) {
this.id = id;
this.name = name;
this.nickname = nickname;
this.company = company;
this.position = position;
this.email = email;
this.phone = phone;
this.githubId = githubId;
this.bio = bio;
this.profileImg = profileImg;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
}

public Long getId() { return id; }
public String getName() { return name; }
public String getNickname() { return nickname; }
public String getCompany() { return company; }
public String getPosition() { return position; }
public String getEmail() { return email; }
public String getPhone() { return phone; }
public String getGithubId() { return githubId; }
public String getBio() { return bio; }
public String getProfileImg() { return profileImg; }
public LocalDateTime getCreatedAt() { return createdAt; }
public LocalDateTime getUpdatedAt() { return updatedAt; }

public static CardResponseDto fromEntity(Card card) {
Member member = card.getMember();
return new CardResponseDto(
card.getId(),
member.getUsername(),
card.getNickname(),
card.getCompany(),
card.getPosition(),
member.getEmail(),
card.getPhone(),
member.getGithubId(),
card.getBio(),
member.getProfileImg(),
card.getCreatedAt(),
card.getUpdatedAt()
);
}
}
Loading

0 comments on commit 044cd71

Please sign in to comment.