Skip to content

Commit

Permalink
[feat][#6] Implement reload in UserController
Browse files Browse the repository at this point in the history
- 클라이언트가 리로드 되면, 유저 정보를 새로 받아간다
  • Loading branch information
Sinyoung3016 committed May 9, 2022
1 parent 7f671b3 commit eb961d4
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 7 deletions.
1 change: 1 addition & 0 deletions src/main/java/gp/cnusambe/config/WebSecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ protected void configure(HttpSecurity http) throws Exception {

.and()
.authorizeRequests()
.antMatchers("/reload").authenticated()
.antMatchers("/**").permitAll()
.anyRequest().authenticated();
http.addFilterBefore(authTokenFilter(), UsernamePasswordAuthenticationFilter.class);
Expand Down
38 changes: 31 additions & 7 deletions src/main/java/gp/cnusambe/controller/UserController.java
Original file line number Diff line number Diff line change
@@ -1,32 +1,40 @@
package gp.cnusambe.controller;

import gp.cnusambe.domain.User;
import gp.cnusambe.error.AccessTokenException;
import gp.cnusambe.error.InvalidPasswordException;
import gp.cnusambe.error.RefreshTokenException;
import gp.cnusambe.payload.request.LoginRequest;
import gp.cnusambe.payload.request.LogoutOrRefreshRequest;
import gp.cnusambe.payload.request.SignupRequest;
import gp.cnusambe.payload.response.LoginResponse;
import gp.cnusambe.payload.response.UserInfoResponse;
import gp.cnusambe.security.JwtTokenProvider;
import gp.cnusambe.security.UserDetailsImpl;
import gp.cnusambe.service.UserDetailsServiceImpl;
import gp.cnusambe.service.UserService;
import gp.cnusambe.util.RedisUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.net.URI;
import java.util.UUID;

import static gp.cnusambe.security.JwtAuthFilter.AUTHORIZATION_HEADER;
import static gp.cnusambe.security.JwtAuthFilter.BEARER_PREFIX;

@RequiredArgsConstructor
@RestController
public class UserController {
Expand All @@ -49,18 +57,17 @@ public ResponseEntity<Void> signUp(@RequestBody SignupRequest signUpRequest) thr
}

@PostMapping("/login")
public ResponseEntity<LoginResponse> login(@RequestBody LoginRequest loginRequest){
public ResponseEntity<LoginResponse> login(@RequestBody LoginRequest loginRequest) {
Authentication authentication;
try {
authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUserId(), loginRequest.getPassword()));
} catch (BadCredentialsException e) {
throw new InvalidPasswordException();
}

SecurityContextHolder.getContext().setAuthentication(authentication);

UserDetailsImpl userDetailsImpl = (UserDetailsImpl)authentication.getPrincipal();
UserDetailsImpl userDetailsImpl = (UserDetailsImpl) authentication.getPrincipal();
LoginResponse jwtResponse = generateAndSaveToken(userDetailsImpl);

return new ResponseEntity<>(jwtResponse, HttpStatus.OK);
Expand All @@ -76,11 +83,9 @@ public ResponseEntity<LoginResponse> refreshToken(@RequestBody LogoutOrRefreshRe
if (!jwtTokenProvider.validateJwtToken(oldAccessToken)) {
throw new RefreshTokenException();
}

if(!userId.equals(jwtTokenProvider.getUserIdFromJwtToken(oldRefreshToken)) && !userId.equals(jwtTokenProvider.getUserIdFromJwtToken(oldAccessToken))) {
if (!userId.equals(jwtTokenProvider.getUserIdFromJwtToken(oldRefreshToken)) && !userId.equals(jwtTokenProvider.getUserIdFromJwtToken(oldAccessToken))) {
throw new RefreshTokenException();
}

UserDetailsImpl userDetailsImpl = (UserDetailsImpl) userDetailsServiceImp.loadUserByUsername(userId);
LoginResponse jwtResponse = generateAndSaveToken(userDetailsImpl);
deleteToken(uuid, oldAccessToken);
Expand All @@ -94,6 +99,15 @@ public ResponseEntity<Void> logout(@RequestBody LogoutOrRefreshRequest request)
return ResponseEntity.noContent().build();
}

@PostMapping("/reload")
public ResponseEntity<UserInfoResponse> reload(@RequestHeader HttpHeaders header) {
String token = parseJwt(header);
String userId = jwtTokenProvider.getUserIdFromJwtToken(token);
UserDetailsImpl userDetailsImpl = (UserDetailsImpl) userDetailsServiceImp.loadUserByUsername(userId);
UserInfoResponse userInfoResponse = new UserInfoResponse(userDetailsImpl.getUserId(), userDetailsImpl.getAuthorities().stream().findFirst().get().toString());
return new ResponseEntity<>(userInfoResponse, HttpStatus.OK);
}

private LoginResponse generateAndSaveToken(UserDetailsImpl userDetailsImpl) {
String userId = userDetailsImpl.getUserId();
String uuid = UUID.randomUUID().toString();
Expand All @@ -110,6 +124,16 @@ private void deleteToken(String uuid, String oldAccessToken) {
if (redisUtil.getData(uuid).isPresent()) {
redisUtil.deleteData(uuid);
}
redisUtil.setDataExpire(oldAccessToken, oldAccessToken, (int)JwtTokenProvider.TOKEN_EXPIRATION_SECONDS);
redisUtil.setDataExpire(oldAccessToken, oldAccessToken, (int) JwtTokenProvider.TOKEN_EXPIRATION_SECONDS);
}

private String parseJwt(HttpHeaders request) {
String headerAuth = request.getFirst(AUTHORIZATION_HEADER);
if (StringUtils.hasText(headerAuth) && headerAuth.startsWith(BEARER_PREFIX)) {
return headerAuth.substring(7);
}
else{
throw new AccessTokenException();
}
}
}

0 comments on commit eb961d4

Please sign in to comment.