104 lines
3.0 KiB
C#
104 lines
3.0 KiB
C#
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Identity;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using survey_beta.DTOs.Create;
|
|
using survey_beta.DTOs.Response;
|
|
using survey_beta.DTOs.Update;
|
|
using survey_beta.Models;
|
|
using System.Linq;
|
|
using System.Security.Claims;
|
|
using System.Threading.Tasks;
|
|
|
|
[Route("api/[controller]")]
|
|
[ApiController]
|
|
public class SurveyController : ControllerBase
|
|
{
|
|
private readonly SurveyService _surveyService;
|
|
private readonly UserManager<User> _userManager;
|
|
|
|
public SurveyController(SurveyService surveyService, UserManager<User> userManager)
|
|
{
|
|
_surveyService = surveyService;
|
|
_userManager = userManager;
|
|
}
|
|
|
|
[HttpGet("{id}")]
|
|
public async Task<IActionResult> GetById(string id)
|
|
{
|
|
var userId = _userManager.GetUserId(User);
|
|
var survey = await _surveyService.GetSurveyByIdAsync(id);
|
|
|
|
if (survey == null)
|
|
{
|
|
return NotFound();
|
|
}
|
|
|
|
if (userId != survey.AuthorId)
|
|
{
|
|
return Forbid();
|
|
}
|
|
|
|
var result = new SurveyResponseDto
|
|
{
|
|
Id = survey.Id,
|
|
Title = survey.Title,
|
|
Description = survey.Description,
|
|
Category = survey.Category,
|
|
ExpirationDate = survey.ExpirationDate,
|
|
IsPublished = survey.IsPublished,
|
|
};
|
|
|
|
return Ok(result);
|
|
}
|
|
//[Authorize]
|
|
[HttpPost]
|
|
public async Task<ActionResult<Survey>> CreateSurvey([FromBody] CreateSurveyDto request)
|
|
{
|
|
try
|
|
{
|
|
var survey = await _surveyService.CreateSurveyAsync(request);
|
|
return CreatedAtAction(nameof(GetById), new { id = survey.Id }, survey);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return BadRequest(new { message = ex.Message });
|
|
}
|
|
}
|
|
|
|
//[Authorize]
|
|
[HttpPut]
|
|
public async Task<IActionResult> UpdateSurvey([FromBody] UpdateSurveyDto request)
|
|
{
|
|
var success = await _surveyService.UpdateSurveyAsync(request);
|
|
if (!success) return NotFound(new { message = "Survey not found." });
|
|
return NoContent();
|
|
}
|
|
|
|
//[Authorize]
|
|
[HttpPatch("publish/{id}")]
|
|
public async Task<IActionResult> PublishSurvey(string id)
|
|
{
|
|
var success = await _surveyService.PublishSurveyAsync(id);
|
|
if (!success) return NotFound(new { message = "Survey not found." });
|
|
return NoContent();
|
|
}
|
|
|
|
//[Authorize]
|
|
[HttpPatch("unpublish/{id}")]
|
|
public async Task<IActionResult> UnpublishSurvey(string id)
|
|
{
|
|
var success = await _surveyService.UnpublishSurveyAsync(id);
|
|
if (!success) return NotFound(new { message = "Survey not found." });
|
|
return NoContent();
|
|
}
|
|
|
|
//[Authorize]
|
|
[HttpDelete("{id}")]
|
|
public async Task<IActionResult> DeleteSurvey(string id)
|
|
{
|
|
var success = await _surveyService.DeleteSurveyAsync(id);
|
|
if (!success) return NotFound(new { message = "Survey not found." });
|
|
return NoContent();
|
|
}
|
|
}
|