source: iknow-api/Controllers/ProfController.cs@ f7c8acf

Last change on this file since f7c8acf was ea40556, checked in by Stefan-Saveski <stefansaveski19@…>, 8 days ago
  • ready for presentation
  • Property mode set to 100644
File size: 3.0 KB
Line 
1using System.Security.Claims;
2using iknow_api.DTOs;
3using iknow_api.Services;
4using Microsoft.AspNetCore.Authorization;
5using Microsoft.AspNetCore.Mvc;
6
7namespace iknow_api.Controllers
8{
9 [ApiController]
10 [Route("api/[controller]")]
11 [Authorize]
12 public class ProfController : ControllerBase
13 {
14 private readonly IProfService _profService;
15
16 public ProfController(IProfService profService)
17 {
18 _profService = profService;
19 }
20
21 /// <summary>
22 /// The subjects this professor teaches, each with the students enrolled
23 /// in it and their grade so far.
24 /// </summary>
25 [HttpGet("students")]
26 public async Task<IActionResult> GetStudents()
27 {
28 if (!TryGetProfessorId(out var professorId, out var error))
29 {
30 return error;
31 }
32
33 return Ok(await _profService.GetStudentsBySubjectAsync(professorId));
34 }
35
36 [HttpPost("grade/add")]
37 public Task<IActionResult> AddGrade([FromBody] GradeRequestDto request) =>
38 SetGrade(request, GradeAction.Add);
39
40 [HttpPost("grade/edit")]
41 public Task<IActionResult> EditGrade([FromBody] GradeRequestDto request) =>
42 SetGrade(request, GradeAction.Edit);
43
44 [HttpPost("grade/remove")]
45 public Task<IActionResult> RemoveGrade([FromBody] GradeRequestDto request) =>
46 SetGrade(request, GradeAction.Remove);
47
48 private async Task<IActionResult> SetGrade(GradeRequestDto request, GradeAction action)
49 {
50 if (!TryGetProfessorId(out var professorId, out var error))
51 {
52 return error;
53 }
54
55 var result = await _profService.SetGradeAsync(professorId, request, action);
56 return result.Ok ? Ok(result) : BadRequest(result);
57 }
58
59 /// <summary>
60 /// Reads the caller from the validated token and requires the professor
61 /// role, so one professor can never act on another one's subjects.
62 /// </summary>
63 private bool TryGetProfessorId(out int professorId, out IActionResult error)
64 {
65 professorId = 0;
66 error = Forbid();
67
68 var role = User.FindFirst(ClaimTypes.Role)?.Value ?? User.FindFirst("role")?.Value;
69 if (!string.Equals(role, nameof(Models.UserRole.Professor), StringComparison.OrdinalIgnoreCase))
70 {
71 error = StatusCode(403, new GradeResultDto
72 {
73 Ok = false,
74 Message = "This endpoint is for professors."
75 });
76 return false;
77 }
78
79 var idClaim = User.FindFirst("id")?.Value;
80 if (!int.TryParse(idClaim, out professorId))
81 {
82 error = Unauthorized(new GradeResultDto
83 {
84 Ok = false,
85 Message = "Token has no usable user id."
86 });
87 return false;
88 }
89
90 return true;
91 }
92 }
93}
Note: See TracBrowser for help on using the repository browser.