AuthorizationController.java

/**
 * TFG 75.678 - TFG Desarrollo web 2020 e-Learning for Schools
 * Copyright (C) 2020  Eduardo Rodriguez Carro
 *
 * 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, see <http://www.gnu.org/licenses/>.
 */

package org.uoc.tfg.sel.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.uoc.tfg.sel.repository.model.Authorization;
import org.uoc.tfg.sel.repository.model.User;
import org.uoc.tfg.sel.service.AuthorizationService;
import org.uoc.tfg.sel.service.UserService;
import org.uoc.tfg.sel.validation.ValidationException;
import org.uoc.tfg.sel.validation.ValidatorUtils;
import org.uoc.tfg.sel.web.model.AuthorizationConfirm;
import org.uoc.tfg.sel.web.model.AuthorizationRequest;
import org.uoc.tfg.sel.web.model.ErrorCodes;

/**
 * The Class AuthorizationController.
 * @author Eduardo Rodriguez Carro
 */
@RestController
@CrossOrigin
@RequestMapping("/authorization")
public class AuthorizationController {

	/** The user service. */
	@Autowired
	private UserService userService;

	/** The authorization service. */
	@Autowired
	private AuthorizationService authorizationService;

	/**
	 * New authorization.
	 *
	 * @param request the request
	 * @param authentication the authentication
	 * @return the response entity
	 */
	@PreAuthorize("hasRole('ROLE_API_AUTHORIZATION_EDIT')")
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public ResponseEntity<Void> newAuthorization ( @RequestBody AuthorizationRequest request,Authentication authentication){
		List<User> users = null;
		
		ValidatorUtils.assertIsNonNull("request", request);
		ValidatorUtils.assertIsNonNull("content", request.getContent());
		
		// Validation entry data
		if (request.getStudentId() != null ) {
			User user = userService.getUserById(request.getStudentId());
			ValidatorUtils.assertIsNonNull("student", user);
			users = new ArrayList<>();
			users.add(user);
		} else if (request.getClassId() != null) {
			users = userService.getStudentsByClass(request.getClassId());
			ValidatorUtils.assertIsNonNull("student", users);
			if ( users.isEmpty()) {
				ValidationException.throwIt(ErrorCodes.VALIDATION_NOSTUDENTS, "No students");
			}
		} else if (request.getCourseId() != null) {
			users = userService.getStudentsByCourse(request.getCourseId());
			ValidatorUtils.assertIsNonNull("student", users);
			if ( users.isEmpty()) {
				ValidationException.throwIt(ErrorCodes.VALIDATION_NOSTUDENTS, "No students");
			}
		}else {
			ValidationException.throwIt(ErrorCodes.VALIDATION_NOSTUDENTS, "No student,class or course");
		}
		
		User teacher = ControllerUtils.getUser(authentication);
		ValidatorUtils.assertIsNonNull("teacher", request);
		
		List<Authorization> authorizations = new ArrayList<>();
		for ( User user: users) {
			Authorization auth = new Authorization();
			auth.setDate(new Date());
			auth.setStatus(0);
			auth.setStudent(user);
			auth.setPorpouse(request.getContent());
			auth.setTeacherTutor(teacher);
			authorizations.add(auth);
		}
		
		authorizationService.save(authorizations);
		return ResponseEntity.ok().build();
	}
	
	/**
	 * New authorization.
	 *
	 * @param request the request
	 * @param authentication the authentication
	 * @return the response entity
	 */
	@PreAuthorize("hasRole('ROLE_API_CONFIRM_AUTHORIZATION')")
	@RequestMapping(value = "/confirm", method = RequestMethod.POST)
	public ResponseEntity<Void> confirmAuthorization ( @RequestBody AuthorizationConfirm request){
		authorizationService.confirm(request.getId(),request.getResponse(), request.getNotes());
		return ResponseEntity.ok().build();
	}
	
	
	/**
	 * Delete.
	 *
	 * @param id the id
	 * @return the response entity
	 * @throws Exception the exception
	 */
	@PreAuthorize("hasRole('ROLE_API_AUTHORIZATION_DELETE')")
	@RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
	public ResponseEntity<Void> delete(@PathVariable("id") Integer id,Authentication authentication) throws Exception {
		User user = ControllerUtils.getUser(authentication);
		authorizationService.delete(id,user);
		return ResponseEntity.ok().build();
	}	
	
	
	/**
	 * Listado de usuarios por tipo.
	 *
	 * @return the all
	 * @throws Exception the exception
	 */
	@PreAuthorize("hasRole('ROLE_API_AUTHORIZATION')")
	@RequestMapping(value = "/all", method = RequestMethod.GET)
	public ResponseEntity<List<Authorization>> getAll(Authentication authentication) throws Exception {
		User user = ControllerUtils.getUser(authentication);
		return ResponseEntity.ok(authorizationService.getByUser(user));
	}

}