Skip to content

Commit

Permalink
Merge pull request #10 from ssafy-19-final-pjt/feature/#1-oauth-login
Browse files Browse the repository at this point in the history
Feature/#1 oauth login
  • Loading branch information
gurwls0122 authored May 19, 2024
2 parents 173653e + 8fccfcb commit a47299f
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 28 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public class MemberController {
@PostMapping(path = "/", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> register(@RequestBody RegisterRequest registerRequest){

memberService.register(registerRequest);
memberService.register(registerRequest.getEmail(), registerRequest.getPassword(), registerRequest.getName());

return ResponseEntity.status(HttpStatus.OK).body("signup success");
}
Expand All @@ -51,7 +51,7 @@ public ResponseEntity<String> register(@RequestBody RegisterRequest registerRequ
@PostMapping("/login")
public ResponseEntity<String> login(@RequestBody LoginRequest loginRequest, HttpServletResponse response){

TokenResponse tokenResponse = memberService.login(loginRequest);
TokenResponse tokenResponse = memberService.login(loginRequest.getEmail(), loginRequest.getPassword());

response.addHeader(JwtTokenProvider.AUTHORIZATION_HEADER, tokenResponse.getAccessToken());

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package com.ssafy.home.domain.member.service;

import com.ssafy.home.domain.member.dto.request.LoginRequest;
import com.ssafy.home.domain.member.dto.request.RegisterRequest;
import com.ssafy.home.domain.member.dto.response.TokenResponse;
import com.ssafy.home.domain.member.repository.GeneralMemberRepository;
import com.ssafy.home.domain.member.repository.LoginAttemptRepository;
Expand Down Expand Up @@ -44,32 +42,33 @@ public class MemberService {
private final Encryption encryption;

@Transactional
public void register(RegisterRequest registerRequest) {
public void register(String email, String password, String name) {

if (memberRepository.existsByEmail(registerRequest.getEmail())) {
if (memberRepository.existsByEmail(email)) {
throw new AuthenticationException(ErrorCode.MEMBER_NOT_MATCH);
}

String salt = encryption.getSalt();
String password = "";

try {
password = encryption.Hashing(registerRequest.getPassword().getBytes(), salt);
password = encryption.Hashing(password.getBytes(), salt);
} catch (Exception e) {
throw new BusinessException(ErrorCode.INVALID_AES_KEY);
}

Member member = memberRepository.save(registerRequest.toEntity());
Member member = memberRepository.save(Member.builder()
.name(name)
.email(email)
.build());
GeneralMember generalMember = generalMemberRepository.save(GeneralMember.builder().member(member).userEncPassword(password).build());
memberSecurityRepository.save(MemberSecret.builder().generalMember(generalMember).salt(salt).build());
loginAttemptRepository.save(LoginAttempt.builder().member(member).build());

}

@Transactional
public TokenResponse login(LoginRequest loginRequest) {
public TokenResponse login(String email, String password) {

Member member = memberRepository.findByEmail(loginRequest.getEmail())
Member member = memberRepository.findByEmail(email)
.orElseThrow(() -> new AuthenticationException(ErrorCode.MEMBER_NOT_MATCH));

if (member.getLoginAttempt().getCount() >= 5) {
Expand All @@ -80,7 +79,7 @@ public TokenResponse login(LoginRequest loginRequest) {

String salt = member.getGeneralMember().getMemberSecret().getSalt();

String encPassword = encryption.Hashing(loginRequest.getPassword().getBytes(), salt);
String encPassword = encryption.Hashing(password.getBytes(), salt);

if (!member.getGeneralMember().getUserEncPassword().equals(encPassword)) {
throw new AuthenticationException(ErrorCode.MEMBER_NOT_MATCH);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
package com.ssafy.home.global.auth.filter;

import com.ssafy.home.domain.member.service.MemberService;
import com.ssafy.home.entity.member.Member;
import com.ssafy.home.domain.member.repository.MemberRepository;
import com.ssafy.home.global.auth.dto.MemberDto;
import com.ssafy.home.global.auth.jwt.JwtTokenProvider;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
Expand All @@ -16,18 +17,18 @@
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;

@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtTokenProvider jwtTokenProvider;
private final MemberRepository memberRepository;
private final MemberService memberService;

// Jwt Provier 주입
public JwtAuthenticationFilter(MemberRepository memberRepository, JwtTokenProvider jwtTokenProvider) {
this.memberRepository = memberRepository;
public JwtAuthenticationFilter(JwtTokenProvider jwtTokenProvider, MemberService memberService) {
this.jwtTokenProvider = jwtTokenProvider;
this.memberService = memberService;
}

@Override
Expand All @@ -50,14 +51,27 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
log.info("token : {}", token);

if(!jwtTokenProvider.validateToken(token)){
filterChain.doFilter(request,response);
return;

Cookie[] cookies = request.getCookies();

String refreshToken = null;

if (cookies != null) {
refreshToken = Arrays.stream(cookies)
.filter(cookie -> cookie.getName().equals("refreshToken"))
.map(Cookie::getValue)
.findFirst()
.orElse(null);
}

token = memberService.reissue(refreshToken);

response.addHeader(JwtTokenProvider.AUTHORIZATION_HEADER, token);
}

Long userId = jwtTokenProvider.getInfoId(token);
log.info("userId : {}", userId);
Member member = memberRepository.findById(userId)
.orElseThrow(() -> new NoSuchElementException("Error: No member found with id " + userId));
Member member = memberService.getMemberById(userId);

UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
MemberDto.builder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
@RequiredArgsConstructor
public class JwtTokenProvider {

// Header KEY 값
public static final String AUTHORIZATION_HEADER = "Authorization";

// openssl rand -hex 32
Expand All @@ -40,7 +39,7 @@ protected void init() {
}

private Date createAccessTokenExpireTime(Date now){
return new Date(now.getTime() + (1000L * 60 * 5));
return new Date(now.getTime() + (1000L * 60 * 1));
}

private Date createRefreshTokenExpireTime(Date now){
Expand Down Expand Up @@ -93,20 +92,17 @@ public String createRefreshToken(Long id) {
return token;
}

// Jwt Token의 유효성 및 만료 기간 검사합니다
public boolean validateToken(String jwtToken) {
try {
Jws<Claims> claims = Jwts
.parser().verifyWith(this.secretKey).build()
.parseSignedClaims(jwtToken);
// parseClaimsJws가 만료시간을 체크해서 확인할 필요 없음
return true;
} catch (JwtException | IllegalArgumentException e) {
return false;
}
}


public Long getInfoId(String token) {
return parseJson(token).getLong("id");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
.httpBasic(AbstractHttpConfigurer::disable)
.formLogin(AbstractHttpConfigurer::disable)
.logout(AbstractHttpConfigurer::disable)
.addFilterBefore(new JwtAuthenticationFilter(memberRepository, jwtTokenProvider), BasicAuthenticationFilter.class);
.addFilterBefore(new JwtAuthenticationFilter(jwtTokenProvider, memberService), BasicAuthenticationFilter.class);

return http.build();
}
Expand Down

0 comments on commit a47299f

Please sign in to comment.