1
0
forked from PGL/Clyde
Clyde/backend/src/main/java/ovh/herisson/Clyde/EndPoints/NotificationController.java
2024-04-21 20:15:47 +02:00

62 lines
2.1 KiB
Java

package ovh.herisson.Clyde.EndPoints;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import lombok.AllArgsConstructor;
import ovh.herisson.Clyde.Repositories.NotificationRepository;
import ovh.herisson.Clyde.Responses.UnauthorizedResponse;
import ovh.herisson.Clyde.Services.AuthenticatorService;
import ovh.herisson.Clyde.Tables.Notification;
import ovh.herisson.Clyde.Tables.User;
import ovh.herisson.Clyde.Tables.Notification.Status;
@RestController
@AllArgsConstructor
@CrossOrigin(originPatterns = "*", allowCredentials = "true")
public class NotificationController {
private AuthenticatorService authServ;
private NotificationRepository notifRepo;
@GetMapping("/notifications")
public ResponseEntity<List<Notification>> getNotifications(@RequestHeader("Authorization") String token){
User u = authServ.getUserFromToken(token);
if(u == null){
return new UnauthorizedResponse<>(null);
}
ArrayList<Notification> ret = new ArrayList<>();
for (Notification n : u.getNotifications()) {
if(!n.getStatus().equals(Status.Archived)){
ret.add(n);
}
}
return new ResponseEntity<>(ret, HttpStatus.OK);
}
@PostMapping("/notifications/{id}")
public ResponseEntity<Notification> archiveNotification(@RequestHeader("Authorization") String token, @PathVariable long id){
User u = authServ.getUserFromToken(token);
Notification n = notifRepo.findById(id).orElse(null);
if(u == null || n.getUser() != u){
return new UnauthorizedResponse<>(null);
}
n.setStatus(Status.Archived);
notifRepo.save(n);
return new ResponseEntity<>(HttpStatus.OK);
}
}