Skip to content

Commit

Permalink
Merge pull request #555 from bounswe/backend-authorization
Browse files Browse the repository at this point in the history
authorization logic implemented
  • Loading branch information
canuzdrn authored Oct 28, 2023
2 parents 0b49cf1 + 25c032b commit 6884ef7
Show file tree
Hide file tree
Showing 11 changed files with 160 additions and 61 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package com.app.gamereview.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.app.gamereview.model.User;
import com.app.gamereview.util.AuthorizationRequired;
import com.app.gamereview.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import com.app.gamereview.repository.UserRepository;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Component
public class JwtInterceptor implements HandlerInterceptor {

private final UserRepository userRepository;

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

@Autowired
private ObjectMapper objectMapper;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {

String uri = request.getRequestURI();

// Exclude Swagger URLs
if (uri.startsWith("/v3/api-docs") || uri.contains("/swagger-ui/")) {
return true;
}

if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
AuthorizationRequired authRequired = handlerMethod.getMethodAnnotation(AuthorizationRequired.class);
String token = request.getHeader("Authorization");
if (authRequired != null) {
if (token == null || !JwtUtil.validateToken(token)) {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
Map<String, String> responseMessage = new HashMap<>();
responseMessage.put("message", "Token is not valid");
responseMessage.put("code", "401");

String jsonResponse = objectMapper.writeValueAsString(responseMessage);

response.getWriter().write(jsonResponse);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
return false;
}
String email = JwtUtil.extractSubject(token);
Optional<User> user = userRepository.findByEmailAndIsDeletedFalse(email);
if (user.isPresent()) {
request.setAttribute("authenticatedUser", user.get());
}
else {
response.setStatus(HttpStatus.METHOD_NOT_ALLOWED.value());
Map<String, String> responseMessage = new HashMap<>();
responseMessage.put("message", "User doesn't exist or account is deleted");
responseMessage.put("code", "405");

String jsonResponse = objectMapper.writeValueAsString(responseMessage);

response.getWriter().write(jsonResponse);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
return false;
}
}
}

return true;
}

}
20 changes: 20 additions & 0 deletions app/backend/src/main/java/com/app/gamereview/config/WebConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.app.gamereview.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

@Autowired
private JwtInterceptor jwtInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(jwtInterceptor);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@
import com.app.gamereview.service.AuthService;
import com.app.gamereview.service.EmailService;
import com.app.gamereview.service.UserService;
import com.app.gamereview.util.AuthorizationRequired;
import com.app.gamereview.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
Expand Down Expand Up @@ -52,16 +54,22 @@ public ResponseEntity<User> registerUser(@RequestBody RegisterUserRequestDto reg
return ResponseEntity.ok(userToCreate);
}

@AuthorizationRequired
@PostMapping("/change-password")
public ResponseEntity<Boolean> changePassword(@RequestBody ChangeUserPasswordRequestDto passwordRequestDto) {
Boolean changePasswordResult = authService.changeUserPassword(passwordRequestDto);
public ResponseEntity<Boolean> changePassword(@RequestBody ChangeUserPasswordRequestDto passwordRequestDto,
@RequestHeader String Authorization, HttpServletRequest request) {
User user = (User) request.getAttribute("authenticatedUser");
Boolean changePasswordResult = authService.changeUserPassword(passwordRequestDto, user);
return ResponseEntity.ok(changePasswordResult);
}

@AuthorizationRequired
@PostMapping("/change-forgot-password")
public ResponseEntity<Boolean> changeForgotPassword(
@RequestBody ForgotChangeUserPasswordRequestDto passwordRequestDto) {
Boolean changePasswordResult = authService.changeForgotPassword(passwordRequestDto);
@RequestBody ForgotChangeUserPasswordRequestDto passwordRequestDto, @RequestHeader String Authorization,
HttpServletRequest request) {
User user = (User) request.getAttribute("authenticatedUser");
Boolean changePasswordResult = authService.changeForgotPassword(passwordRequestDto, user);
return ResponseEntity.ok(changePasswordResult);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
@Getter
public class ChangeUserPasswordRequestDto {

private String userId;

private String currentPassword;

private String newPassword;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
@Getter
public class ForgotChangeUserPasswordRequestDto {

private String userId;

private String newPassword;

}
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package com.app.gamereview.dto.request;

import lombok.Getter;

@Getter
public class MeRequestDto {
String token;

String token;

}
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,23 @@
@Getter
@Setter
public class UserResponseDto {
private String username;
private String id;

private String email;
private String username;

private String role;
private String id;

private Boolean isVerified;
private String email;

private String role;

private Boolean isVerified;

public UserResponseDto(User user) {
this.email = user.getEmail();
this.username = user.getUsername();
this.role = user.getRole();
this.isVerified = user.getVerified();
this.id = user.getId();
}

public UserResponseDto(User user) {
this.email = user.getEmail();
this.username = user.getUsername();
this.role = user.getRole();
this.isVerified = user.getVerified();
this.id = user.getId();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public String getUsername() {
return username;
}

public void setUsername(String username) {
public void setUsername(String username) {
this.username = username;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,19 +45,7 @@ public User registerUser(RegisterUserRequestDto registerUserRequestDto) {
return userRepository.save(userToCreate);
}

public Boolean changeUserPassword(ChangeUserPasswordRequestDto passwordRequestDto) {
Optional<User> optionalUser = userRepository.findById(passwordRequestDto.getUserId());

if (optionalUser.isEmpty()) {
return false;
}

User user = optionalUser.get();

if (user.getIsDeleted()) {
return false;
}

public Boolean changeUserPassword(ChangeUserPasswordRequestDto passwordRequestDto, User user) {
if (!Objects.equals(passwordRequestDto.getCurrentPassword(), user.getPassword())) {
return false;
}
Expand All @@ -67,19 +55,7 @@ public Boolean changeUserPassword(ChangeUserPasswordRequestDto passwordRequestDt
return true;
}

public Boolean changeForgotPassword(ForgotChangeUserPasswordRequestDto passwordRequestDto) {
Optional<User> optionalUser = userRepository.findById(passwordRequestDto.getUserId());

if (optionalUser.isEmpty()) {
return false;
}

User user = optionalUser.get();

if (user.getIsDeleted()) {
return false;
}

public Boolean changeForgotPassword(ForgotChangeUserPasswordRequestDto passwordRequestDto, User user) {
user.setPassword(passwordRequestDto.getNewPassword());
userRepository.save(user);
return true;
Expand Down Expand Up @@ -118,6 +94,4 @@ public UserResponseDto me(MeRequestDto meRequestDto) {

}



}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.app.gamereview.util;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AuthorizationRequired {

}
20 changes: 9 additions & 11 deletions app/backend/src/main/java/com/app/gamereview/util/JwtUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -60,16 +60,14 @@ public static boolean validateToken(String token) {
}

public static String extractSubject(String token) {
try {
Claims claims = Jwts.parser()
.setSigningKey(SECRET_KEY)
.parseClaimsJws(token)
.getBody();

return claims.getSubject();
} catch (Exception e) {
return null;
}
}
try {
Claims claims = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();

return claims.getSubject();
}
catch (Exception e) {
return null;
}
}

}

0 comments on commit 6884ef7

Please sign in to comment.