mirror of
https://github.com/opelly27/WinStudentGoalTracker.git
synced 2026-05-20 06:27:37 +00:00
added first controller and corresponding stored procedures.
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace WinStudentGoalTracker.BaseClasses;
|
||||
|
||||
public class BaseController : ControllerBase
|
||||
{
|
||||
protected (int userId, ActionResult? error) GetUserIdFromClaims()
|
||||
{
|
||||
var userIdClaim = User.FindFirst("user_id")?.Value
|
||||
?? User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(userIdClaim) || !int.TryParse(userIdClaim, out var userId))
|
||||
{
|
||||
return (0, Unauthorized("Missing or invalid user_id claim."));
|
||||
}
|
||||
|
||||
return (userId, null);
|
||||
}
|
||||
|
||||
protected (string email, List<string> roles, ActionResult? error) GetUserDetailsFromClaims()
|
||||
{
|
||||
var email = User.FindFirst(ClaimTypes.Email)?.Value;
|
||||
if (string.IsNullOrWhiteSpace(email))
|
||||
{
|
||||
return (string.Empty, new List<string>(), Unauthorized("Missing email claim."));
|
||||
}
|
||||
|
||||
var roles = User.FindAll(ClaimTypes.Role).Select(claim => claim.Value).ToList();
|
||||
return (email, roles, null);
|
||||
}
|
||||
|
||||
protected bool HasRole(string role)
|
||||
{
|
||||
return User.IsInRole(role);
|
||||
}
|
||||
|
||||
protected bool HasAnyRole(params string[] roles)
|
||||
{
|
||||
return roles.Any(User.IsInRole);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using WinStudentGoalTracker.Models;
|
||||
using WinStudentGoalTracker.BaseClasses;
|
||||
using WinStudentGoalTracker.DataAccess;
|
||||
|
||||
namespace WinStudentGoalTracker.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public class StudentController : BaseController
|
||||
{
|
||||
private readonly StudentRepository _studentRepository = new();
|
||||
|
||||
|
||||
// TODO refactor this stored procedure
|
||||
// to getmystudents
|
||||
// This required auth system to be set up first
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(ResponseResult<IEnumerable<StudentResponse>>), StatusCodes.Status200OK)]
|
||||
public async Task<ActionResult<ResponseResult<IEnumerable<StudentResponse>>>> GetAll()
|
||||
{
|
||||
var students = await _studentRepository.GetAllAsync();
|
||||
var response = students.Select(StudentResponse.FromDatabaseModel);
|
||||
|
||||
return Ok(new ResponseResult<IEnumerable<StudentResponse>>
|
||||
{
|
||||
Success = true,
|
||||
Data = response
|
||||
});
|
||||
}
|
||||
|
||||
[HttpGet("{idStudent:int}")]
|
||||
[ProducesResponseType(typeof(ResponseResult<StudentResponse>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ResponseResult<StudentResponse>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ActionResult<ResponseResult<StudentResponse>>> GetById(int idStudent)
|
||||
{
|
||||
var student = await _studentRepository.GetByIdAsync(idStudent);
|
||||
if (student is null)
|
||||
{
|
||||
return NotFound(new ResponseResult<StudentResponse>
|
||||
{
|
||||
Success = false,
|
||||
Message = "Student not found."
|
||||
});
|
||||
}
|
||||
|
||||
return Ok(new ResponseResult<StudentResponse>
|
||||
{
|
||||
Success = true,
|
||||
Data = StudentResponse.FromDatabaseModel(student)
|
||||
});
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[ProducesResponseType(typeof(ResponseResult<StudentResponse>), StatusCodes.Status201Created)]
|
||||
[ProducesResponseType(typeof(ResponseResult<StudentResponse>), StatusCodes.Status400BadRequest)]
|
||||
public async Task<ActionResult<ResponseResult<StudentResponse>>> Create([FromBody] CreateStudentDto request)
|
||||
{
|
||||
var existing = await _studentRepository.GetByIdAsync(request.IdStudent);
|
||||
if (existing is not null)
|
||||
{
|
||||
return BadRequest(new ResponseResult<StudentResponse>
|
||||
{
|
||||
Success = false,
|
||||
Message = $"Student with id {request.IdStudent} already exists."
|
||||
});
|
||||
}
|
||||
|
||||
var created = await _studentRepository.InsertAsync(request);
|
||||
if (created is null)
|
||||
{
|
||||
return BadRequest(new ResponseResult<StudentResponse>
|
||||
{
|
||||
Success = false,
|
||||
Message = "Unable to create student."
|
||||
});
|
||||
}
|
||||
|
||||
var response = StudentResponse.FromDatabaseModel(created);
|
||||
return CreatedAtAction(nameof(GetById), new { idStudent = response.IdStudent }, new ResponseResult<StudentResponse>
|
||||
{
|
||||
Success = true,
|
||||
Data = response
|
||||
});
|
||||
}
|
||||
|
||||
[HttpPut("{idStudent:int}")]
|
||||
[ProducesResponseType(typeof(ResponseResult<StudentResponse>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ResponseResult<StudentResponse>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ActionResult<ResponseResult<StudentResponse>>> Update(int idStudent, [FromBody] UpdateStudentDto request)
|
||||
{
|
||||
var existing = await _studentRepository.GetByIdAsync(idStudent);
|
||||
if (existing is null)
|
||||
{
|
||||
return NotFound(new ResponseResult<StudentResponse>
|
||||
{
|
||||
Success = false,
|
||||
Message = "Student not found."
|
||||
});
|
||||
}
|
||||
|
||||
var updated = await _studentRepository.UpdateAsync(idStudent, request);
|
||||
var refreshed = await _studentRepository.GetByIdAsync(idStudent);
|
||||
if (refreshed is null)
|
||||
{
|
||||
return NotFound(new ResponseResult<StudentResponse>
|
||||
{
|
||||
Success = false,
|
||||
Message = "Student not found after update."
|
||||
});
|
||||
}
|
||||
|
||||
return Ok(new ResponseResult<StudentResponse>
|
||||
{
|
||||
Success = true,
|
||||
Message = updated ? null : "No changes were applied.",
|
||||
Data = StudentResponse.FromDatabaseModel(refreshed)
|
||||
});
|
||||
}
|
||||
|
||||
[HttpDelete("{idStudent:int}")]
|
||||
[ProducesResponseType(typeof(ResponseResult<object>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ResponseResult<object>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ActionResult<ResponseResult<object>>> Delete(int idStudent)
|
||||
{
|
||||
var deleted = await _studentRepository.DeleteAsync(idStudent);
|
||||
if (!deleted)
|
||||
{
|
||||
return NotFound(new ResponseResult<object>
|
||||
{
|
||||
Success = false,
|
||||
Message = "Student not found."
|
||||
});
|
||||
}
|
||||
|
||||
return Ok(new ResponseResult<object>
|
||||
{
|
||||
Success = true,
|
||||
Message = "Student deleted."
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using Dapper;
|
||||
using WinStudentGoalTracker.Api.Configuration;
|
||||
|
||||
namespace WinStudentGoalTracker.DataAccess;
|
||||
|
||||
public static class DatabaseManager
|
||||
{
|
||||
static DatabaseManager()
|
||||
{
|
||||
DefaultTypeMap.MatchNamesWithUnderscores = true;
|
||||
}
|
||||
|
||||
public static string ConnectionString =>
|
||||
ConfigHelper.Configuration.GetConnectionString("DefaultConnection")
|
||||
?? throw new MissingFieldException("DefaultConnection not configured.");
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace WinStudentGoalTracker.DataAccess;
|
||||
|
||||
public class CreateStudentDto
|
||||
{
|
||||
public required int IdStudent { get; set; }
|
||||
public int? IdProgram { get; set; }
|
||||
public string? Identifier { get; set; }
|
||||
public int? ProgramYear { get; set; }
|
||||
public DateTime? EnrollmentDate { get; set; }
|
||||
public DateTime? ExpectedGrad { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace WinStudentGoalTracker.DataAccess;
|
||||
|
||||
public class UpdateStudentDto
|
||||
{
|
||||
public int? IdProgram { get; set; }
|
||||
public string? Identifier { get; set; }
|
||||
public int? ProgramYear { get; set; }
|
||||
public DateTime? EnrollmentDate { get; set; }
|
||||
public DateTime? ExpectedGrad { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace WinStudentGoalTracker.DataAccess;
|
||||
|
||||
public class dbStudent
|
||||
{
|
||||
public required int IdStudent { get; set; }
|
||||
public int? IdProgram { get; set; }
|
||||
public string? Identifier { get; set; }
|
||||
public int? ProgramYear { get; set; }
|
||||
public DateTime? EnrollmentDate { get; set; }
|
||||
public DateTime? ExpectedGrad { get; set; }
|
||||
public DateTime? CreatedAt { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using System.Data;
|
||||
using Dapper;
|
||||
using MySql.Data.MySqlClient;
|
||||
|
||||
namespace WinStudentGoalTracker.DataAccess;
|
||||
|
||||
public class StudentRepository
|
||||
{
|
||||
private IDbConnection Connection => new MySqlConnection(DatabaseManager.ConnectionString);
|
||||
|
||||
public async Task<IEnumerable<dbStudent>> GetAllAsync()
|
||||
{
|
||||
using var db = Connection;
|
||||
return await db.QueryAsync<dbStudent>(
|
||||
"sp_Student_GetAll",
|
||||
commandType: CommandType.StoredProcedure);
|
||||
}
|
||||
|
||||
public async Task<dbStudent?> GetByIdAsync(int idStudent)
|
||||
{
|
||||
using var db = Connection;
|
||||
return await db.QuerySingleOrDefaultAsync<dbStudent>(
|
||||
"sp_Student_GetById",
|
||||
new { p_id_student = idStudent },
|
||||
commandType: CommandType.StoredProcedure);
|
||||
}
|
||||
|
||||
public async Task<dbStudent?> InsertAsync(CreateStudentDto dto)
|
||||
{
|
||||
using var db = Connection;
|
||||
return await db.QuerySingleOrDefaultAsync<dbStudent>(
|
||||
"sp_Student_Insert",
|
||||
new
|
||||
{
|
||||
p_id_student = dto.IdStudent,
|
||||
p_id_program = dto.IdProgram,
|
||||
p_identifier = dto.Identifier,
|
||||
p_program_year = dto.ProgramYear,
|
||||
p_enrollment_date = dto.EnrollmentDate,
|
||||
p_expected_grad = dto.ExpectedGrad
|
||||
},
|
||||
commandType: CommandType.StoredProcedure);
|
||||
}
|
||||
|
||||
public async Task<bool> UpdateAsync(int idStudent, UpdateStudentDto dto)
|
||||
{
|
||||
using var db = Connection;
|
||||
var rowsAffected = await db.ExecuteScalarAsync<int>(
|
||||
"sp_Student_Update",
|
||||
new
|
||||
{
|
||||
p_id_student = idStudent,
|
||||
p_id_program = dto.IdProgram,
|
||||
p_identifier = dto.Identifier,
|
||||
p_program_year = dto.ProgramYear,
|
||||
p_enrollment_date = dto.EnrollmentDate,
|
||||
p_expected_grad = dto.ExpectedGrad
|
||||
},
|
||||
commandType: CommandType.StoredProcedure);
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteAsync(int idStudent)
|
||||
{
|
||||
using var db = Connection;
|
||||
var rowsAffected = await db.ExecuteScalarAsync<int>(
|
||||
"sp_Student_Delete",
|
||||
new { p_id_student = idStudent },
|
||||
commandType: CommandType.StoredProcedure);
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace WinStudentGoalTracker.Models;
|
||||
|
||||
public class ResponseResult<T>
|
||||
{
|
||||
public bool Success { get; set; }
|
||||
public string? Message { get; set; }
|
||||
public T? Data { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using WinStudentGoalTracker.DataAccess;
|
||||
|
||||
namespace WinStudentGoalTracker.Models;
|
||||
|
||||
public class StudentResponse
|
||||
{
|
||||
public int IdStudent { get; set; }
|
||||
public int? IdProgram { get; set; }
|
||||
public string? Identifier { get; set; }
|
||||
public int? ProgramYear { get; set; }
|
||||
public DateTime? EnrollmentDate { get; set; }
|
||||
public DateTime? ExpectedGrad { get; set; }
|
||||
public DateTime? CreatedAt { get; set; }
|
||||
|
||||
public static StudentResponse FromDatabaseModel(dbStudent student)
|
||||
{
|
||||
return new StudentResponse
|
||||
{
|
||||
IdStudent = student.IdStudent,
|
||||
IdProgram = student.IdProgram,
|
||||
Identifier = student.Identifier,
|
||||
ProgramYear = student.ProgramYear,
|
||||
EnrollmentDate = student.EnrollmentDate,
|
||||
ExpectedGrad = student.ExpectedGrad,
|
||||
CreatedAt = student.CreatedAt
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
namespace WinStudentGoalTracker.Models;
|
||||
|
||||
public static class UserRoles
|
||||
{
|
||||
// Role names from role-based-access-control.md
|
||||
public const string Teacher = "Teacher";
|
||||
public const string Paraeducator = "Paraeducator";
|
||||
public const string ProgramAdmin = "ProgramAdmin";
|
||||
public const string DistrictAdmin = "DistrictAdmin";
|
||||
public const string SuperAdmin = "SuperAdmin";
|
||||
|
||||
public static readonly IReadOnlyList<string> All = new[]
|
||||
{
|
||||
Teacher,
|
||||
Paraeducator,
|
||||
ProgramAdmin,
|
||||
DistrictAdmin,
|
||||
SuperAdmin
|
||||
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user