BaseController.java 2.83 KB
package etunicorn.controller;

import etunicorn.entity.Permission;
import etunicorn.entity.Session;
import etunicorn.repository.PermissionRepository;
import etunicorn.service.SessionService;
import net.minidev.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;

/**
 * etunicorn-server
 * Copyright © 2017 Le Club Info Polytech Lille
 * Tous droits réservés
 */
@RestController
public class BaseController {

    // Permettent la vérification de permissions dans les méthodes de controlleur
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SessionService sessionService;
    @Autowired
    private PermissionRepository permissionRepository;

    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    protected boolean hasPermission(Permission permission) {
        Session session = sessionService.getSession(request);
        if (session == null || permission == null) {
            return false;
        }
        return session.hasPermission(permission);
    }

    protected boolean hasPermission(String nomPermission) {
        Permission permission = permissionRepository.findByNom(nomPermission);
        return hasPermission(permission);
    }

    // Utilités pour générer des erreurs
    private JSONObject generateErrorJSON(HttpStatus status, String message) {
        JSONObject json = new JSONObject();
        json.put("timestamp", new Date().getTime());
        json.put("status", status.value());
        json.put("message", message);
        json.put("path", request.getPathInfo());
        return json;

    }

    public ResponseEntity generateError(HttpStatus status, String message) {
        JSONObject json = generateErrorJSON(status, message);
        return new ResponseEntity(json, status);
    }

    public ResponseEntity generateError(HttpStatus status, Exception exception, String message) {
        JSONObject json = generateErrorJSON(status, message);
        json.put("error", exception.getMessage());
        // From http://stackoverflow.com/a/1149721
        StringWriter sw = new StringWriter();
        exception.printStackTrace(new PrintWriter(sw));
        json.put("stacktrace", sw.toString());
        return new ResponseEntity(json, status);
    }

    public ResponseEntity generateError(HttpStatus status) {
        return generateError(status, status.getReasonPhrase());
    }

    public ResponseEntity generateError(Exception exception) {
        return generateError(HttpStatus.INTERNAL_SERVER_ERROR, exception, exception.getLocalizedMessage());
    }
}