Skip to content
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

8주차 미션 / 서버 3조 김나은 #9

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/main/java/com/kuit/kuit4serverauth/config/WebConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,7 @@ public WebConfig(AuthInterceptor authInterceptor) {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// TODO /profile, /admin 앞에 붙이기
registry.addInterceptor(authInterceptor)
.addPathPatterns("/profile", "/admin");
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package com.kuit.kuit4serverauth.controller;

import com.kuit.kuit4serverauth.model.User;
import com.kuit.kuit4serverauth.repository.UserRepository;
import com.kuit.kuit4serverauth.service.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
Expand All @@ -8,16 +12,36 @@

@RestController
public class UserController {
private final UserRepository userRepository;

public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}

@GetMapping("/profile")
public ResponseEntity<String> getProfile(HttpServletRequest request) {
// TODO : 로그인 한 사용자면 username 이용해 "Hello, {username}" 반환하기
String username = (String) request.getAttribute("username");

if (username != null) {
User user = userRepository.findByUsername(username);
if (user != null) {
return ResponseEntity.ok("Hello, " + user.getUsername());
}
}

return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized");
}

@GetMapping("/admin")
public ResponseEntity<String> getAdmin(HttpServletRequest request) {
// TODO: role이 admin이면 "Hello, admin" 반환하기
String role = (String) request.getAttribute("role");

if ("ROLE_ADMIN".equals(role)) {
return ResponseEntity.ok("Hello, admin");
}

return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Forbidden");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

@Component
public class JwtUtil {
private final String secret = "mysecretkey";
private final String secret = "mysecurekeymysecurekeymysecurekeymysecurekey";
private final long expirationMs = 3600000; // 1 hour

public String generateToken(String username, String role) {
Expand Down