| 1 | using System.Security.Claims;
|
|---|
| 2 | using iknow_api.DTOs;
|
|---|
| 3 | using iknow_api.Services;
|
|---|
| 4 | using Microsoft.AspNetCore.Authorization;
|
|---|
| 5 | using Microsoft.AspNetCore.Mvc;
|
|---|
| 6 |
|
|---|
| 7 | namespace iknow_api.Controllers
|
|---|
| 8 | {
|
|---|
| 9 | [ApiController]
|
|---|
| 10 | [Route("api/[controller]")]
|
|---|
| 11 | [Authorize]
|
|---|
| 12 | public class EnrollmentController : ControllerBase
|
|---|
| 13 | {
|
|---|
| 14 | private readonly IEnrollmentService _enrollmentService;
|
|---|
| 15 |
|
|---|
| 16 | public EnrollmentController(IEnrollmentService enrollmentService)
|
|---|
| 17 | {
|
|---|
| 18 | _enrollmentService = enrollmentService;
|
|---|
| 19 | }
|
|---|
| 20 |
|
|---|
| 21 | [HttpGet("options")]
|
|---|
| 22 | public async Task<IActionResult> GetOptions()
|
|---|
| 23 | {
|
|---|
| 24 | if (!TryGetStudentId(out var studentId, out var error))
|
|---|
| 25 | {
|
|---|
| 26 | return error;
|
|---|
| 27 | }
|
|---|
| 28 |
|
|---|
| 29 | return Ok(await _enrollmentService.GetOptionsAsync(studentId));
|
|---|
| 30 | }
|
|---|
| 31 |
|
|---|
| 32 | [HttpPost]
|
|---|
| 33 | public async Task<IActionResult> Enroll([FromBody] EnrollSemesterRequestDto request)
|
|---|
| 34 | {
|
|---|
| 35 | if (!TryGetStudentId(out var studentId, out var error))
|
|---|
| 36 | {
|
|---|
| 37 | return error;
|
|---|
| 38 | }
|
|---|
| 39 |
|
|---|
| 40 | var result = await _enrollmentService.EnrollAsync(studentId, request);
|
|---|
| 41 | return result.Ok ? Ok(result) : BadRequest(result);
|
|---|
| 42 | }
|
|---|
| 43 |
|
|---|
| 44 | /// <summary>
|
|---|
| 45 | /// Reads the caller from the validated token, so a student can only ever
|
|---|
| 46 | /// enrol themselves.
|
|---|
| 47 | /// </summary>
|
|---|
| 48 | private bool TryGetStudentId(out int studentId, out IActionResult error)
|
|---|
| 49 | {
|
|---|
| 50 | studentId = 0;
|
|---|
| 51 | error = Forbid();
|
|---|
| 52 |
|
|---|
| 53 | var role = User.FindFirst(ClaimTypes.Role)?.Value ?? User.FindFirst("role")?.Value;
|
|---|
| 54 | if (!string.Equals(role, nameof(Models.UserRole.Student), StringComparison.OrdinalIgnoreCase))
|
|---|
| 55 | {
|
|---|
| 56 | error = StatusCode(403, new EnrollSemesterResultDto
|
|---|
| 57 | {
|
|---|
| 58 | Ok = false,
|
|---|
| 59 | Message = "Only students can enrol in a semester."
|
|---|
| 60 | });
|
|---|
| 61 | return false;
|
|---|
| 62 | }
|
|---|
| 63 |
|
|---|
| 64 | var idClaim = User.FindFirst("id")?.Value;
|
|---|
| 65 | if (!int.TryParse(idClaim, out studentId))
|
|---|
| 66 | {
|
|---|
| 67 | error = Unauthorized(new EnrollSemesterResultDto
|
|---|
| 68 | {
|
|---|
| 69 | Ok = false,
|
|---|
| 70 | Message = "Token has no usable user id."
|
|---|
| 71 | });
|
|---|
| 72 | return false;
|
|---|
| 73 | }
|
|---|
| 74 |
|
|---|
| 75 | return true;
|
|---|
| 76 | }
|
|---|
| 77 | }
|
|---|
| 78 | }
|
|---|