@@ -50,8 +50,9 @@ To run the application, follow these steps:
|
|||||||
GRANT ALL PRIVILEGES ON DATABASE jambotronDB TO admin;
|
GRANT ALL PRIVILEGES ON DATABASE jambotronDB TO admin;
|
||||||
```
|
```
|
||||||
- If you are using Docker, you can run PostgreSQL using the following command:
|
- If you are using Docker, you can run PostgreSQL using the following command:
|
||||||
|
- port 5433 is used.
|
||||||
```bash
|
```bash
|
||||||
docker run --name postgresDB -p 5432:5432 -e POSTGRES_USER=admin -e POSTGRES_PASSWORD=postgrespw -e POSTGRES_DB=jambotronDB -d postgres
|
docker run --name postgresDB -p 5433:5432 -e POSTGRES_USER=admin -e POSTGRES_PASSWORD=postgrespw -e POSTGRES_DB=jambotronDB -d postgres
|
||||||
```
|
```
|
||||||
- if you are wont to use pgadmin
|
- if you are wont to use pgadmin
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
@@ -3,10 +3,11 @@ import { Injectable } from '@angular/core';
|
|||||||
import { HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
|
import { HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
|
||||||
|
|
||||||
import { TokenStorageService } from '../services/token-storage.service';
|
import { TokenStorageService } from '../services/token-storage.service';
|
||||||
import {catchError, Observable, throwError} from 'rxjs';
|
import {catchError, Observable, switchMap, throwError} from 'rxjs';
|
||||||
import {EventBusService} from '../_shared/event-bus.service';
|
import {EventBusService} from '../_shared/event-bus.service';
|
||||||
import {EventData} from '../_shared/event.class';
|
import {EventData} from '../_shared/event.class';
|
||||||
import {environment} from '../../environments/environment';
|
import {environment} from '../../environments/environment';
|
||||||
|
import {AuthService} from '../services/auth.service';
|
||||||
|
|
||||||
const TOKEN_HEADER_KEY = 'Authorization'; // for Spring Boot back-end
|
const TOKEN_HEADER_KEY = 'Authorization'; // for Spring Boot back-end
|
||||||
|
|
||||||
@@ -15,7 +16,11 @@ export class AuthInterceptor implements HttpInterceptor {
|
|||||||
private isRefreshing = false;
|
private isRefreshing = false;
|
||||||
enviorment = environment;
|
enviorment = environment;
|
||||||
|
|
||||||
constructor(private tokenStorageService: TokenStorageService, private eventBusService: EventBusService) { }
|
constructor(
|
||||||
|
private tokenStorageService: TokenStorageService,
|
||||||
|
private eventBusService: EventBusService,
|
||||||
|
private authService:AuthService
|
||||||
|
) { }
|
||||||
|
|
||||||
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
|
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
|
||||||
|
|
||||||
@@ -43,8 +48,23 @@ export class AuthInterceptor implements HttpInterceptor {
|
|||||||
this.isRefreshing = true;
|
this.isRefreshing = true;
|
||||||
|
|
||||||
if (this.tokenStorageService.isLoggedIn()) {
|
if (this.tokenStorageService.isLoggedIn()) {
|
||||||
|
return this.authService.refreshToken().pipe(
|
||||||
|
switchMap(() => {
|
||||||
|
this.isRefreshing = false;
|
||||||
|
console.log("refresh token");
|
||||||
|
return next.handle(request);
|
||||||
|
}),
|
||||||
|
catchError((error) => {
|
||||||
|
this.isRefreshing = false;
|
||||||
|
|
||||||
|
if (error.status == '403') {
|
||||||
this.eventBusService.emit(new EventData('logout', null));
|
this.eventBusService.emit(new EventData('logout', null));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return throwError(() => error);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return next.handle(request);
|
return next.handle(request);
|
||||||
|
|||||||
@@ -36,4 +36,7 @@ export class AuthService {
|
|||||||
logout(): Observable<any> {
|
logout(): Observable<any> {
|
||||||
return this.http.post(AUTH_API + 'signout', { }, httpOptions);
|
return this.http.post(AUTH_API + 'signout', { }, httpOptions);
|
||||||
}
|
}
|
||||||
|
refreshToken() {
|
||||||
|
return this.http.post(AUTH_API + 'refreshtoken', { }, httpOptions);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
package com.jambotronGroup.jambotron.controllers;
|
package com.jambotronGroup.jambotron.controllers;
|
||||||
|
|
||||||
|
|
||||||
|
import com.jambotronGroup.jambotron.exceptions.TokenRefreshException;
|
||||||
import com.jambotronGroup.jambotron.model.ERole;
|
import com.jambotronGroup.jambotron.model.ERole;
|
||||||
|
import com.jambotronGroup.jambotron.model.RefreshToken;
|
||||||
import com.jambotronGroup.jambotron.model.Role;
|
import com.jambotronGroup.jambotron.model.Role;
|
||||||
import com.jambotronGroup.jambotron.model.User;
|
import com.jambotronGroup.jambotron.model.User;
|
||||||
import com.jambotronGroup.jambotron.payload.request.LoginRequest;
|
import com.jambotronGroup.jambotron.payload.request.LoginRequest;
|
||||||
@@ -11,7 +13,9 @@ import com.jambotronGroup.jambotron.payload.response.UserInfoResponse;
|
|||||||
import com.jambotronGroup.jambotron.repository.RoleRepository;
|
import com.jambotronGroup.jambotron.repository.RoleRepository;
|
||||||
import com.jambotronGroup.jambotron.repository.UserRepository;
|
import com.jambotronGroup.jambotron.repository.UserRepository;
|
||||||
import com.jambotronGroup.jambotron.security.jwt.JwtUtils;
|
import com.jambotronGroup.jambotron.security.jwt.JwtUtils;
|
||||||
|
import com.jambotronGroup.jambotron.security.services.RefreshTokenService;
|
||||||
import com.jambotronGroup.jambotron.security.services.UserDetailsImpl;
|
import com.jambotronGroup.jambotron.security.services.UserDetailsImpl;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import jakarta.validation.Valid;
|
import jakarta.validation.Valid;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
@@ -37,7 +41,7 @@ import java.util.stream.Collectors;
|
|||||||
@RequestMapping("/api/auth")
|
@RequestMapping("/api/auth")
|
||||||
public class AuthController {
|
public class AuthController {
|
||||||
|
|
||||||
private static final Logger logger = LoggerFactory.getLogger(AuthController.class);
|
private static final Logger _logger = LoggerFactory.getLogger(AuthController.class);
|
||||||
@Autowired
|
@Autowired
|
||||||
AuthenticationManager authenticationManager;
|
AuthenticationManager authenticationManager;
|
||||||
|
|
||||||
@@ -50,6 +54,9 @@ public class AuthController {
|
|||||||
@Autowired
|
@Autowired
|
||||||
PasswordEncoder encoder;
|
PasswordEncoder encoder;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
RefreshTokenService refreshTokenService;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
JwtUtils jwtUtils;
|
JwtUtils jwtUtils;
|
||||||
|
|
||||||
@@ -69,9 +76,16 @@ public class AuthController {
|
|||||||
.map(item -> item.getAuthority())
|
.map(item -> item.getAuthority())
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
logger.info("User {} authenticated successfully with roles: {}", userDetails.getUsername(), roles);
|
RefreshToken refreshToken = refreshTokenService.createRefreshToken(userDetails.getId());
|
||||||
|
|
||||||
return ResponseEntity.ok().header(HttpHeaders.SET_COOKIE, jwtCookie.toString())
|
ResponseCookie jwtRefreshCookie = jwtUtils.generateRefreshJwtCookie(refreshToken.getToken());
|
||||||
|
|
||||||
|
|
||||||
|
_logger.info("User {} authenticated successfully with roles: {}", userDetails.getUsername(), roles);
|
||||||
|
|
||||||
|
return ResponseEntity.ok()
|
||||||
|
.header(HttpHeaders.SET_COOKIE, jwtCookie.toString())
|
||||||
|
.header(HttpHeaders.SET_COOKIE, jwtRefreshCookie.toString())
|
||||||
.body(new UserInfoResponse(
|
.body(new UserInfoResponse(
|
||||||
userDetails.getId(),
|
userDetails.getId(),
|
||||||
userDetails.getUsername(),
|
userDetails.getUsername(),
|
||||||
@@ -134,8 +148,42 @@ public class AuthController {
|
|||||||
|
|
||||||
@PostMapping("/signout")
|
@PostMapping("/signout")
|
||||||
public ResponseEntity<?> logoutUser() {
|
public ResponseEntity<?> logoutUser() {
|
||||||
|
Object principle = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
||||||
|
if (principle.toString() != "anonymousUser") {
|
||||||
|
Long userId = ((UserDetailsImpl) principle).getId();
|
||||||
|
refreshTokenService.deleteByUserId(userId);
|
||||||
|
}
|
||||||
|
|
||||||
ResponseCookie cookie = jwtUtils.getCleanJwtCookie();
|
ResponseCookie cookie = jwtUtils.getCleanJwtCookie();
|
||||||
return ResponseEntity.ok().header(HttpHeaders.SET_COOKIE, cookie.toString())
|
ResponseCookie jwtRefreshCookie = jwtUtils.getCleanJwtRefreshCookie();
|
||||||
|
|
||||||
|
_logger.info("User signed out successfully, cookies cleared.");
|
||||||
|
return ResponseEntity.ok()
|
||||||
|
.header(HttpHeaders.SET_COOKIE, cookie.toString())
|
||||||
|
.header(HttpHeaders.SET_COOKIE, jwtRefreshCookie.toString())
|
||||||
.body(new MessageResponse("You've been signed out!"));
|
.body(new MessageResponse("You've been signed out!"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@PostMapping("/refreshtoken")
|
||||||
|
public ResponseEntity<?> refreshtoken(HttpServletRequest request) {
|
||||||
|
String refreshToken = jwtUtils.getJwtRefreshFromCookies(request);
|
||||||
|
|
||||||
|
if ((refreshToken != null) && (refreshToken.length() > 0)) {
|
||||||
|
return refreshTokenService.findByToken(refreshToken)
|
||||||
|
.map(refreshTokenService::verifyExpiration)
|
||||||
|
.map(RefreshToken::getUser)
|
||||||
|
.map(user -> {
|
||||||
|
ResponseCookie jwtCookie = jwtUtils.generateJwtCookie(user);
|
||||||
|
|
||||||
|
_logger.info("Refresh token for user {} is valid, generating new JWT cookie.", user.getUsername());
|
||||||
|
return ResponseEntity.ok()
|
||||||
|
.header(HttpHeaders.SET_COOKIE, jwtCookie.toString())
|
||||||
|
.body(new MessageResponse("Token is refreshed successfully!"));
|
||||||
|
})
|
||||||
|
.orElseThrow(() -> new TokenRefreshException(refreshToken,
|
||||||
|
"Refresh token is not in database!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
return ResponseEntity.badRequest().body(new MessageResponse("Refresh Token is empty!"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +0,0 @@
|
|||||||
package com.jambotronGroup.jambotron.controllers;
|
|
||||||
|
|
||||||
import org.springframework.stereotype.Controller;
|
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
|
||||||
|
|
||||||
/*@Controller
|
|
||||||
public class RedirectController {
|
|
||||||
@RequestMapping(value = "/{path:[^\\.]*}")
|
|
||||||
public String redirect() {
|
|
||||||
return "forward:/index.html";
|
|
||||||
}
|
|
||||||
}*/
|
|
||||||
@@ -10,6 +10,8 @@ import com.jambotronGroup.jambotron.repository.UserRepository;
|
|||||||
import com.jambotronGroup.jambotron.security.AuthenticationFacade;
|
import com.jambotronGroup.jambotron.security.AuthenticationFacade;
|
||||||
import com.jambotronGroup.jambotron.security.services.UserDetailsImpl;
|
import com.jambotronGroup.jambotron.security.services.UserDetailsImpl;
|
||||||
import com.jambotronGroup.jambotron.utils.FilesRoutingHelper;
|
import com.jambotronGroup.jambotron.utils.FilesRoutingHelper;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
@@ -30,6 +32,8 @@ import java.util.*;
|
|||||||
@RequestMapping("/api")
|
@RequestMapping("/api")
|
||||||
public class TutorialController {
|
public class TutorialController {
|
||||||
|
|
||||||
|
private static final Logger _logger = LoggerFactory.getLogger(AuthController.class);
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
AuthenticationFacade authenticationFacade;
|
AuthenticationFacade authenticationFacade;
|
||||||
@Autowired
|
@Autowired
|
||||||
@@ -112,7 +116,7 @@ public class TutorialController {
|
|||||||
User user = authenticationFacade.getUser();
|
User user = authenticationFacade.getUser();
|
||||||
|
|
||||||
|
|
||||||
String newFilename = FilesStorageServiceImpl.getFileNameFromUrl(tutorial.getTitleimage());
|
String newFilename = filesStorageService.getFileNameFromUrl(tutorial.getTitleimage());
|
||||||
Path path= filesStorageService.moveFile(
|
Path path= filesStorageService.moveFile(
|
||||||
user.getId().toString(),
|
user.getId().toString(),
|
||||||
tutorial.getTitleimage(),
|
tutorial.getTitleimage(),
|
||||||
@@ -121,7 +125,6 @@ public class TutorialController {
|
|||||||
|
|
||||||
String url = FilesRoutingHelper.getPublicImageUrl(path.getFileName().toString());
|
String url = FilesRoutingHelper.getPublicImageUrl(path.getFileName().toString());
|
||||||
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
Tutorial newTutorial =new Tutorial(
|
Tutorial newTutorial =new Tutorial(
|
||||||
tutorial.getTitle(),
|
tutorial.getTitle(),
|
||||||
@@ -137,8 +140,10 @@ public class TutorialController {
|
|||||||
|
|
||||||
Tutorial _tutorial = tutorialRepository
|
Tutorial _tutorial = tutorialRepository
|
||||||
.save(newTutorial);
|
.save(newTutorial);
|
||||||
|
_logger.info("Tutorial created: " + _tutorial.getId() + " by user: " + user.getId());
|
||||||
return new ResponseEntity<>(_tutorial, HttpStatus.CREATED);
|
return new ResponseEntity<>(_tutorial, HttpStatus.CREATED);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
|
_logger.error("Error creating tutorial: ", e.getMessage());
|
||||||
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -164,8 +169,6 @@ public class TutorialController {
|
|||||||
|
|
||||||
User user = authenticationFacade.getUser();
|
User user = authenticationFacade.getUser();
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Optional<Tutorial> tutorialData = tutorialRepository.findById(id);
|
Optional<Tutorial> tutorialData = tutorialRepository.findById(id);
|
||||||
Map<String, Object> map = new LinkedHashMap<String, Object>();
|
Map<String, Object> map = new LinkedHashMap<String, Object>();
|
||||||
if (tutorialData.isPresent()) {
|
if (tutorialData.isPresent()) {
|
||||||
@@ -177,8 +180,8 @@ public class TutorialController {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
|
|
||||||
String imageFileName = FilesStorageServiceImpl.getFileNameFromUrl(tutorial.getTitleimage());
|
String imageFileName = filesStorageService.getFileNameFromUrl(tutorial.getTitleimage());
|
||||||
String servImageFileName = FilesStorageServiceImpl.getFileNameFromUrl(servTutorial.getTitleimage());
|
String servImageFileName = filesStorageService.getFileNameFromUrl(servTutorial.getTitleimage());
|
||||||
|
|
||||||
if(!servImageFileName.equals(imageFileName)){
|
if(!servImageFileName.equals(imageFileName)){
|
||||||
filesStorageService.deletePublicFile(servImageFileName);
|
filesStorageService.deletePublicFile(servImageFileName);
|
||||||
@@ -197,10 +200,13 @@ public class TutorialController {
|
|||||||
|
|
||||||
map.put("status", 0);
|
map.put("status", 0);
|
||||||
map.put("message", e.getMessage());
|
map.put("message", e.getMessage());
|
||||||
|
_logger.error("Error updating tutorial: ", e.getMessage());
|
||||||
return new ResponseEntity<>(map,HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(map,HttpStatus.INTERNAL_SERVER_ERROR);
|
||||||
}
|
}
|
||||||
|
_logger.info("Tutorial updated: " + servTutorial.getId() + " by user: " + user.getId());
|
||||||
return new ResponseEntity<>(servTutorial, HttpStatus.OK);
|
return new ResponseEntity<>(servTutorial, HttpStatus.OK);
|
||||||
} else {
|
} else {
|
||||||
|
_logger.error("Tutorial with id: " + id + " not found for user: " + user.getId());
|
||||||
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -209,8 +215,10 @@ public class TutorialController {
|
|||||||
public ResponseEntity<HttpStatus> deleteTutorial(@PathVariable("id") long id) {
|
public ResponseEntity<HttpStatus> deleteTutorial(@PathVariable("id") long id) {
|
||||||
try {
|
try {
|
||||||
tutorialRepository.deleteById(id);
|
tutorialRepository.deleteById(id);
|
||||||
|
_logger.info("Tutorial deleted: " + id + " by user: " + authenticationFacade.getUserDetails().getId());
|
||||||
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
|
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
|
_logger.error("Error deleting tutorial: ", e.getMessage());
|
||||||
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package com.jambotronGroup.jambotron.exceptionHandlers;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
public class ErrorMessage {
|
||||||
|
private int statusCode;
|
||||||
|
private Date timestamp;
|
||||||
|
private String message;
|
||||||
|
private String description;
|
||||||
|
|
||||||
|
public ErrorMessage(int statusCode, Date timestamp, String message, String description) {
|
||||||
|
this.statusCode = statusCode;
|
||||||
|
this.timestamp = timestamp;
|
||||||
|
this.message = message;
|
||||||
|
this.description = description;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getStatusCode() {
|
||||||
|
return statusCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Date getTimestamp() {
|
||||||
|
return timestamp;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getMessage() {
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDescription() {
|
||||||
|
return description;
|
||||||
|
}
|
||||||
|
}
|
||||||
+14
-8
@@ -1,6 +1,9 @@
|
|||||||
package com.jambotronGroup.jambotron.exceptionHandlers;
|
package com.jambotronGroup.jambotron.exceptionHandlers;
|
||||||
|
|
||||||
|
import com.jambotronGroup.jambotron.controllers.AuthController;
|
||||||
import com.jambotronGroup.jambotron.fileUpload.ResponseMessage;
|
import com.jambotronGroup.jambotron.fileUpload.ResponseMessage;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||||
@@ -8,11 +11,14 @@ import org.springframework.web.bind.annotation.ExceptionHandler;
|
|||||||
import org.springframework.web.multipart.MaxUploadSizeExceededException;
|
import org.springframework.web.multipart.MaxUploadSizeExceededException;
|
||||||
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
|
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
|
||||||
|
|
||||||
//@ControllerAdvice
|
/*
|
||||||
//public class FileUploadExceptionHandler extends ResponseEntityExceptionHandler {
|
@ControllerAdvice
|
||||||
//
|
public class FileUploadExceptionHandler extends ResponseEntityExceptionHandler {
|
||||||
// @ExceptionHandler(MaxUploadSizeExceededException.class)
|
|
||||||
// public ResponseEntity<ResponseMessage> handleMaxSizeException(MaxUploadSizeExceededException exc) {
|
private static final Logger _logger = LoggerFactory.getLogger(AuthController.class);
|
||||||
// return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage("File too large!"));
|
@ExceptionHandler(MaxUploadSizeExceededException.class)
|
||||||
// }
|
public ResponseEntity<ResponseMessage> handleMaxSizeException(MaxUploadSizeExceededException exc) {
|
||||||
//}
|
_logger.error("File upload size exceeded: {}", exc.getMessage());
|
||||||
|
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage("File too large!"));
|
||||||
|
}
|
||||||
|
}*/
|
||||||
|
|||||||
+25
@@ -0,0 +1,25 @@
|
|||||||
|
package com.jambotronGroup.jambotron.exceptionHandlers;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
import com.jambotronGroup.jambotron.exceptions.TokenRefreshException;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||||
|
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||||
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||||
|
import org.springframework.web.context.request.WebRequest;
|
||||||
|
|
||||||
|
|
||||||
|
@RestControllerAdvice
|
||||||
|
public class TokenControllerAdvice {
|
||||||
|
|
||||||
|
@ExceptionHandler(value = TokenRefreshException.class)
|
||||||
|
@ResponseStatus(HttpStatus.FORBIDDEN)
|
||||||
|
public ErrorMessage handleTokenRefreshException(TokenRefreshException ex, WebRequest request) {
|
||||||
|
return new ErrorMessage(
|
||||||
|
HttpStatus.FORBIDDEN.value(),
|
||||||
|
new Date(),
|
||||||
|
ex.getMessage(),
|
||||||
|
request.getDescription(false));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package com.jambotronGroup.jambotron.exceptions;
|
||||||
|
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||||
|
|
||||||
|
@ResponseStatus(HttpStatus.FORBIDDEN)
|
||||||
|
public class TokenRefreshException extends RuntimeException {
|
||||||
|
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
public TokenRefreshException(String token, String message) {
|
||||||
|
super(String.format("Failed for [%s]: %s", token, message));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
package com.jambotronGroup.jambotron.fileUpload;
|
|
||||||
|
|
||||||
|
|
||||||
import org.springframework.http.HttpStatus;
|
|
||||||
import org.springframework.http.ResponseEntity;
|
|
||||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
|
||||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
|
||||||
import org.springframework.web.multipart.MaxUploadSizeExceededException;
|
|
||||||
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
|
|
||||||
|
|
||||||
@ControllerAdvice
|
|
||||||
public class FileUploadExceptionAdvice extends ResponseEntityExceptionHandler {
|
|
||||||
|
|
||||||
|
|
||||||
// @ExceptionHandler(MaxUploadSizeExceededException.class)
|
|
||||||
// public ResponseEntity<ResponseMessage> handleMaxSizeException(MaxUploadSizeExceededException exc) {
|
|
||||||
// return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage("File too large!"));
|
|
||||||
// }
|
|
||||||
}
|
|
||||||
@@ -10,6 +10,8 @@ import java.util.stream.Stream;
|
|||||||
public interface FilesStorageService {
|
public interface FilesStorageService {
|
||||||
public void init();
|
public void init();
|
||||||
|
|
||||||
|
public String getFileNameFromUrl(String urlString);
|
||||||
|
|
||||||
public String save(String userID,MultipartFile file);
|
public String save(String userID,MultipartFile file);
|
||||||
|
|
||||||
public void save(MultipartFile file);
|
public void save(MultipartFile file);
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
package com.jambotronGroup.jambotron.fileUpload;
|
package com.jambotronGroup.jambotron.fileUpload;
|
||||||
|
|
||||||
|
|
||||||
|
import com.jambotronGroup.jambotron.controllers.AuthController;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.core.io.Resource;
|
import org.springframework.core.io.Resource;
|
||||||
import org.springframework.core.io.UrlResource;
|
import org.springframework.core.io.UrlResource;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
@@ -19,9 +22,8 @@ import java.util.stream.Stream;
|
|||||||
@Service
|
@Service
|
||||||
public class FilesStorageServiceImpl implements FilesStorageService {
|
public class FilesStorageServiceImpl implements FilesStorageService {
|
||||||
|
|
||||||
// private final Path root = Paths.get("uploads/user-images/");
|
private static final Logger _logger = LoggerFactory.getLogger(AuthController.class);
|
||||||
//
|
|
||||||
// private final Path rootPublic = Paths.get("uploads/public-images/");
|
|
||||||
|
|
||||||
// Update paths to use the Docker volume
|
// Update paths to use the Docker volume
|
||||||
private final Path root = Paths.get("/jambotron_data/uploads/user-images/");
|
private final Path root = Paths.get("/jambotron_data/uploads/user-images/");
|
||||||
@@ -38,10 +40,18 @@ public class FilesStorageServiceImpl implements FilesStorageService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String getFileNameFromUrl(String urlString) throws Exception {
|
@Override
|
||||||
|
public String getFileNameFromUrl(String urlString){
|
||||||
|
try {
|
||||||
|
|
||||||
URL url = new URL(urlString); // Create a URL object
|
URL url = new URL(urlString); // Create a URL object
|
||||||
String path = url.getPath(); // Get the path from the URL
|
String path = url.getPath(); // Get the path from the URL
|
||||||
return path.substring(path.lastIndexOf('/') + 1); // Extract the file name
|
return path.substring(path.lastIndexOf('/') + 1); // Extract the file name
|
||||||
|
|
||||||
|
}catch (MalformedURLException e) {
|
||||||
|
_logger.error("Invalid URL: " + urlString, e);
|
||||||
|
throw new RuntimeException("Invalid URL: " + urlString);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -52,12 +62,11 @@ public class FilesStorageServiceImpl implements FilesStorageService {
|
|||||||
* @param url The URL of the file to move.
|
* @param url The URL of the file to move.
|
||||||
* @param newFilename The new name for the file in the public directory.
|
* @param newFilename The new name for the file in the public directory.
|
||||||
* @return The path to the moved file in the public directory.
|
* @return The path to the moved file in the public directory.
|
||||||
* @throws Exception If the file cannot be moved.
|
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public Path moveFile(String userID, String url, String newFilename) throws Exception {
|
public Path moveFile(String userID, String url, String newFilename) {
|
||||||
|
|
||||||
String filename = FilesStorageServiceImpl.getFileNameFromUrl(url);
|
String filename = this.getFileNameFromUrl(url);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
Path sourcePath = this.root.resolve(userID).resolve(filename);
|
Path sourcePath = this.root.resolve(userID).resolve(filename);
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package com.jambotronGroup.jambotron.model;
|
||||||
|
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
|
||||||
|
@Entity(name = "refreshtoken")
|
||||||
|
public class RefreshToken {
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private long id;
|
||||||
|
|
||||||
|
@OneToOne
|
||||||
|
@JoinColumn(name = "user_id", referencedColumnName = "id")
|
||||||
|
private User user;
|
||||||
|
|
||||||
|
@Column(nullable = false, unique = true)
|
||||||
|
private String token;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private Instant expiryDate;
|
||||||
|
|
||||||
|
public long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(long id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public User getUser() {
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUser(User user) {
|
||||||
|
this.user = user;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getToken() {
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setToken(String token) {
|
||||||
|
this.token = token;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Instant getExpiryDate() {
|
||||||
|
return expiryDate;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setExpiryDate(Instant expiryDate) {
|
||||||
|
this.expiryDate = expiryDate;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package com.jambotronGroup.jambotron.repository;
|
||||||
|
|
||||||
|
import com.jambotronGroup.jambotron.model.RefreshToken;
|
||||||
|
import com.jambotronGroup.jambotron.model.User;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import org.springframework.data.jpa.repository.Modifying;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
public interface RefreshTokenRepository extends JpaRepository<RefreshToken, Long> {
|
||||||
|
Optional<RefreshToken> findByToken(String token);
|
||||||
|
|
||||||
|
@Modifying
|
||||||
|
int deleteByUser(User user);
|
||||||
|
}
|
||||||
|
|
||||||
@@ -2,6 +2,7 @@ package com.jambotronGroup.jambotron.security.jwt;
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
import com.jambotronGroup.jambotron.model.User;
|
||||||
import com.jambotronGroup.jambotron.security.services.UserDetailsImpl;
|
import com.jambotronGroup.jambotron.security.services.UserDetailsImpl;
|
||||||
import io.jsonwebtoken.*;
|
import io.jsonwebtoken.*;
|
||||||
import io.jsonwebtoken.io.Decoders;
|
import io.jsonwebtoken.io.Decoders;
|
||||||
@@ -31,6 +32,9 @@ public class JwtUtils {
|
|||||||
@Value("${app.jwtCookieName}")
|
@Value("${app.jwtCookieName}")
|
||||||
private String jwtCookie;
|
private String jwtCookie;
|
||||||
|
|
||||||
|
@Value("${app.jwtRefreshCookieName}")
|
||||||
|
private String jwtRefreshCookie;
|
||||||
|
|
||||||
public String getJwtFromCookies(HttpServletRequest request) {
|
public String getJwtFromCookies(HttpServletRequest request) {
|
||||||
Cookie cookie = WebUtils.getCookie(request, jwtCookie);
|
Cookie cookie = WebUtils.getCookie(request, jwtCookie);
|
||||||
if (cookie != null) {
|
if (cookie != null) {
|
||||||
@@ -46,6 +50,38 @@ public class JwtUtils {
|
|||||||
return cookie;
|
return cookie;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public ResponseCookie generateRefreshJwtCookie(String refreshToken) {
|
||||||
|
return generateCookie(jwtRefreshCookie, refreshToken, "/api/auth/refreshtoken");
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getJwtRefreshFromCookies(HttpServletRequest request) {
|
||||||
|
return getCookieValueByName(request, jwtRefreshCookie);
|
||||||
|
}
|
||||||
|
|
||||||
|
public ResponseCookie getCleanJwtRefreshCookie() {
|
||||||
|
ResponseCookie cookie = ResponseCookie.from(jwtRefreshCookie, null).path("/api/auth/refreshtoken").build();
|
||||||
|
return cookie;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ResponseCookie generateJwtCookie(User user) {
|
||||||
|
String jwt = generateTokenFromUsername(user.getUsername());
|
||||||
|
return generateCookie(jwtCookie, jwt, "/api");
|
||||||
|
}
|
||||||
|
|
||||||
|
private ResponseCookie generateCookie(String name, String value, String path) {
|
||||||
|
ResponseCookie cookie = ResponseCookie.from(name, value).path(path).maxAge(24 * 60 * 60).httpOnly(true).build();
|
||||||
|
return cookie;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getCookieValueByName(HttpServletRequest request, String name) {
|
||||||
|
Cookie cookie = WebUtils.getCookie(request, name);
|
||||||
|
if (cookie != null) {
|
||||||
|
return cookie.getValue();
|
||||||
|
} else {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public ResponseCookie getCleanJwtCookie() {
|
public ResponseCookie getCleanJwtCookie() {
|
||||||
ResponseCookie cookie = ResponseCookie.from(jwtCookie, null).path("/api").build();
|
ResponseCookie cookie = ResponseCookie.from(jwtCookie, null).path("/api").build();
|
||||||
return cookie;
|
return cookie;
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package com.jambotronGroup.jambotron.security.services;
|
||||||
|
|
||||||
|
import com.jambotronGroup.jambotron.exceptions.TokenRefreshException;
|
||||||
|
import com.jambotronGroup.jambotron.model.RefreshToken;
|
||||||
|
import com.jambotronGroup.jambotron.repository.RefreshTokenRepository;
|
||||||
|
import com.jambotronGroup.jambotron.repository.UserRepository;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class RefreshTokenService {
|
||||||
|
@Value("${app.jwtRefreshExpirationMs}")
|
||||||
|
private Long refreshTokenDurationMs;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private RefreshTokenRepository refreshTokenRepository;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private UserRepository userRepository;
|
||||||
|
|
||||||
|
public Optional<RefreshToken> findByToken(String token) {
|
||||||
|
return refreshTokenRepository.findByToken(token);
|
||||||
|
}
|
||||||
|
|
||||||
|
public RefreshToken createRefreshToken(Long userId) {
|
||||||
|
RefreshToken refreshToken = new RefreshToken();
|
||||||
|
|
||||||
|
refreshToken.setUser(userRepository.findById(userId).get());
|
||||||
|
refreshToken.setExpiryDate(Instant.now().plusMillis(refreshTokenDurationMs));
|
||||||
|
refreshToken.setToken(UUID.randomUUID().toString());
|
||||||
|
|
||||||
|
refreshToken = refreshTokenRepository.save(refreshToken);
|
||||||
|
return refreshToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
public RefreshToken verifyExpiration(RefreshToken token) {
|
||||||
|
if (token.getExpiryDate().compareTo(Instant.now()) < 0) {
|
||||||
|
refreshTokenRepository.delete(token);
|
||||||
|
throw new TokenRefreshException(token.getToken(), "Refresh token was expired. Please make a new signin request");
|
||||||
|
}
|
||||||
|
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public int deleteByUserId(Long userId) {
|
||||||
|
return refreshTokenRepository.deleteByUser(userRepository.findById(userId).get());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,14 +5,14 @@ spring.application.name=jambotron
|
|||||||
server.port=8082
|
server.port=8082
|
||||||
#============Localhost Configurations========================
|
#============Localhost Configurations========================
|
||||||
|
|
||||||
spring.datasource.url= jdbc:postgresql://localhost:5432/jambotronDB
|
spring.datasource.url= jdbc:postgresql://localhost:5433/jambotronDB
|
||||||
spring.datasource.username= admin
|
spring.datasource.username= admin
|
||||||
spring.datasource.password= postgrespw
|
spring.datasource.password= postgrespw
|
||||||
|
|
||||||
spring.flyway.baseline-on-migrate=true
|
spring.flyway.baseline-on-migrate=true
|
||||||
spring.flyway.validate-on-migrate=true
|
spring.flyway.validate-on-migrate=true
|
||||||
|
|
||||||
spring.flyway.url=jdbc:postgresql://localhost:5432/jambotronDB
|
spring.flyway.url=jdbc:postgresql://localhost:5433/jambotronDB
|
||||||
spring.flyway.user=admin
|
spring.flyway.user=admin
|
||||||
spring.flyway.password=postgrespw
|
spring.flyway.password=postgrespw
|
||||||
|
|
||||||
@@ -30,9 +30,14 @@ spring.ai.zhipuai.api-key = 628447c8c65845a48a7226391464a2ea.Dw8ci6TiW0BRF5LI
|
|||||||
|
|
||||||
|
|
||||||
#============ Custom App Properties
|
#============ Custom App Properties
|
||||||
app.jwtSecret= ======================spring=back====================
|
app.jwtSecret= ======================jambotron=back=================
|
||||||
app.jwtExpirationMs= 800000
|
app.jwtCookieName=jambotron-jwt-cookie
|
||||||
app.jwtCookieName=springangularts
|
app.jwtRefreshCookieName= jambotron-jwt-cookie-refresh
|
||||||
|
#app.jwtExpirationMs= 800000
|
||||||
|
#app.jwtRefreshExpirationMs= 86400000
|
||||||
|
|
||||||
|
app.jwtExpirationMs= 30000
|
||||||
|
app.jwtRefreshExpirationMs= 60000
|
||||||
|
|
||||||
#=============File Upload Configurations========================
|
#=============File Upload Configurations========================
|
||||||
spring.servlet.multipart.max-file-size=50MB
|
spring.servlet.multipart.max-file-size=50MB
|
||||||
|
|||||||
Reference in New Issue
Block a user