Skip to content

Commit

Permalink
Merge pull request #230 from JakduK/bug
Browse files Browse the repository at this point in the history
Bug
  • Loading branch information
pio authored Apr 26, 2017
2 parents d797b67 + 803bb04 commit 2f6f7c8
Show file tree
Hide file tree
Showing 21 changed files with 155 additions and 107 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import com.jakduk.api.common.util.UserUtils;
import com.jakduk.api.common.vo.AuthUserProfile;
import com.jakduk.core.model.simple.UserProfile;
import com.jakduk.core.service.UserService;
import com.jakduk.api.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.jakduk.api.common.constraint;

import com.jakduk.core.model.simple.UserProfile;
import com.jakduk.core.service.UserService;
import com.jakduk.api.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import com.jakduk.core.exception.ServiceError;
import com.jakduk.core.exception.ServiceException;
import com.jakduk.core.model.simple.UserProfile;
import com.jakduk.core.service.UserService;
import com.jakduk.api.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.jakduk.api.common.constraint;

import com.jakduk.core.model.simple.UserProfile;
import com.jakduk.core.service.UserService;
import com.jakduk.api.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import com.jakduk.api.common.util.UserUtils;
import com.jakduk.api.common.vo.AuthUserProfile;
import com.jakduk.core.model.simple.UserOnPasswordUpdate;
import com.jakduk.core.service.UserService;
import com.jakduk.api.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.StandardPasswordEncoder;

