using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using DevHive.Web.Models.Role; using AutoMapper; using System; using DevHive.Services.Interfaces; using DevHive.Services.Models.Role; using Microsoft.AspNetCore.Authorization; namespace DevHive.Web.Controllers { /// /// All endpoints for interacting with the roles layer /// [ApiController] [Route("/api/[controller]")] public class RoleController { private readonly IRoleService _roleService; private readonly IMapper _roleMapper; public RoleController(IRoleService roleService, IMapper mapper) { this._roleService = roleService; this._roleMapper = mapper; } /// /// Create a new role for the roles hierarchy. Admin only! /// /// The new role's parametars /// The new role's Id [HttpPost] [Authorize(Roles = "Admin")] public async Task Create([FromBody] CreateRoleWebModel createRoleWebModel) { CreateRoleServiceModel roleServiceModel = this._roleMapper.Map(createRoleWebModel); Guid id = await this._roleService.CreateRole(roleServiceModel); return id == Guid.Empty ? new BadRequestObjectResult($"Could not create role {createRoleWebModel.Name}") : new OkObjectResult(new { Id = id }); } /// /// Get a role's full data, querying it by it's Id /// /// The role's Id /// Full info of the role [HttpGet] [Authorize(Roles = "User,Admin")] public async Task GetById(Guid id) { RoleServiceModel roleServiceModel = await this._roleService.GetRoleById(id); RoleWebModel roleWebModel = this._roleMapper.Map(roleServiceModel); return new OkObjectResult(roleWebModel); } /// /// Update a role's parametars. Admin only! /// /// The role's Id /// The new parametrats for that role /// Ok result [HttpPut] [Authorize(Roles = "Admin")] public async Task Update(Guid id, [FromBody] UpdateRoleWebModel updateRoleWebModel) { UpdateRoleServiceModel updateRoleServiceModel = this._roleMapper.Map(updateRoleWebModel); updateRoleServiceModel.Id = id; bool result = await this._roleService.UpdateRole(updateRoleServiceModel); if (!result) return new BadRequestObjectResult("Could not update role!"); return new OkResult(); } /// /// Delete a role. Admin only! /// /// The role's Id /// Ok result [HttpDelete] [Authorize(Roles = "Admin")] public async Task Delete(Guid id) { bool result = await this._roleService.DeleteRole(id); if (!result) return new BadRequestObjectResult("Could not delete role!"); return new OkResult(); } } }