Witam wszystkich, mam serwis restowy w którym dodaje oferty pracy. Do serwisu dodałem opcję autoryzacji po jwt @PreAuthorize 3 role admin, user, moderator wszystko sprawdzane jest w kontrolerze JobController. Zaczyna się problem gdy chcę usunąć ofertę pracy jako administrator nie wiem jak wyciągnąć usera do którego należy oferta pracy. Usera z ofertą pracy mam złączoną relacją jeden-do-wielu z tabelą złączenia. Nie mam pojęcia czy takie podejście jest poprawne zależy mi aby oferty pracy były jak najmniej zależne od konta usera. Na dole dodałem też metody z post i delete z kontrolera nie wiem czy dobrze implementuje wykrywanie usera, chciałbym żeby to wszystko było jak najbardziej bez stanowe.
Klasa User
public class User {
//inne metody
@OneToMany(fetch = FetchType.LAZY)
@JoinTable(name = "USER_JOBS",
joinColumns = @JoinColumn(name = "USER_ID"),
inverseJoinColumns = @JoinColumn(name = "JOB_ID"))
private List<Job> jobs;
}
@Entity
@Getter
@Setter
@EqualsAndHashCode(of = "id")
@Table(name = "JOB")
public class Job {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private Long id;
@Column(name = "TITLE")
private String title;
@Enumerated(EnumType.STRING)
@Column(name = "CATEGORY")
private Category category;
@Column(name = "COMPANY")
private String company;
@Column(name = "CITY")
private String city;
@OneToOne(mappedBy = "job", cascade=CascadeType.ALL,
fetch = FetchType.LAZY, optional = false)
private JobDetails jobDetails;
public Job() {
}
public Job(String title, Category category, String company, String city) {
this.title = title;
this.category = category;
this.company = company;
this.city = city;
}
metody kontrolera
@PostMapping("/jobs")
@PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')")
public ResponseEntity<Job> createJobs(@RequestBody JobPostDto postDto) {
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication()
.getPrincipal();
Optional<User> userByName = userService.findUserByName(userDetails.getUsername());
try {
Job newJob = jobOfferService.saveJobOffer(postDto);
userService.addJobToUser(userByName.get(), newJob);
return ResponseEntity
.created(new URI("/jobs/" + newJob.getId()))
.body(newJob);
} catch(URISyntaxException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
@DeleteMapping("/jobs/{id}")
@PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')")
public ResponseEntity<?> deleteJob(@PathVariable Long id) {
Optional<Job> existingJob = jobOfferService.getJobOfferById(id);
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication()
.getPrincipal();
Optional<User> userByName = userService.findUserByName(userDetails.getUsername());
return existingJob.map(job -> {
if(!userDetails.getAuthorities().contains(RoleType.ROLE_ADMIN)) {
if(userService.existJobByUser(userDetails.getUsername(), job)) {
userByName.get().getJobs().remove(existingJob.get());
jobOfferService.deleteJob(job.getId());
return ResponseEntity.ok().build();
} else {
return new ResponseEntity<>("Unauthorized", HttpStatus.UNAUTHORIZED);
}
}else {
userByName.get().getJobs().remove(existingJob.get()); // tego nie wiem
jobOfferService.deleteJob(job.getId()); / //
return ResponseEntity.ok().build();
}
}).orElse(ResponseEntity.notFound().build());
}