-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[PC-379] 어드민 모듈 로그인 기능 #34
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
package org.yapp.auth.application; | ||
|
||
public enum AdminRole { | ||
ADMIN, | ||
ROLE_ADMIN; | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
package org.yapp.auth.application; | ||
|
||
import lombok.RequiredArgsConstructor; | ||
import lombok.extern.slf4j.Slf4j; | ||
import org.springframework.beans.factory.annotation.Value; | ||
import org.springframework.stereotype.Service; | ||
import org.yapp.auth.AuthToken; | ||
import org.yapp.auth.AuthTokenGenerator; | ||
import org.yapp.auth.application.dto.LoginDto; | ||
import org.yapp.domain.user.User; | ||
import org.yapp.error.code.auth.AuthErrorCode; | ||
import org.yapp.error.exception.ApplicationException; | ||
import org.yapp.user.application.UserService; | ||
|
||
@Slf4j | ||
@Service | ||
@RequiredArgsConstructor | ||
public class AuthService { | ||
|
||
private final UserService userService; | ||
|
||
private final AuthTokenGenerator authTokenGenerator; | ||
|
||
@Value("${admin.password}") | ||
private String PWD; | ||
|
||
public AuthToken login(LoginDto loginDto) { | ||
String oauthId = loginDto.oauthId(); | ||
String password = loginDto.password(); | ||
|
||
User loginUser = userService.getUserByOauthId(oauthId); | ||
|
||
if (password.equals(PWD) && loginUser.getRole().equals(AdminRole.ADMIN.toString())) { | ||
return authTokenGenerator.generate(loginUser.getId(), null, | ||
AdminRole.ROLE_ADMIN.toString()); | ||
} else { | ||
throw new ApplicationException(AuthErrorCode.ACCESS_DENIED); | ||
} | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
package org.yapp.auth.application.dto; | ||
|
||
public record LoginDto(String oauthId, String password) { | ||
|
||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
package org.yapp.auth.presentation; | ||
|
||
import jakarta.validation.Valid; | ||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.http.ResponseEntity; | ||
import org.springframework.web.bind.annotation.PostMapping; | ||
import org.springframework.web.bind.annotation.RequestBody; | ||
import org.springframework.web.bind.annotation.RequestMapping; | ||
import org.springframework.web.bind.annotation.RestController; | ||
import org.yapp.auth.AuthToken; | ||
import org.yapp.auth.application.AuthService; | ||
import org.yapp.auth.presentation.request.LoginRequest; | ||
import org.yapp.util.CommonResponse; | ||
|
||
@RestController | ||
@RequiredArgsConstructor | ||
@RequestMapping("/admin/v1/auth/") | ||
public class AuthController { | ||
|
||
private final AuthService authService; | ||
|
||
@PostMapping("/login") | ||
public ResponseEntity<CommonResponse<AuthToken>> login( | ||
@RequestBody @Valid LoginRequest loginRequest) { | ||
AuthToken authToken = authService.login(loginRequest.toDto()); | ||
return ResponseEntity.ok(CommonResponse.createSuccess(authToken)); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
package org.yapp.auth.presentation.request; | ||
|
||
import jakarta.validation.constraints.NotNull; | ||
import org.yapp.auth.application.dto.LoginDto; | ||
|
||
public record LoginRequest(@NotNull String loginId, @NotNull String password) { | ||
|
||
public LoginDto toDto() { | ||
return new LoginDto(loginId, password); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,3 @@ | ||
spring: | ||
profiles: | ||
include: db | ||
include: db, secret |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
plugins { | ||
id 'java' | ||
} | ||
|
||
group = 'org.yapp' | ||
version = '0.0.1-SNAPSHOT' | ||
|
||
repositories { | ||
mavenCentral() | ||
} | ||
|
||
dependencies { | ||
testImplementation platform('org.junit:junit-bom:5.10.0') | ||
testImplementation 'org.junit.jupiter:junit-jupiter' | ||
} | ||
|
||
test { | ||
useJUnitPlatform() | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
package org.yapp.auth; | ||
|
||
public record AuthToken(String accessToken, String refreshToken) { | ||
|
||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
package org.yapp.auth; | ||
|
||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.beans.factory.annotation.Value; | ||
import org.springframework.stereotype.Component; | ||
import org.yapp.jwt.JwtUtil; | ||
|
||
@Component | ||
@RequiredArgsConstructor | ||
public class AuthTokenGenerator { | ||
|
||
private final JwtUtil jwtUtil; | ||
|
||
@Value("${jwt.accessToken.expiration}") | ||
private Long accessTokenExpiration; | ||
|
||
@Value("${jwt.refreshToken.expiration}") | ||
private Long refreshTokenExpiration; | ||
|
||
|
||
public AuthToken generate(Long userId, String oauthId, String role) { | ||
String accessToken = jwtUtil.createJwt("access_token", userId, oauthId, role, | ||
accessTokenExpiration); | ||
|
||
String refreshToken = jwtUtil.createJwt("refesh_token", userId, oauthId, role, | ||
refreshTokenExpiration); | ||
|
||
return new AuthToken(accessToken, refreshToken); | ||
} | ||
} | ||
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
package org.yapp.jwt; | ||
|
||
import io.jsonwebtoken.ExpiredJwtException; | ||
import jakarta.servlet.FilterChain; | ||
import jakarta.servlet.ServletException; | ||
import jakarta.servlet.http.HttpServletRequest; | ||
import jakarta.servlet.http.HttpServletResponse; | ||
import java.io.IOException; | ||
import java.io.PrintWriter; | ||
import java.util.Collections; | ||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | ||
import org.springframework.security.core.Authentication; | ||
import org.springframework.security.core.GrantedAuthority; | ||
import org.springframework.security.core.context.SecurityContextHolder; | ||
import org.springframework.stereotype.Component; | ||
import org.springframework.web.filter.OncePerRequestFilter; | ||
|
||
@RequiredArgsConstructor | ||
@Component | ||
public class JwtFilter extends OncePerRequestFilter { | ||
|
||
private final JwtUtil jwtUtil; | ||
|
||
@Override | ||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, | ||
FilterChain filterChain) | ||
throws ServletException, IOException { | ||
|
||
String accessToken = request.getHeader("Authorization"); | ||
if (accessToken == null || !accessToken.startsWith("Bearer ")) { | ||
filterChain.doFilter(request, response); | ||
return; | ||
} | ||
accessToken = accessToken.substring(7); | ||
|
||
try { | ||
jwtUtil.isExpired(accessToken); | ||
} catch (ExpiredJwtException e) { | ||
|
||
PrintWriter writer = response.getWriter(); | ||
writer.print("access token expired"); | ||
|
||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); | ||
return; | ||
} | ||
|
||
String category = jwtUtil.getCategory(accessToken); | ||
if (!category.equals("access_token")) { | ||
PrintWriter writer = response.getWriter(); | ||
writer.print("invalid access token"); | ||
|
||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); | ||
return; | ||
} | ||
|
||
Long userId = jwtUtil.getUserId(accessToken); | ||
String role = jwtUtil.getRole(accessToken); | ||
|
||
Authentication authToken = | ||
new UsernamePasswordAuthenticationToken(userId, null, Collections.singleton( | ||
(GrantedAuthority) () -> role)); | ||
|
||
SecurityContextHolder.getContext().setAuthentication(authToken); | ||
|
||
filterChain.doFilter(request, response); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,89 @@ | ||
package org.yapp.jwt; | ||
|
||
import io.jsonwebtoken.Jwts; | ||
import java.nio.charset.StandardCharsets; | ||
import java.util.Date; | ||
import javax.crypto.SecretKey; | ||
import javax.crypto.spec.SecretKeySpec; | ||
import org.springframework.beans.factory.annotation.Value; | ||
import org.springframework.stereotype.Component; | ||
|
||
@Component | ||
public class JwtUtil { | ||
|
||
private final SecretKey secretKey; | ||
|
||
public JwtUtil(@Value("${jwt.secret}") String secret) { | ||
secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), | ||
Jwts.SIG.HS256.key().build().getAlgorithm()); | ||
} | ||
|
||
public String getOauthId(String token) { | ||
String oauthId; | ||
try { | ||
oauthId = Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token) | ||
.getPayload().get("oauthId", String.class); | ||
} catch (Exception e) { | ||
throw new RuntimeException(); | ||
} | ||
return oauthId; | ||
} | ||
|
||
public String getRole(String token) { | ||
String role; | ||
try { | ||
role = Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload() | ||
.get("role", String.class); | ||
} catch (Exception e) { | ||
throw new RuntimeException(); | ||
} | ||
return role; | ||
} | ||
|
||
public Boolean isExpired(String token) { | ||
boolean before; | ||
try { | ||
before = Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token) | ||
.getPayload().getExpiration().before(new Date()); | ||
} catch (Exception e) { | ||
throw new RuntimeException(); | ||
} | ||
return before; | ||
} | ||
|
||
public String createJwt(String category, Long userId, String oauthId, String role, | ||
Long expiredMs) { | ||
return Jwts.builder() | ||
.claim("category", category) | ||
.claim("userId", userId) | ||
.claim("oauthId", oauthId) | ||
.claim("role", role) | ||
.issuedAt(new Date(System.currentTimeMillis())) | ||
.expiration(new Date(System.currentTimeMillis() + expiredMs)) | ||
.signWith(secretKey) | ||
.compact(); | ||
} | ||
|
||
public Long getUserId(String token) { | ||
Long userId; | ||
try { | ||
userId = Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token) | ||
.getPayload().get("userId", Long.class); | ||
} catch (Exception e) { | ||
throw new RuntimeException(); | ||
} | ||
return userId; | ||
} | ||
|
||
public String getCategory(String token) { | ||
String category; | ||
try { | ||
category = Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token) | ||
.getPayload().get("category", String.class); | ||
} catch (Exception e) { | ||
throw new RuntimeException(); | ||
} | ||
return category; | ||
} | ||
} | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -9,8 +9,10 @@ | |
@RequiredArgsConstructor | ||
public enum AuthErrorCode implements ErrorCode { | ||
OAUTH_ERROR(HttpStatus.FORBIDDEN, "Oauth Error"), | ||
ACCESS_DENIED(HttpStatus.FORBIDDEN, "권한이 없습니다."), | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 에러 메시지 한글로 하는 거 좋은 것 같습니다! There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 에러 메시지가 한글인게 더 명확한 것 같습니다 ! 그리고, 에러가 발생한 응답이 전달될때 클라이언트 분들은 저희 서비스만의 에러 코드(ex. 1404, 1402 ...)가 같이 전달되었으면 하는 바람이 있으신 것 같습니다. 한글로 변환하는 김에 저희 서비스 에러코드도 지정하는 것이 어떨까요 ? |
||
; | ||
|
||
|
||
private final HttpStatus httpStatus; | ||
private final String message; | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
책임 분리 좋은 것 같습니다!