Expand Down
21 changes: 14 additions & 7 deletions api/src/main/java/com/jakduk/api/common/util/JwtTokenUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,17 @@
import com.jakduk.core.exception.ServiceError;
import com.jakduk.core.exception.ServiceException;
import io.jsonwebtoken.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.aop.AopInvocationException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mobile.device.Device;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Component
public class JwtTokenUtils implements Serializable {
Expand Down Expand Up @@ -67,6 +68,9 @@ public AttemptSocialUser getAttemptedFromToken(String token) {
try {
final Claims claims = getClaimsFromToken(token);

if (claims.containsKey("id"))
attemptSocialUser.setId(claims.get("id", String.class));

if (claims.containsKey("email"))
attemptSocialUser.setEmail(claims.get("email", String.class));

Expand Down Expand Up @@ -220,22 +224,25 @@ public Boolean isValidateToken(String token) {
private Map<String, Object> convertAttemptedSocialUserToMap(AttemptSocialUser attemptSocialUser) {
Map<String, Object> attempted = new HashMap<>();

if (! ObjectUtils.isEmpty(attemptSocialUser.getEmail()))
if (StringUtils.isNotBlank(attemptSocialUser.getId()))
attempted.put("id", attemptSocialUser.getId());

if (StringUtils.isNotBlank(attemptSocialUser.getEmail()))
attempted.put("email", attemptSocialUser.getEmail());

if (! ObjectUtils.isEmpty(attemptSocialUser.getUsername()))
if (StringUtils.isNotBlank(attemptSocialUser.getUsername()))
attempted.put("username", attemptSocialUser.getUsername());

if (! ObjectUtils.isEmpty(attemptSocialUser.getProviderId()))
if (Objects.nonNull(attemptSocialUser.getProviderId()))
attempted.put("providerId", attemptSocialUser.getProviderId());

if (! ObjectUtils.isEmpty(attemptSocialUser.getProviderUserId()))
if (StringUtils.isNotBlank(attemptSocialUser.getProviderUserId()))
attempted.put("providerUserId", attemptSocialUser.getProviderUserId());

if (! ObjectUtils.isEmpty(attemptSocialUser.getExternalSmallPictureUrl()))
if (StringUtils.isNotBlank(attemptSocialUser.getExternalSmallPictureUrl()))
attempted.put("externalSmallPictureUrl", attemptSocialUser.getExternalSmallPictureUrl());

if (! ObjectUtils.isEmpty(attemptSocialUser.getExternalLargePictureUrl()))
if (StringUtils.isNotBlank(attemptSocialUser.getExternalLargePictureUrl()))
attempted.put("externalLargePictureUrl", attemptSocialUser.getExternalLargePictureUrl());

return attempted;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
@Setter
public class AttemptSocialUser {

private String id;
private String email;
private String username;
private CoreConst.ACCOUNT_TYPE providerId;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,16 @@ public class SocialDetailService implements UserDetailsService {
private UserUtils userUtils;

@Override
public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException {
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {

if (StringUtils.isBlank(userId)) {
throw new IllegalArgumentException("userId 는 꼭 필요한 값입니다.");
if (StringUtils.isBlank(email)) {
throw new IllegalArgumentException("email 는 꼭 필요한 값입니다.");
} else {
User user = userRepository.findOneById(userId)
User user = userRepository.findOneByEmail(email)
.orElseThrow(() -> new ServiceException(ServiceError.NOT_FOUND_ACCOUNT,
CoreUtils.getExceptionMessage("exception.not.found.user")));
CoreUtils.getExceptionMessage("exception.not.found.jakduk.account", email)));

SocialUserDetails socialUserDetails = new SocialUserDetails(user.getId(), user.getEmail(), user.getUsername(), user.getProviderId(), user.getEmail(),
SocialUserDetails socialUserDetails = new SocialUserDetails(user.getId(), email, user.getUsername(), user.getProviderId(), user.getEmail(),
true, true, true, true, UserUtils.getAuthorities(user.getRoles()));

UserPicture userPicture = user.getUserPicture();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.jakduk.api.restcontroller.user;
package com.jakduk.api.restcontroller;

import com.jakduk.api.common.util.JwtTokenUtils;
import com.jakduk.api.common.util.UserUtils;
Expand All @@ -8,17 +8,17 @@
import com.jakduk.api.configuration.authentication.JakdukDetailsService;
import com.jakduk.api.configuration.authentication.SocialDetailService;
import com.jakduk.api.configuration.authentication.user.JakdukUserDetails;
import com.jakduk.api.configuration.authentication.user.SocialUserDetails;
import com.jakduk.api.restcontroller.user.vo.LoginEmailUserForm;
import com.jakduk.api.restcontroller.user.vo.LoginSocialUserForm;
import com.jakduk.api.restcontroller.vo.EmptyJsonResponse;
import com.jakduk.api.service.UserService;
import com.jakduk.api.vo.user.LoginEmailUserForm;
import com.jakduk.api.vo.user.LoginSocialUserForm;
import com.jakduk.core.common.CoreConst;
import com.jakduk.core.exception.ServiceError;
import com.jakduk.core.exception.ServiceException;
import com.jakduk.core.model.db.User;
import com.jakduk.core.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
Expand All @@ -35,6 +35,7 @@
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Optional;

/**
* @author pyohwan
Expand Down Expand Up @@ -65,9 +66,6 @@ public class AuthRestController {
@Autowired
private JakdukDetailsService jakdukDetailsService;

@Autowired
private SocialDetailService socialDetailService;

@Autowired
private UserService userService;

Expand Down Expand Up @@ -115,17 +113,19 @@ public EmptyJsonResponse refreshAndGetAuthenticationToken(HttpServletRequest req
}
}

@ApiOperation(value = "SNS 기반 로그인 (존재 하지 않는 회원이면 신규가입 진행)")
@RequestMapping(value = "/login/social/{providerId}", method = RequestMethod.POST)
public EmptyJsonResponse loginSocialUser(@PathVariable String providerId,
@Valid @RequestBody LoginSocialUserForm form,
Device device,
HttpServletResponse response) {
@ApiOperation("SNS 기반 로그인 (존재 하지 않는 회원이면 신규가입 진행)")
@PostMapping("/login/social/{providerId}")
public EmptyJsonResponse loginSocialUser(
@ApiParam(value = "Provider ID", required = true) @PathVariable String providerId,
@ApiParam(value = "SNS 회원 폼", required = true) @Valid @RequestBody LoginSocialUserForm form,
Device device,
HttpServletResponse response) {

log.info("accessToken={}", form.getAccessToken());

CoreConst.ACCOUNT_TYPE convertProviderId = CoreConst.ACCOUNT_TYPE.valueOf(providerId.toUpperCase());
SocialProfile socialProfile = null;
AttemptSocialUser attemptSocialUser = null;

switch (convertProviderId) {
case DAUM:
Expand All @@ -136,42 +136,43 @@ public EmptyJsonResponse loginSocialUser(@PathVariable String providerId,
break;
}

log.info("socialProfile({}, {}) email({})", socialProfile.getId(), socialProfile.getNickname(), socialProfile.getEmail());
log.info("socialProfile providerId:{} providerUserId:{} nickname:{} email:{}",
convertProviderId.name(), socialProfile.getId(), socialProfile.getNickname(), socialProfile.getEmail());

try {
User user = userService.findOneByProviderIdAndProviderUserId(convertProviderId, socialProfile.getId());
Optional<User> oUser = userService.findOneByProviderIdAndProviderUserId(convertProviderId, socialProfile.getId());

// 과거에 SNS 가입 회원들은 email이 없는 경우가 있음. 이메일을 DB에 저장
if (StringUtils.isBlank(user.getEmail()) && StringUtils.isNotBlank(socialProfile.getEmail())) {
user.setEmail(socialProfile.getEmail());
userService.save(user);
// User DB 와 SNS Profile 모두에 email이 없을 경우에는 신규 가입으로 진행한다.
// SNS 가입시 이메일 제공 동의를 안해서 그렇다.
if (oUser.isPresent() && StringUtils.isBlank(oUser.get().getEmail()) && StringUtils.isBlank(socialProfile.getEmail())) {

log.info("user({},{}) email({}) has been entered.", user.getId(), user.getUsername(), user.getEmail());
}
User user = oUser.get();

// 토큰 생성
SocialUserDetails userDetails = (SocialUserDetails) socialDetailService.loadUserByUsername(user.getId());

String token = jwtTokenUtils.generateToken(device, userDetails.getId(), userDetails.getEmail(), userDetails.getUsername(),
userDetails.getProviderId().name());
attemptSocialUser = AttemptSocialUser.builder()
.id(user.getId())
.username(user.getUsername())
.providerId(convertProviderId)
.providerUserId(socialProfile.getId())
.build();
}
// 가입 회원이라 로그인
else if (oUser.isPresent()) {
String token = userService.loginSnsUser(device, socialProfile.getEmail(), oUser.get());

response.setHeader(tokenHeader, token);

return EmptyJsonResponse.newInstance();

} catch (ServiceException ignored) {
}

// 신규 가입.
AttemptSocialUser attemptSocialUser = AttemptSocialUser.builder()
.username(socialProfile.getNickname())
.providerId(convertProviderId)
.providerUserId(socialProfile.getId())
.build();

// Daum은 이메일을 안 알려준다.
if (StringUtils.isNotBlank(socialProfile.getEmail()))
attemptSocialUser.setEmail(socialProfile.getEmail());
// 그냥 신규 가입
else {
attemptSocialUser = AttemptSocialUser.builder()
.username(socialProfile.getNickname())
.providerId(convertProviderId)
.providerUserId(socialProfile.getId())
.build();

if (StringUtils.isNotBlank(socialProfile.getEmail()))
attemptSocialUser.setEmail(socialProfile.getEmail());
}

if (StringUtils.isNotBlank(socialProfile.getLargePictureUrl()))
attemptSocialUser.setExternalLargePictureUrl(socialProfile.getLargePictureUrl());
Expand Down Expand Up @@ -207,4 +208,5 @@ public AuthUserProfile getMyProfile() {

return authUserProfile;
}

}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.jakduk.api.restcontroller.user;
package com.jakduk.api.restcontroller;

import com.jakduk.core.common.CoreConst;
import com.jakduk.core.common.util.CoreUtils;
Expand All @@ -9,7 +9,7 @@
import com.jakduk.core.repository.TokenRepository;
import com.jakduk.core.service.CommonService;
import com.jakduk.core.service.EmailService;
import com.jakduk.core.service.UserService;
import com.jakduk.api.service.UserService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
Expand Down
Loading

0 comments on commit 2f6f7c8

Please sign in to comment.