de.sainth.recipe.backend.rest.controller.CookbookController.java Source code

Java tutorial

Introduction

Here is the source code for de.sainth.recipe.backend.rest.controller.CookbookController.java

Source

/*
 * Copyright (c) 2017 sainth (sainth@sainth.de)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 */

package de.sainth.recipe.backend.rest.controller;

import de.sainth.recipe.backend.db.repositories.CookbookRepository;
import de.sainth.recipe.backend.rest.views.Cookbook;
import de.sainth.recipe.backend.security.RecipeManagerAuthenticationToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

import static de.sainth.recipe.backend.rest.views.User.Permission.ROLE_ADMIN;

@RestController
@RequestMapping("/cookbooks")
public class CookbookController {

    @Autowired
    CookbookRepository repository;

    @Secured({ "ROLE_USER", "ROLE_ADMIN" })
    @RequestMapping()
    HttpEntity<List<Cookbook>> getAll() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof RecipeManagerAuthenticationToken) {
            RecipeManagerAuthenticationToken token = (RecipeManagerAuthenticationToken) authentication;
            if (ROLE_ADMIN.name().equals(token.getRole())) {
                return new ResponseEntity<>(repository.findAll(), HttpStatus.OK);
            } else {
                return new ResponseEntity<>(repository.findAllFor(token.getPrincipal()), HttpStatus.OK);
            }
        }
        return new ResponseEntity<>(HttpStatus.FORBIDDEN);
    }

    @Secured({ "ROLE_USER", "ROLE_ADMIN" })
    @RequestMapping("{id}")
    HttpEntity<Cookbook> get(@PathVariable("id") Long id) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof RecipeManagerAuthenticationToken) {
            RecipeManagerAuthenticationToken token = (RecipeManagerAuthenticationToken) authentication;
            Cookbook cookbook = repository.findOne(id);
            if (cookbook == null) {
                return new ResponseEntity<>(HttpStatus.NO_CONTENT);
            }
            if (ROLE_ADMIN.name().equals(token.getRole())
                    || token.getPrincipal().equals(cookbook.getAuthor().getId())) {
                return new ResponseEntity<>(cookbook, HttpStatus.OK);
            }
        }
        return new ResponseEntity<>(HttpStatus.FORBIDDEN);
    }

    @Secured({ "ROLE_USER", "ROLE_ADMIN" })
    @RequestMapping(value = "{id}", method = RequestMethod.DELETE)
    @ResponseStatus(HttpStatus.NO_CONTENT)
    void delete(@PathVariable("id") Long id) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof RecipeManagerAuthenticationToken) {
            RecipeManagerAuthenticationToken token = (RecipeManagerAuthenticationToken) authentication;
            if (ROLE_ADMIN.name().equals(token.getRole())) {
                repository.delete(id);
            } else {
                repository.delete(id, token.getPrincipal());
            }
        }
    }

    @Secured({ "ROLE_USER", "ROLE_ADMIN" })
    @RequestMapping(method = RequestMethod.POST)
    HttpEntity<Cookbook> add(@Valid @RequestBody Cookbook cookbook) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof RecipeManagerAuthenticationToken) {
            RecipeManagerAuthenticationToken token = (RecipeManagerAuthenticationToken) authentication;
            if (ROLE_ADMIN.name().equals(token.getRole())
                    || token.getPrincipal().equals(cookbook.getAuthor().getId())) {
                Cookbook c = repository.save(cookbook);
                return new ResponseEntity<>(c, HttpStatus.CREATED);
            } else {
                return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
            }
        }
        return new ResponseEntity<>(HttpStatus.FORBIDDEN);
    }

    @Secured({ "ROLE_USER", "ROLE_ADMIN" })
    @RequestMapping(value = "{id}", method = RequestMethod.PUT)
    HttpEntity<Cookbook> update(@PathVariable("id") Long id, @Valid @RequestBody Cookbook cookbook) {
        if (id.equals(cookbook.getId())) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication instanceof RecipeManagerAuthenticationToken) {
                RecipeManagerAuthenticationToken token = (RecipeManagerAuthenticationToken) authentication;
                Cookbook existingCookbook = repository.findOne(cookbook.getId());
                if (existingCookbook != null) {
                    if (ROLE_ADMIN.name().equals(token.getRole())
                            || existingCookbook.getAuthor().getId().equals(authentication.getPrincipal())) {
                        repository.save(cookbook);
                        return new ResponseEntity<>(cookbook, HttpStatus.OK);
                    } else {
                        return new ResponseEntity<>(HttpStatus.FORBIDDEN);
                    }
                }
            }
        }
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }

}