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

Java tutorial

Introduction

Here is the source code for de.sainth.recipe.backend.rest.controller.RecipeController.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.RecipeRepository;
import de.sainth.recipe.backend.rest.views.Recipe;
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("/recipes")
public class RecipeController {

    @Autowired
    RecipeRepository repository;

    @Secured({ "ROLE_USER", "ROLE_ADMIN" })
    @RequestMapping()
    HttpEntity<List<Recipe>> 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<Recipe> get(@PathVariable("id") Long id) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof RecipeManagerAuthenticationToken) {
            RecipeManagerAuthenticationToken token = (RecipeManagerAuthenticationToken) authentication;
            Recipe recipe = repository.findOne(id);
            if (recipe == null) {
                return new ResponseEntity<>(HttpStatus.NO_CONTENT);
            } else if (recipe.isPublicVisible() || ROLE_ADMIN.name().equals(token.getRole())
                    || token.getPrincipal().equals(recipe.getAuthor().getId())) {
                return new ResponseEntity<>(recipe, 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<Recipe> add(@Valid @RequestBody Recipe recipe) {
        Recipe r = repository.save(recipe);
        return new ResponseEntity<>(r, HttpStatus.CREATED);
    }

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

}