diff --git a/Directory.Build.props b/Directory.Build.props
index 208b791ca..bc8ae8f35 100644
--- a/Directory.Build.props
+++ b/Directory.Build.props
@@ -4,6 +4,6 @@
- enable
+ disable
\ No newline at end of file
diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/AccountController.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/AccountController.cs
index 7886595ab..48f18993e 100644
--- a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/AccountController.cs
+++ b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/AccountController.cs
@@ -14,135 +14,134 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
-namespace HwProj.APIGateway.API.Controllers
-{
- [Route("api/[controller]")]
- [ApiController]
- public class AccountController : AggregationController
- {
- private readonly ICoursesServiceClient _coursesClient;
- private readonly ISolutionsServiceClient _solutionsServiceClient;
+namespace HwProj.APIGateway.API.Controllers;
- public AccountController(
- IAuthServiceClient authClient,
- ICoursesServiceClient coursesClient,
- ISolutionsServiceClient solutionsServiceClient) : base(authClient)
- {
- _coursesClient = coursesClient;
- _solutionsServiceClient = solutionsServiceClient;
- }
+[Route("api/[controller]")]
+[ApiController]
+public class AccountController : AggregationController
+{
+ private readonly ICoursesServiceClient _coursesClient;
+ private readonly ISolutionsServiceClient _solutionsServiceClient;
- [HttpGet("getUserData/{userId}")]
- [ProducesResponseType(typeof(AccountDataDto), (int)HttpStatusCode.OK)]
- public async Task GetUserDataById(string userId)
- {
- var result = await AuthServiceClient.GetAccountData(userId);
- return result == null
- ? NotFound() as IActionResult
- : Ok(result);
- }
+ public AccountController(
+ IAuthServiceClient authClient,
+ ICoursesServiceClient coursesClient,
+ ISolutionsServiceClient solutionsServiceClient) : base(authClient)
+ {
+ _coursesClient = coursesClient;
+ _solutionsServiceClient = solutionsServiceClient;
+ }
- //TODO: separate for mentor and student
- [HttpGet("getUserData")]
- [Authorize]
- [ProducesResponseType(typeof(UserDataDto), (int)HttpStatusCode.OK)]
- public async Task GetUserData()
- {
- var getAccountDataTask = AuthServiceClient.GetAccountData(UserId);
- var getCoursesTask = _coursesClient.GetAllUserCourses();
+ [HttpGet("getUserData/{userId}")]
+ [ProducesResponseType(typeof(AccountDataDto), (int)HttpStatusCode.OK)]
+ public async Task GetUserDataById(string userId)
+ {
+ var result = await AuthServiceClient.GetAccountData(userId);
+ return result == null
+ ? NotFound()
+ : Ok(result);
+ }
- await Task.WhenAll(getAccountDataTask, getCoursesTask);
+ //TODO: separate for mentor and student
+ [HttpGet("getUserData")]
+ [Authorize]
+ [ProducesResponseType(typeof(UserDataDto), (int)HttpStatusCode.OK)]
+ public async Task GetUserData()
+ {
+ var getAccountDataTask = AuthServiceClient.GetAccountData(UserId);
+ var getCoursesTask = _coursesClient.GetAllUserCourses();
- var courses = GetCoursePreviews(getCoursesTask.Result);
+ await Task.WhenAll(getAccountDataTask, getCoursesTask);
- if (User.IsInRole(Roles.LecturerRole))
- {
- return Ok(new UserDataDto
- {
- UserData = getAccountDataTask.Result,
- Courses = await courses,
- TaskDeadlines = Array.Empty()
- });
- }
-
- var taskDeadlines = await _coursesClient.GetTaskDeadlines();
- var taskIds = taskDeadlines.Select(t => t.TaskId).ToArray();
- var solutions = await _solutionsServiceClient.GetLastTaskSolutions(taskIds, UserId);
- var taskDeadlinesInfo = taskDeadlines.Select((d, i) => new TaskDeadlineView
- {
- Deadline = d,
- SolutionState = solutions[i]?.State,
- Rating = solutions[i]?.Rating,
- MaxRating = taskDeadlines[i].MaxRating
- }).ToArray();
+ var courses = GetCoursePreviews(getCoursesTask.Result);
- var aggregatedResult = new UserDataDto
+ if (User.IsInRole(Roles.LecturerRole))
+ {
+ return Ok(new UserDataDto
{
UserData = getAccountDataTask.Result,
Courses = await courses,
- TaskDeadlines = taskDeadlinesInfo
- };
- return Ok(aggregatedResult);
+ TaskDeadlines = Array.Empty()
+ });
}
- [HttpPost("register")]
- [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)]
- public async Task Register(RegisterViewModel model)
+ var taskDeadlines = await _coursesClient.GetTaskDeadlines();
+ var taskIds = taskDeadlines.Select(t => t.TaskId).ToArray();
+ var solutions = await _solutionsServiceClient.GetLastTaskSolutions(taskIds, UserId);
+ var taskDeadlinesInfo = taskDeadlines.Select((d, i) => new TaskDeadlineView
{
- var result = await AuthServiceClient.Register(model);
- return Ok(result);
- }
+ Deadline = d,
+ SolutionState = solutions[i]?.State,
+ Rating = solutions[i]?.Rating,
+ MaxRating = taskDeadlines[i].MaxRating
+ }).ToArray();
- [HttpPost("login")]
- [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)]
- public async Task Login(LoginViewModel model)
+ var aggregatedResult = new UserDataDto
{
- var tokenMeta = await AuthServiceClient.Login(model).ConfigureAwait(false);
- return Ok(tokenMeta);
- }
+ UserData = getAccountDataTask.Result,
+ Courses = await courses,
+ TaskDeadlines = taskDeadlinesInfo
+ };
+ return Ok(aggregatedResult);
+ }
- [HttpPut("edit")]
- [Authorize]
- [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)]
- public async Task Edit(EditAccountViewModel model)
- {
- var result = await AuthServiceClient.Edit(model, UserId);
- return Ok(result);
- }
+ [HttpPost("register")]
+ [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)]
+ public async Task Register(RegisterViewModel model)
+ {
+ var result = await AuthServiceClient.Register(model);
+ return Ok(result);
+ }
- [HttpPost("inviteNewLecturer")]
- [Authorize(Roles = Roles.LecturerRole)]
- [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)]
- public async Task InviteNewLecturer(InviteLecturerViewModel model)
- {
- var result = await AuthServiceClient.InviteNewLecturer(model).ConfigureAwait(false);
- return Ok(result);
- }
+ [HttpPost("login")]
+ [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)]
+ public async Task Login(LoginViewModel model)
+ {
+ var tokenMeta = await AuthServiceClient.Login(model).ConfigureAwait(false);
+ return Ok(tokenMeta);
+ }
- [HttpPost("google")]
- [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)]
- public async Task LoginByGoogle(string tokenId)
- {
- var tokenMeta = await AuthServiceClient.LoginByGoogle(tokenId).ConfigureAwait(false);
- return Ok(tokenMeta);
- }
+ [HttpPut("edit")]
+ [Authorize]
+ [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)]
+ public async Task Edit(EditAccountViewModel model)
+ {
+ var result = await AuthServiceClient.Edit(model, UserId);
+ return Ok(result);
+ }
- [HttpPut("editExternal")]
- [Authorize]
- [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)]
- public async Task EditExternal(EditExternalViewModel model)
- {
- var result = await AuthServiceClient.EditExternal(model, UserId);
- return Ok(result);
- }
+ [HttpPost("inviteNewLecturer")]
+ [Authorize(Roles = Roles.LecturerRole)]
+ [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)]
+ public async Task InviteNewLecturer(InviteLecturerViewModel model)
+ {
+ var result = await AuthServiceClient.InviteNewLecturer(model).ConfigureAwait(false);
+ return Ok(result);
+ }
- [HttpGet("getAllStudents")]
- [Authorize(Roles = Roles.LecturerRole)]
- [ProducesResponseType(typeof(AccountDataDto[]), (int)HttpStatusCode.OK)]
- public async Task GetAllStudents()
- {
- var result = await AuthServiceClient.GetAllStudents();
- return Ok(result);
- }
+ [HttpPost("google")]
+ [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)]
+ public async Task LoginByGoogle(string tokenId)
+ {
+ var tokenMeta = await AuthServiceClient.LoginByGoogle(tokenId).ConfigureAwait(false);
+ return Ok(tokenMeta);
+ }
+
+ [HttpPut("editExternal")]
+ [Authorize]
+ [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)]
+ public async Task EditExternal(EditExternalViewModel model)
+ {
+ var result = await AuthServiceClient.EditExternal(model, UserId);
+ return Ok(result);
+ }
+
+ [HttpGet("getAllStudents")]
+ [Authorize(Roles = Roles.LecturerRole)]
+ [ProducesResponseType(typeof(AccountDataDto[]), (int)HttpStatusCode.OK)]
+ public async Task GetAllStudents()
+ {
+ var result = await AuthServiceClient.GetAllStudents();
+ return Ok(result);
}
}
diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/AggregationController.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/AggregationController.cs
index c484313e4..105a76f03 100644
--- a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/AggregationController.cs
+++ b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/AggregationController.cs
@@ -5,39 +5,38 @@
using HwProj.Models.CoursesService.ViewModels;
using Microsoft.AspNetCore.Mvc;
-namespace HwProj.APIGateway.API.Controllers
+namespace HwProj.APIGateway.API.Controllers;
+
+public class AggregationController : ControllerBase
{
- public class AggregationController : ControllerBase
- {
- protected readonly IAuthServiceClient AuthServiceClient;
+ protected readonly IAuthServiceClient AuthServiceClient;
- protected AggregationController(IAuthServiceClient authServiceClient)
- {
- AuthServiceClient = authServiceClient;
- }
+ protected AggregationController(IAuthServiceClient authServiceClient)
+ {
+ AuthServiceClient = authServiceClient;
+ }
- protected string? UserId =>
- Request.HttpContext.User.Claims
- .FirstOrDefault(claim => claim.Type.ToString() == "_id")
- ?.Value;
+ protected string? UserId =>
+ Request.HttpContext.User.Claims
+ .FirstOrDefault(claim => claim.Type.ToString() == "_id")
+ ?.Value;
- protected async Task GetCoursePreviews(CoursePreview[] courses)
- {
- var getMentorsTasks = courses.Select(t => AuthServiceClient.GetAccountsData(t.MentorIds)).ToList();
- await Task.WhenAll(getMentorsTasks);
- var mentorDTOs = getMentorsTasks.Select(t => t.Result);
+ protected async Task GetCoursePreviews(CoursePreview[] courses)
+ {
+ var getMentorsTasks = courses.Select(t => AuthServiceClient.GetAccountsData(t.MentorIds)).ToList();
+ await Task.WhenAll(getMentorsTasks);
+ var mentorDTOs = getMentorsTasks.Select(t => t.Result);
- var result = courses.Zip(mentorDTOs, (course, mentors) =>
- new CoursePreviewView
- {
- Id = course.Id,
- Name = course.Name,
- GroupName = course.GroupName,
- IsCompleted = course.IsCompleted,
- Mentors = mentors.Where(t => t != null).ToArray()
- }).ToArray();
+ var result = courses.Zip(mentorDTOs, (course, mentors) =>
+ new CoursePreviewView
+ {
+ Id = course.Id,
+ Name = course.Name,
+ GroupName = course.GroupName,
+ IsCompleted = course.IsCompleted,
+ Mentors = mentors.Where(t => t != null).ToArray()
+ }).ToArray();
- return result;
- }
+ return result;
}
-}
+}
\ No newline at end of file
diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/CourseGroupsController.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/CourseGroupsController.cs
index 7e1672ee6..1aebf1161 100644
--- a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/CourseGroupsController.cs
+++ b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/CourseGroupsController.cs
@@ -6,97 +6,96 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
-namespace HwProj.APIGateway.API.Controllers
+namespace HwProj.APIGateway.API.Controllers;
+
+[Route("api/[controller]")]
+[ApiController]
+public class CourseGroupsController : AggregationController
{
- [Route("api/[controller]")]
- [ApiController]
- public class CourseGroupsController : AggregationController
- {
- private readonly ICoursesServiceClient _coursesClient;
+ private readonly ICoursesServiceClient _coursesClient;
- public CourseGroupsController(ICoursesServiceClient coursesClient) : base(null)
- {
- _coursesClient = coursesClient;
- }
+ public CourseGroupsController(ICoursesServiceClient coursesClient) : base(null)
+ {
+ _coursesClient = coursesClient;
+ }
- [HttpGet("{courseId}/getAll")]
- [ProducesResponseType(typeof(GroupViewModel[]), (int)HttpStatusCode.OK)]
- public async Task GetAllCourseGroups(long courseId)
- {
- var result = await _coursesClient.GetAllCourseGroups(courseId);
- return result == null
- ? NotFound() as IActionResult
- : Ok(result);
- }
+ [HttpGet("{courseId}/getAll")]
+ [ProducesResponseType(typeof(GroupViewModel[]), (int)HttpStatusCode.OK)]
+ public async Task GetAllCourseGroups(long courseId)
+ {
+ var result = await _coursesClient.GetAllCourseGroups(courseId);
+ return result == null
+ ? NotFound()
+ : Ok(result);
+ }
- [HttpPost("{courseId}/create")]
- [Authorize(Roles = Roles.LecturerRole)]
- [ProducesResponseType(typeof(long), (int)HttpStatusCode.OK)]
- public async Task CreateCourseGroup(CreateGroupViewModel model, long courseId)
- {
- var result = await _coursesClient.CreateCourseGroup(model, courseId);
- return Ok(result);
- }
+ [HttpPost("{courseId}/create")]
+ [Authorize(Roles = Roles.LecturerRole)]
+ [ProducesResponseType(typeof(long), (int)HttpStatusCode.OK)]
+ public async Task CreateCourseGroup(CreateGroupViewModel model, long courseId)
+ {
+ var result = await _coursesClient.CreateCourseGroup(model, courseId);
+ return Ok(result);
+ }
- [HttpDelete("{courseId}/delete/{groupId}")]
- [Authorize(Roles = Roles.LecturerRole)]
- public async Task DeleteCourseGroup(long courseId, long groupId)
- {
- await _coursesClient.DeleteCourseGroup(courseId, groupId);
- return Ok();
- }
+ [HttpDelete("{courseId}/delete/{groupId}")]
+ [Authorize(Roles = Roles.LecturerRole)]
+ public async Task DeleteCourseGroup(long courseId, long groupId)
+ {
+ await _coursesClient.DeleteCourseGroup(courseId, groupId);
+ return Ok();
+ }
- [HttpPost("{courseId}/update/{groupId}")]
- [Authorize(Roles = Roles.LecturerRole)]
- public async Task UpdateCourseGroup(UpdateGroupViewModel model, long courseId, long groupId)
- {
- await _coursesClient.UpdateCourseGroup(model, courseId, groupId);
- return Ok();
- }
+ [HttpPost("{courseId}/update/{groupId}")]
+ [Authorize(Roles = Roles.LecturerRole)]
+ public async Task UpdateCourseGroup(UpdateGroupViewModel model, long courseId, long groupId)
+ {
+ await _coursesClient.UpdateCourseGroup(model, courseId, groupId);
+ return Ok();
+ }
- [HttpGet("{courseId}/get")]
- [Authorize]
- [ProducesResponseType(typeof(GroupViewModel), (int)HttpStatusCode.OK)]
- public async Task GetCourseGroupsById(long courseId)
- {
- var result = await _coursesClient.GetCourseGroupsById(courseId, UserId);
- return result == null
- ? NotFound() as IActionResult
- : Ok(result);
- }
+ [HttpGet("{courseId}/get")]
+ [Authorize]
+ [ProducesResponseType(typeof(GroupViewModel), (int)HttpStatusCode.OK)]
+ public async Task GetCourseGroupsById(long courseId)
+ {
+ var result = await _coursesClient.GetCourseGroupsById(courseId, UserId);
+ return result == null
+ ? NotFound()
+ : Ok(result);
+ }
- [HttpPost("{courseId}/addStudentInGroup/{groupId}")]
- [Authorize(Roles = Roles.LecturerRole)]
- public async Task AddStudentInGroup(long courseId, long groupId, [FromQuery] string userId)
- {
- await _coursesClient.AddStudentInGroup(courseId, groupId, userId);
- return Ok();
- }
+ [HttpPost("{courseId}/addStudentInGroup/{groupId}")]
+ [Authorize(Roles = Roles.LecturerRole)]
+ public async Task AddStudentInGroup(long courseId, long groupId, [FromQuery] string userId)
+ {
+ await _coursesClient.AddStudentInGroup(courseId, groupId, userId);
+ return Ok();
+ }
- [HttpPost("{courseId}/removeStudentFromGroup/{groupId}")]
- [Authorize(Roles = Roles.LecturerRole)]
- public async Task RemoveStudentFromGroup(long courseId, long groupId, [FromQuery] string userId)
- {
- await _coursesClient.RemoveStudentFromGroup(courseId, groupId, userId);
- return Ok();
- }
+ [HttpPost("{courseId}/removeStudentFromGroup/{groupId}")]
+ [Authorize(Roles = Roles.LecturerRole)]
+ public async Task RemoveStudentFromGroup(long courseId, long groupId, [FromQuery] string userId)
+ {
+ await _coursesClient.RemoveStudentFromGroup(courseId, groupId, userId);
+ return Ok();
+ }
- [HttpGet("get/{groupId}")]
- [ProducesResponseType(typeof(GroupViewModel), (int)HttpStatusCode.OK)]
- public async Task GetGroup(long groupId)
- {
- var result = await _coursesClient.GetGroupById(groupId);
- return result == null
- ? NotFound() as IActionResult
- : Ok(result);
- }
+ [HttpGet("get/{groupId}")]
+ [ProducesResponseType(typeof(GroupViewModel), (int)HttpStatusCode.OK)]
+ public async Task GetGroup(long groupId)
+ {
+ var result = await _coursesClient.GetGroupById(groupId);
+ return result == null
+ ? NotFound()
+ : Ok(result);
+ }
- [HttpGet("getTasks/{groupId}")]
- [ProducesResponseType(typeof(long[]), (int)HttpStatusCode.OK)]
- public async Task GetGroupTasks(long groupId)
- {
- var result = await _coursesClient.GetGroupTasks(groupId);
- return Ok(result);
- }
+ [HttpGet("getTasks/{groupId}")]
+ [ProducesResponseType(typeof(long[]), (int)HttpStatusCode.OK)]
+ public async Task GetGroupTasks(long groupId)
+ {
+ var result = await _coursesClient.GetGroupTasks(groupId);
+ return Ok(result);
}
-}
+}
\ No newline at end of file
diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/CoursesController.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/CoursesController.cs
index 5b83b747e..b178ff9b3 100644
--- a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/CoursesController.cs
+++ b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/CoursesController.cs
@@ -11,142 +11,146 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
-namespace HwProj.APIGateway.API.Controllers
-{
- [Route("api/[controller]")]
- [ApiController]
- public class CoursesController : AggregationController
- {
- private readonly ICoursesServiceClient _coursesClient;
+namespace HwProj.APIGateway.API.Controllers;
- public CoursesController(ICoursesServiceClient coursesClient, IAuthServiceClient authServiceClient) : base(
- authServiceClient)
- {
- _coursesClient = coursesClient;
- }
+[Route("api/[controller]")]
+[ApiController]
+public class CoursesController : AggregationController
+{
+ private readonly ICoursesServiceClient _coursesClient;
- [HttpGet]
- [Authorize]
- public async Task GetAllCourses()
- {
- var courses = await _coursesClient.GetAllCourses();
- var result = await GetCoursePreviews(courses);
- return result;
- }
+ public CoursesController(ICoursesServiceClient coursesClient, IAuthServiceClient authServiceClient) : base(
+ authServiceClient)
+ {
+ _coursesClient = coursesClient;
+ }
- [HttpGet("{courseId}")]
- [ProducesResponseType(typeof(CourseViewModel), (int)HttpStatusCode.OK)]
- public async Task GetCourseData(long courseId)
- {
- var course = await _coursesClient.GetCourseById(courseId, UserId);
- if (course == null) return NotFound();
+ [HttpGet]
+ [Authorize]
+ public async Task GetAllCourses()
+ {
+ var courses = await _coursesClient.GetAllCourses();
+ var result = await GetCoursePreviews(courses);
+ return result;
+ }
- var studentIds = course.CourseMates.Select(t => t.StudentId).ToArray();
- var getStudentsTask = AuthServiceClient.GetAccountsData(studentIds);
- var getMentorsTask = AuthServiceClient.GetAccountsData(course.MentorIds);
+ [HttpGet("{courseId}")]
+ [ProducesResponseType(typeof(CourseViewModel), (int)HttpStatusCode.OK)]
+ public async Task GetCourseData(long courseId)
+ {
+ var course = await _coursesClient.GetCourseById(courseId, UserId);
+ if (course == null) return NotFound();
- await Task.WhenAll(getStudentsTask, getMentorsTask);
+ var studentIds = course.CourseMates.Select(t => t.StudentId).ToArray();
+ var getStudentsTask = AuthServiceClient.GetAccountsData(studentIds);
+ var getMentorsTask = AuthServiceClient.GetAccountsData(course.MentorIds);
- var students = getStudentsTask.Result;
+ await Task.WhenAll(getStudentsTask, getMentorsTask);
+ var students = getStudentsTask.Result;
- var acceptedStudents = new List();
- var newStudents = new List();
- for (var i = 0; i < students.Length; i++)
+ var acceptedStudents = new List();
+ var newStudents = new List();
+ for (var i = 0; i < students.Length; i++)
+ {
+ if (!(students[i] is { } student)) continue;
+ if (course.CourseMates[i].IsAccepted)
{
- if (!(students[i] is { } student)) continue;
- if (course.CourseMates[i].IsAccepted) acceptedStudents.Add(student);
- else newStudents.Add(student);
+ acceptedStudents.Add(students[i]);
}
-
- var result = new CourseViewModel
+ else
{
- Id = courseId,
- Name = course.Name,
- GroupName = course.GroupName,
- Mentors = getMentorsTask.Result.Where(t => t != null).ToArray(),
- AcceptedStudents = acceptedStudents.ToArray(),
- NewStudents = newStudents.ToArray(),
- Homeworks = course.Homeworks,
- IsCompleted = course.IsCompleted,
- IsOpen = course.IsOpen,
- };
-
- return Ok(result);
+ newStudents.Add(student);
+ }
}
- [HttpDelete("{courseId}")]
- [Authorize(Roles = Roles.LecturerRole)]
- public async Task DeleteCourse(long courseId)
+ var result = new CourseViewModel
{
- await _coursesClient.DeleteCourse(courseId);
- return Ok();
- }
+ Id = courseId,
+ Name = course.Name,
+ GroupName = course.GroupName,
+ Mentors = getMentorsTask.Result.Where(t => t != null).ToArray(),
+ AcceptedStudents = acceptedStudents.ToArray(),
+ NewStudents = newStudents.ToArray(),
+ Homeworks = course.Homeworks,
+ IsCompleted = course.IsCompleted,
+ IsOpen = course.IsOpen,
+ };
+
+ return Ok(result);
+ }
- [HttpPost("create")]
- [Authorize(Roles = Roles.LecturerRole)]
- [ProducesResponseType(typeof(long), (int)HttpStatusCode.OK)]
- public async Task CreateCourse(CreateCourseViewModel model)
- {
- var result = await _coursesClient.CreateCourse(model, UserId);
- return Ok(result);
- }
+ [HttpDelete("{courseId}")]
+ [Authorize(Roles = Roles.LecturerRole)]
+ public async Task DeleteCourse(long courseId)
+ {
+ await _coursesClient.DeleteCourse(courseId);
+ return Ok();
+ }
- [HttpPost("update/{courseId}")]
- [Authorize(Roles = Roles.LecturerRole)]
- public async Task UpdateCourse(UpdateCourseViewModel model, long courseId)
- {
- await _coursesClient.UpdateCourse(model, courseId);
- return Ok();
- }
+ [HttpPost("create")]
+ [Authorize(Roles = Roles.LecturerRole)]
+ [ProducesResponseType(typeof(long), (int)HttpStatusCode.OK)]
+ public async Task CreateCourse(CreateCourseViewModel model)
+ {
+ var result = await _coursesClient.CreateCourse(model, UserId);
+ return Ok(result);
+ }
- [HttpPost("signInCourse/{courseId}")]
- [Authorize]
- public async Task SignInCourse(long courseId)
- {
- await _coursesClient.SignInCourse(courseId, UserId);
- return Ok();
- }
+ [HttpPost("update/{courseId}")]
+ [Authorize(Roles = Roles.LecturerRole)]
+ public async Task UpdateCourse(UpdateCourseViewModel model, long courseId)
+ {
+ await _coursesClient.UpdateCourse(model, courseId);
+ return Ok();
+ }
- [HttpPost("acceptStudent/{courseId}/{studentId}")]
- [Authorize(Roles = Roles.LecturerRole)]
- public async Task AcceptStudent(long courseId, string studentId)
- {
- await _coursesClient.AcceptStudent(courseId, studentId);
- return Ok();
- }
+ [HttpPost("signInCourse/{courseId}")]
+ [Authorize]
+ public async Task SignInCourse(long courseId)
+ {
+ await _coursesClient.SignInCourse(courseId, UserId);
+ return Ok();
+ }
- [HttpPost("rejectStudent/{courseId}/{studentId}")]
- [Authorize(Roles = Roles.LecturerRole)]
- public async Task RejectStudent(long courseId, string studentId)
- {
- await _coursesClient.RejectStudent(courseId, studentId);
- return Ok();
- }
+ [HttpPost("acceptStudent/{courseId}/{studentId}")]
+ [Authorize(Roles = Roles.LecturerRole)]
+ public async Task AcceptStudent(long courseId, string studentId)
+ {
+ await _coursesClient.AcceptStudent(courseId, studentId);
+ return Ok();
+ }
- [HttpGet("userCourses")]
- [Authorize]
- public async Task GetAllUserCourses()
- {
- var userCourses = await _coursesClient.GetAllUserCourses();
- var result = await GetCoursePreviews(userCourses);
- return result;
- }
+ [HttpPost("rejectStudent/{courseId}/{studentId}")]
+ [Authorize(Roles = Roles.LecturerRole)]
+ public async Task RejectStudent(long courseId, string studentId)
+ {
+ await _coursesClient.RejectStudent(courseId, studentId);
+ return Ok();
+ }
- [HttpGet("acceptLecturer/{courseId}/{lecturerEmail}")]
- [Authorize(Roles = Roles.LecturerRole)]
- public async Task AcceptLecturer(long courseId, string lecturerEmail)
- {
- await _coursesClient.AcceptLecturer(courseId, lecturerEmail);
- return Ok();
- }
+ [HttpGet("userCourses")]
+ [Authorize]
+ public async Task GetAllUserCourses()
+ {
+ var userCourses = await _coursesClient.GetAllUserCourses();
+ var result = await GetCoursePreviews(userCourses);
+ return result;
+ }
- [HttpGet("getLecturersAvailableForCourse/{courseId}")]
- [Authorize(Roles = Roles.LecturerRole)]
- [ProducesResponseType(typeof(AccountDataDto[]), (int)HttpStatusCode.OK)]
- public async Task GetLecturersAvailableForCourse(long courseId)
- {
- var result = await _coursesClient.GetLecturersAvailableForCourse(courseId);
- return Ok(result.Value);
- }
+ [HttpGet("acceptLecturer/{courseId}/{lecturerEmail}")]
+ [Authorize(Roles = Roles.LecturerRole)]
+ public async Task AcceptLecturer(long courseId, string lecturerEmail)
+ {
+ await _coursesClient.AcceptLecturer(courseId, lecturerEmail);
+ return Ok();
+ }
+
+ [HttpGet("getLecturersAvailableForCourse/{courseId}")]
+ [Authorize(Roles = Roles.LecturerRole)]
+ [ProducesResponseType(typeof(AccountDataDto[]), (int)HttpStatusCode.OK)]
+ public async Task GetLecturersAvailableForCourse(long courseId)
+ {
+ var result = await _coursesClient.GetLecturersAvailableForCourse(courseId);
+ return Ok(result.Value);
}
-}
+}
\ No newline at end of file
diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/HomeworksController.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/HomeworksController.cs
index 2a7d271af..49c1244bf 100644
--- a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/HomeworksController.cs
+++ b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/HomeworksController.cs
@@ -6,51 +6,50 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
-namespace HwProj.APIGateway.API.Controllers
+namespace HwProj.APIGateway.API.Controllers;
+
+[Route("api/[controller]")]
+[ApiController]
+public class HomeworksController : ControllerBase
{
- [Route("api/[controller]")]
- [ApiController]
- public class HomeworksController : ControllerBase
- {
- private readonly ICoursesServiceClient _coursesClient;
+ private readonly ICoursesServiceClient _coursesClient;
- public HomeworksController(ICoursesServiceClient coursesClient)
- {
- _coursesClient = coursesClient;
- }
+ public HomeworksController(ICoursesServiceClient coursesClient)
+ {
+ _coursesClient = coursesClient;
+ }
- [HttpGet("get/{homeworkId}")]
- [Authorize]
- [ProducesResponseType(typeof(HomeworkViewModel), (int)HttpStatusCode.OK)]
- public async Task GetHomework(long homeworkId)
- {
- var result = await _coursesClient.GetHomework(homeworkId);
- return Ok(result);
- }
+ [HttpGet("get/{homeworkId}")]
+ [Authorize]
+ [ProducesResponseType(typeof(HomeworkViewModel), (int)HttpStatusCode.OK)]
+ public async Task GetHomework(long homeworkId)
+ {
+ var result = await _coursesClient.GetHomework(homeworkId);
+ return Ok(result);
+ }
- [HttpPost("{courseId}/add")]
- [Authorize(Roles = Roles.LecturerRole)]
- [ProducesResponseType(typeof(long), (int)HttpStatusCode.OK)]
- public async Task AddHomework(CreateHomeworkViewModel homeworkViewModel, long courseId)
- {
- var result = await _coursesClient.AddHomeworkToCourse(homeworkViewModel, courseId);
- return Ok(result.Value);
- }
+ [HttpPost("{courseId}/add")]
+ [Authorize(Roles = Roles.LecturerRole)]
+ [ProducesResponseType(typeof(long), (int)HttpStatusCode.OK)]
+ public async Task AddHomework(CreateHomeworkViewModel homeworkViewModel, long courseId)
+ {
+ var result = await _coursesClient.AddHomeworkToCourse(homeworkViewModel, courseId);
+ return Ok(result.Value);
+ }
- [HttpDelete("delete/{homeworkId}")]
- [Authorize(Roles = Roles.LecturerRole)]
- public async Task DeleteHomework(long homeworkId)
- {
- await _coursesClient.DeleteHomework(homeworkId);
- return Ok();
- }
+ [HttpDelete("delete/{homeworkId}")]
+ [Authorize(Roles = Roles.LecturerRole)]
+ public async Task DeleteHomework(long homeworkId)
+ {
+ await _coursesClient.DeleteHomework(homeworkId);
+ return Ok();
+ }
- [HttpPut("update/{homeworkId}")]
- [Authorize(Roles = Roles.LecturerRole)]
- public async Task UpdateHomework(CreateHomeworkViewModel homeworkViewModel, long homeworkId)
- {
- await _coursesClient.UpdateHomework(homeworkViewModel, homeworkId);
- return Ok();
- }
+ [HttpPut("update/{homeworkId}")]
+ [Authorize(Roles = Roles.LecturerRole)]
+ public async Task UpdateHomework(CreateHomeworkViewModel homeworkViewModel, long homeworkId)
+ {
+ await _coursesClient.UpdateHomework(homeworkViewModel, homeworkId);
+ return Ok();
}
-}
+}
\ No newline at end of file
diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/NotificationsController.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/NotificationsController.cs
index 01bab40a8..f19357f40 100644
--- a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/NotificationsController.cs
+++ b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/NotificationsController.cs
@@ -5,40 +5,39 @@
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
-namespace HwProj.APIGateway.API.Controllers
+namespace HwProj.APIGateway.API.Controllers;
+
+[Route("api/[controller]")]
+[Authorize]
+[ApiController]
+public class NotificationsController : AggregationController
{
- [Route("api/[controller]")]
- [Authorize]
- [ApiController]
- public class NotificationsController : AggregationController
- {
- private readonly INotificationsServiceClient _notificationsClient;
+ private readonly INotificationsServiceClient _notificationsClient;
- public NotificationsController(INotificationsServiceClient notificationsClient) : base(null)
- {
- _notificationsClient = notificationsClient;
- }
+ public NotificationsController(INotificationsServiceClient notificationsClient) : base(null)
+ {
+ _notificationsClient = notificationsClient;
+ }
- [HttpGet("getNewNotificationsCount")]
- public async Task GetNewNotificationsCount()
- {
- var count = await _notificationsClient.GetNewNotificationsCount(UserId);
- return count;
- }
+ [HttpGet("getNewNotificationsCount")]
+ public async Task GetNewNotificationsCount()
+ {
+ var count = await _notificationsClient.GetNewNotificationsCount(UserId);
+ return count;
+ }
- [HttpGet("get")]
- [ProducesResponseType(typeof(CategorizedNotifications[]), (int)HttpStatusCode.OK)]
- public async Task Get()
- {
- var result = await _notificationsClient.Get(UserId);
- return Ok(result);
- }
+ [HttpGet("get")]
+ [ProducesResponseType(typeof(CategorizedNotifications[]), (int)HttpStatusCode.OK)]
+ public async Task Get()
+ {
+ var result = await _notificationsClient.Get(UserId);
+ return Ok(result);
+ }
- [HttpPut("markAsSeen")]
- public async Task MarkAsSeen([FromBody] long[] notificationIds)
- {
- await _notificationsClient.MarkAsSeen(UserId, notificationIds);
- return Ok();
- }
+ [HttpPut("markAsSeen")]
+ public async Task MarkAsSeen([FromBody] long[] notificationIds)
+ {
+ await _notificationsClient.MarkAsSeen(UserId, notificationIds);
+ return Ok();
}
-}
+}
\ No newline at end of file
diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/SolutionsController.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/SolutionsController.cs
index 5aa505dcf..984337fef 100644
--- a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/SolutionsController.cs
+++ b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/SolutionsController.cs
@@ -13,170 +13,169 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
-namespace HwProj.APIGateway.API.Controllers
-{
- [Route("api/[controller]")]
- [ApiController]
- [ForbiddenExceptionFilter]
- public class SolutionsController : AggregationController
- {
- private readonly ISolutionsServiceClient _solutionsClient;
- private readonly ICoursesServiceClient _coursesServiceClient;
+namespace HwProj.APIGateway.API.Controllers;
- public SolutionsController(ISolutionsServiceClient solutionsClient, IAuthServiceClient authServiceClient,
- ICoursesServiceClient coursesServiceClient) :
- base(authServiceClient)
- {
- _solutionsClient = solutionsClient;
- _coursesServiceClient = coursesServiceClient;
- }
+[Route("api/[controller]")]
+[ApiController]
+[ForbiddenExceptionFilter]
+public class SolutionsController : AggregationController
+{
+ private readonly ISolutionsServiceClient _solutionsClient;
+ private readonly ICoursesServiceClient _coursesServiceClient;
- [HttpGet]
- [ProducesResponseType(typeof(Solution[]), (int)HttpStatusCode.OK)]
- public async Task GetAllSolutions()
- {
- var result = await _solutionsClient.GetAllSolutions();
- return Ok(result);
- }
+ public SolutionsController(ISolutionsServiceClient solutionsClient, IAuthServiceClient authServiceClient,
+ ICoursesServiceClient coursesServiceClient) :
+ base(authServiceClient)
+ {
+ _solutionsClient = solutionsClient;
+ _coursesServiceClient = coursesServiceClient;
+ }
- [HttpGet("{solutionId}")]
- [ProducesResponseType(typeof(Solution), (int)HttpStatusCode.OK)]
- public async Task GetSolutionById(long solutionId)
- {
- var result = await _solutionsClient.GetSolutionById(solutionId);
- return result == null
- ? NotFound() as IActionResult
- : Ok(result);
- }
+ [HttpGet]
+ [ProducesResponseType(typeof(Solution[]), (int)HttpStatusCode.OK)]
+ public async Task GetAllSolutions()
+ {
+ var result = await _solutionsClient.GetAllSolutions();
+ return Ok(result);
+ }
- [HttpGet("taskSolution/{taskId}/{studentId}")]
- [Authorize]
- public async Task GetStudentSolution(long taskId, string studentId)
- {
- var getSolutionsTask = _solutionsClient.GetUserSolutions(taskId, studentId);
- var getUserTask = AuthServiceClient.GetAccountData(studentId);
+ [HttpGet("{solutionId}")]
+ [ProducesResponseType(typeof(Solution), (int)HttpStatusCode.OK)]
+ public async Task GetSolutionById(long solutionId)
+ {
+ var result = await _solutionsClient.GetSolutionById(solutionId);
+ return result == null
+ ? NotFound()
+ : Ok(result);
+ }
- await Task.WhenAll(getSolutionsTask, getUserTask);
+ [HttpGet("taskSolution/{taskId}/{studentId}")]
+ [Authorize]
+ public async Task GetStudentSolution(long taskId, string studentId)
+ {
+ var getSolutionsTask = _solutionsClient.GetUserSolutions(taskId, studentId);
+ var getUserTask = AuthServiceClient.GetAccountData(studentId);
- var result = new UserTaskSolutions
- {
- User = getUserTask.Result,
- Solutions = getSolutionsTask.Result,
- };
- return result;
- }
+ await Task.WhenAll(getSolutionsTask, getUserTask);
- [HttpPost("{taskId}")]
- [Authorize]
- [ProducesResponseType(typeof(long), (int)HttpStatusCode.OK)]
- public async Task PostSolution(SolutionViewModel model, long taskId)
+ var result = new UserTaskSolutions
{
- model.StudentId = UserId;
- var result = await _solutionsClient.PostSolution(model, taskId);
- return Ok(result);
- }
+ User = getUserTask.Result,
+ Solutions = getSolutionsTask.Result,
+ };
+ return result;
+ }
- [HttpPost("rateSolution/{solutionId}/{newRating}")]
- [Authorize(Roles = Roles.LecturerRole)]
- public async Task RateSolution(long solutionId, int newRating,
- [FromQuery] string lecturerComment)
- {
- await _solutionsClient.RateSolution(solutionId, newRating, lecturerComment, UserId);
- return Ok();
- }
+ [HttpPost("{taskId}")]
+ [Authorize]
+ [ProducesResponseType(typeof(long), (int)HttpStatusCode.OK)]
+ public async Task PostSolution(SolutionViewModel model, long taskId)
+ {
+ model.StudentId = UserId;
+ var result = await _solutionsClient.PostSolution(model, taskId);
+ return Ok(result);
+ }
- [HttpPost("markSolutionFinal/{solutionId}")]
- [Authorize(Roles = Roles.LecturerRole)]
- public async Task MarkSolution(long solutionId)
- {
- await _solutionsClient.MarkSolution(solutionId);
- return Ok();
- }
+ [HttpPost("rateSolution/{solutionId}/{newRating}")]
+ [Authorize(Roles = Roles.LecturerRole)]
+ public async Task RateSolution(long solutionId, int newRating,
+ [FromQuery] string lecturerComment)
+ {
+ await _solutionsClient.RateSolution(solutionId, newRating, lecturerComment, UserId);
+ return Ok();
+ }
- [HttpDelete("delete/{solutionId}")]
- [Authorize(Roles = Roles.LecturerRole)]
- public async Task DeleteSolution(long solutionId)
- {
- await _solutionsClient.DeleteSolution(solutionId);
- return Ok();
- }
+ [HttpPost("markSolutionFinal/{solutionId}")]
+ [Authorize(Roles = Roles.LecturerRole)]
+ public async Task MarkSolution(long solutionId)
+ {
+ await _solutionsClient.MarkSolution(solutionId);
+ return Ok();
+ }
- [HttpPost("{groupId}/{taskId}")]
- [Authorize]
- [ProducesResponseType(typeof(long), (int)HttpStatusCode.OK)]
- public async Task PostGroupSolution(SolutionViewModel model, long taskId, long groupId)
- {
- var result = await _solutionsClient.PostGroupSolution(model, taskId, groupId);
- return Ok(result);
- }
+ [HttpDelete("delete/{solutionId}")]
+ [Authorize(Roles = Roles.LecturerRole)]
+ public async Task DeleteSolution(long solutionId)
+ {
+ await _solutionsClient.DeleteSolution(solutionId);
+ return Ok();
+ }
- [HttpGet("{groupId}/taskSolutions/{taskId}")]
- [Authorize]
- [ProducesResponseType(typeof(Solution[]), (int)HttpStatusCode.OK)]
- public async Task GetGroupSolutions(long groupId, long taskId)
- {
- var result = await _solutionsClient.GetTaskSolutions(groupId, taskId);
- return result == null
- ? NotFound() as IActionResult
- : Ok(result);
- }
+ [HttpPost("{groupId}/{taskId}")]
+ [Authorize]
+ [ProducesResponseType(typeof(long), (int)HttpStatusCode.OK)]
+ public async Task PostGroupSolution(SolutionViewModel model, long taskId, long groupId)
+ {
+ var result = await _solutionsClient.PostGroupSolution(model, taskId, groupId);
+ return Ok(result);
+ }
- [HttpGet("unratedSolutions")]
- [Authorize(Roles = Roles.LecturerRole)]
- public async Task GetUnratedSolutions(long? taskId)
- {
- var mentorCourses = await _coursesServiceClient.GetAllUserCourses();
- var tasks = FilterTasks(mentorCourses, taskId).ToDictionary(t => t.taskId, t => t.data);
+ [HttpGet("{groupId}/taskSolutions/{taskId}")]
+ [Authorize]
+ [ProducesResponseType(typeof(Solution[]), (int)HttpStatusCode.OK)]
+ public async Task GetGroupSolutions(long groupId, long taskId)
+ {
+ var result = await _solutionsClient.GetTaskSolutions(groupId, taskId);
+ return result == null
+ ? NotFound()
+ : Ok(result);
+ }
- var taskIds = tasks.Select(t => t.Key).ToArray();
- var solutions = await _solutionsClient.GetAllUnratedSolutionsForTasks(taskIds);
+ [HttpGet("unratedSolutions")]
+ [Authorize(Roles = Roles.LecturerRole)]
+ public async Task GetUnratedSolutions(long? taskId)
+ {
+ var mentorCourses = await _coursesServiceClient.GetAllUserCourses();
+ var tasks = FilterTasks(mentorCourses, taskId).ToDictionary(t => t.taskId, t => t.data);
- var studentIds = solutions.Select(t => t.StudentId).Distinct().ToArray();
- var accountsData = await AuthServiceClient.GetAccountsData(studentIds);
+ var taskIds = tasks.Select(t => t.Key).ToArray();
+ var solutions = await _solutionsClient.GetAllUnratedSolutionsForTasks(taskIds);
- var unratedSolutions = solutions
- .Join(accountsData, s => s.StudentId, s => s.UserId, (solution, account) =>
- {
- var (course, homeworkTitle, task) = tasks[solution.TaskId];
- return new SolutionPreviewView
- {
- Student = account,
- CourseTitle = $"{course.Name} / {course.GroupName}",
- CourseId = course.Id,
- HomeworkTitle = homeworkTitle,
- TaskTitle = task.Title,
- TaskId = task.Id,
- PublicationDate = solution.PublicationDate,
- IsFirstTry = solution.IsFirstTry,
- SentAfterDeadline = solution.IsFirstTry && task.DeadlineDate != null &&
- solution.PublicationDate > task.DeadlineDate
- };
- })
- .ToArray();
-
- return new UnratedSolutionPreviews
- {
- UnratedSolutions = unratedSolutions,
- };
- }
+ var studentIds = solutions.Select(t => t.StudentId).Distinct().ToArray();
+ var accountsData = await AuthServiceClient.GetAccountsData(studentIds);
- private static IEnumerable<(long taskId,
- (CourseDTO course, string homeworkTitle, HomeworkTaskViewModel task) data)>
- FilterTasks(CourseDTO[] courses, long? taskId)
- {
- foreach (var course in courses)
- foreach (var homework in course.Homeworks)
- foreach (var task in homework.Tasks)
+ var unratedSolutions = solutions
+ .Join(accountsData, s => s.StudentId, s => s.UserId, (solution, account) =>
{
- if (taskId is { } id && task.Id == id)
+ var (course, homeworkTitle, task) = tasks[solution.TaskId];
+ return new SolutionPreviewView
{
- yield return (task.Id, (course, homework.Title, task));
- yield break;
- }
+ Student = account,
+ CourseTitle = $"{course.Name} / {course.GroupName}",
+ CourseId = course.Id,
+ HomeworkTitle = homeworkTitle,
+ TaskTitle = task.Title,
+ TaskId = task.Id,
+ PublicationDate = solution.PublicationDate,
+ IsFirstTry = solution.IsFirstTry,
+ SentAfterDeadline = solution.IsFirstTry && task.DeadlineDate != null &&
+ solution.PublicationDate > task.DeadlineDate
+ };
+ })
+ .ToArray();
+
+ return new UnratedSolutionPreviews
+ {
+ UnratedSolutions = unratedSolutions,
+ };
+ }
- if (!taskId.HasValue)
- yield return (task.Id, (course, homework.Title, task));
+ private static IEnumerable<(long taskId,
+ (CourseDTO course, string homeworkTitle, HomeworkTaskViewModel task) data)>
+ FilterTasks(CourseDTO[] courses, long? taskId)
+ {
+ foreach (var course in courses)
+ foreach (var homework in course.Homeworks)
+ foreach (var task in homework.Tasks)
+ {
+ if (taskId is { } id && task.Id == id)
+ {
+ yield return (task.Id, (course, homework.Title, task));
+ yield break;
}
+
+ if (!taskId.HasValue)
+ yield return (task.Id, (course, homework.Title, task));
}
}
-}
+}
\ No newline at end of file
diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/StatisticsController.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/StatisticsController.cs
index 77d2a1945..84786faa3 100644
--- a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/StatisticsController.cs
+++ b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/StatisticsController.cs
@@ -6,39 +6,38 @@
using HwProj.SolutionsService.Client;
using Microsoft.AspNetCore.Mvc;
-namespace HwProj.APIGateway.API.Controllers
+namespace HwProj.APIGateway.API.Controllers;
+
+[Route("api/[controller]")]
+[ApiController]
+public class StatisticsController : AggregationController
{
- [Route("api/[controller]")]
- [ApiController]
- public class StatisticsController : AggregationController
- {
- private readonly ISolutionsServiceClient _solutionClient;
+ private readonly ISolutionsServiceClient _solutionClient;
- public StatisticsController(ISolutionsServiceClient solutionClient, IAuthServiceClient authServiceClient) :
- base(authServiceClient)
- {
- _solutionClient = solutionClient;
- }
+ public StatisticsController(ISolutionsServiceClient solutionClient, IAuthServiceClient authServiceClient) :
+ base(authServiceClient)
+ {
+ _solutionClient = solutionClient;
+ }
- [HttpGet("{courseId}")]
- [ProducesResponseType(typeof(StatisticsCourseMatesModel[]), (int)HttpStatusCode.OK)]
- public async Task GetCourseStatistics(long courseId)
- {
- var statistics = await _solutionClient.GetCourseStatistics(courseId, UserId);
- if (statistics == null) return Forbid();
+ [HttpGet("{courseId}")]
+ [ProducesResponseType(typeof(StatisticsCourseMatesModel[]), (int)HttpStatusCode.OK)]
+ public async Task GetCourseStatistics(long courseId)
+ {
+ var statistics = await _solutionClient.GetCourseStatistics(courseId, UserId);
+ if (statistics == null) return Forbid();
- var studentIds = statistics.Select(t => t.StudentId).ToArray();
- var students = await AuthServiceClient.GetAccountsData(studentIds);
+ var studentIds = statistics.Select(t => t.StudentId).ToArray();
+ var students = await AuthServiceClient.GetAccountsData(studentIds);
- var result = statistics.Zip(students, (stats, student) => new StatisticsCourseMatesModel
- {
- Id = student.UserId,
- Name = student.Name,
- Surname = student.Surname,
- Homeworks = stats.Homeworks
- }).OrderBy(t => t.Surname).ThenBy(t => t.Name);
+ var result = statistics.Zip(students, (stats, student) => new StatisticsCourseMatesModel
+ {
+ Id = student.UserId,
+ Name = student.Name,
+ Surname = student.Surname,
+ Homeworks = stats.Homeworks
+ }).OrderBy(t => t.Surname).ThenBy(t => t.Name);
- return Ok(result);
- }
+ return Ok(result);
}
}
diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/SystemController.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/SystemController.cs
index 61fb17326..a1b64115f 100644
--- a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/SystemController.cs
+++ b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/SystemController.cs
@@ -6,60 +6,59 @@
using HwProj.SolutionsService.Client;
using Microsoft.AspNetCore.Mvc;
-namespace HwProj.APIGateway.API.Controllers
+namespace HwProj.APIGateway.API.Controllers;
+
+[Route("api/[controller]")]
+[ApiController]
+public class SystemController : AggregationController
{
- [Route("api/[controller]")]
- [ApiController]
- public class SystemController : AggregationController
- {
- private readonly ICoursesServiceClient _coursesServiceClient;
- private readonly INotificationsServiceClient _notificationsServiceClient;
- private readonly ISolutionsServiceClient _solutionsServiceClient;
+ private readonly ICoursesServiceClient _coursesServiceClient;
+ private readonly INotificationsServiceClient _notificationsServiceClient;
+ private readonly ISolutionsServiceClient _solutionsServiceClient;
- public SystemController(
- IAuthServiceClient authServiceClient,
- ICoursesServiceClient coursesServiceClient,
- INotificationsServiceClient notificationsServiceClient,
- ISolutionsServiceClient solutionsServiceClient) : base(authServiceClient)
- {
- _coursesServiceClient = coursesServiceClient;
- _notificationsServiceClient = notificationsServiceClient;
- _solutionsServiceClient = solutionsServiceClient;
- }
+ public SystemController(
+ IAuthServiceClient authServiceClient,
+ ICoursesServiceClient coursesServiceClient,
+ INotificationsServiceClient notificationsServiceClient,
+ ISolutionsServiceClient solutionsServiceClient) : base(authServiceClient)
+ {
+ _coursesServiceClient = coursesServiceClient;
+ _notificationsServiceClient = notificationsServiceClient;
+ _solutionsServiceClient = solutionsServiceClient;
+ }
- [HttpGet("status")]
- public async Task Status()
- {
- var authPing = AuthServiceClient.Ping();
- var coursesPing = _coursesServiceClient.Ping();
- var notificationsPing = _notificationsServiceClient.Ping();
- var solutionsPing = _solutionsServiceClient.Ping();
+ [HttpGet("status")]
+ public async Task Status()
+ {
+ var authPing = AuthServiceClient.Ping();
+ var coursesPing = _coursesServiceClient.Ping();
+ var notificationsPing = _notificationsServiceClient.Ping();
+ var solutionsPing = _solutionsServiceClient.Ping();
- await Task.WhenAll(authPing, coursesPing, notificationsPing, solutionsPing);
+ await Task.WhenAll(authPing, coursesPing, notificationsPing, solutionsPing);
- return new[]
+ return new[]
+ {
+ new SystemInfo
+ {
+ Service = "Auth Service",
+ IsAvailable = authPing.Result
+ },
+ new SystemInfo
+ {
+ Service = "Courses Service",
+ IsAvailable = coursesPing.Result
+ },
+ new SystemInfo
+ {
+ Service = "Notifications Service",
+ IsAvailable = notificationsPing.Result
+ },
+ new SystemInfo
{
- new SystemInfo
- {
- Service = "Auth Service",
- IsAvailable = authPing.Result
- },
- new SystemInfo
- {
- Service = "Courses Service",
- IsAvailable = coursesPing.Result
- },
- new SystemInfo
- {
- Service = "Notifications Service",
- IsAvailable = notificationsPing.Result
- },
- new SystemInfo
- {
- Service = "Solutions Service",
- IsAvailable = solutionsPing.Result
- },
- };
- }
+ Service = "Solutions Service",
+ IsAvailable = solutionsPing.Result
+ },
+ };
}
-}
+}
\ No newline at end of file
diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/TasksController.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/TasksController.cs
index b057a2b05..d46ce7340 100644
--- a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/TasksController.cs
+++ b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/TasksController.cs
@@ -6,52 +6,51 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
-namespace HwProj.APIGateway.API.Controllers
+namespace HwProj.APIGateway.API.Controllers;
+
+[Route("api/[controller]")]
+[ApiController]
+public class TasksController : ControllerBase
{
- [Route("api/[controller]")]
- [ApiController]
- public class TasksController : ControllerBase
- {
- private readonly ICoursesServiceClient _coursesClient;
+ private readonly ICoursesServiceClient _coursesClient;
- public TasksController(ICoursesServiceClient coursesClient)
- {
- _coursesClient = coursesClient;
- }
+ public TasksController(ICoursesServiceClient coursesClient)
+ {
+ _coursesClient = coursesClient;
+ }
- [HttpGet("get/{taskId}")]
- [ProducesResponseType(typeof(HomeworkTaskViewModel), (int)HttpStatusCode.OK)]
- public async Task GetTask(long taskId)
- {
- var result = await _coursesClient.GetTask(taskId);
- return result == null
- ? NotFound() as IActionResult
- : Ok(result);
- }
+ [HttpGet("get/{taskId}")]
+ [ProducesResponseType(typeof(HomeworkTaskViewModel), (int)HttpStatusCode.OK)]
+ public async Task GetTask(long taskId)
+ {
+ var result = await _coursesClient.GetTask(taskId);
+ return result == null
+ ? NotFound()
+ : Ok(result);
+ }
- [HttpPost("add/{homeworkId}")]
- [Authorize(Roles = Roles.LecturerRole)]
- [ProducesResponseType(typeof(long), (int)HttpStatusCode.OK)]
- public async Task AddTask(CreateTaskViewModel taskViewModel, long homeworkId)
- {
- var result = await _coursesClient.AddTask(taskViewModel, homeworkId);
- return Ok(result.Value);
- }
+ [HttpPost("add/{homeworkId}")]
+ [Authorize(Roles = Roles.LecturerRole)]
+ [ProducesResponseType(typeof(long), (int)HttpStatusCode.OK)]
+ public async Task AddTask(CreateTaskViewModel taskViewModel, long homeworkId)
+ {
+ var result = await _coursesClient.AddTask(taskViewModel, homeworkId);
+ return Ok(result.Value);
+ }
- [HttpDelete("delete/{taskId}")]
- [Authorize(Roles = Roles.LecturerRole)]
- public async Task DeleteTask(long taskId)
- {
- await _coursesClient.DeleteTask(taskId);
- return Ok();
- }
+ [HttpDelete("delete/{taskId}")]
+ [Authorize(Roles = Roles.LecturerRole)]
+ public async Task DeleteTask(long taskId)
+ {
+ await _coursesClient.DeleteTask(taskId);
+ return Ok();
+ }
- [HttpPut("update/{taskId}")]
- [Authorize(Roles = Roles.LecturerRole)]
- public async Task UpdateTask(CreateTaskViewModel taskViewModel, long taskId)
- {
- await _coursesClient.UpdateTask(taskViewModel, taskId);
- return Ok();
- }
+ [HttpPut("update/{taskId}")]
+ [Authorize(Roles = Roles.LecturerRole)]
+ public async Task UpdateTask(CreateTaskViewModel taskViewModel, long taskId)
+ {
+ await _coursesClient.UpdateTask(taskViewModel, taskId);
+ return Ok();
}
-}
+}
\ No newline at end of file
diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Dockerfile b/HwProj.APIGateway/HwProj.APIGateway.API/Dockerfile
index 002d9d289..06712d702 100644
--- a/HwProj.APIGateway/HwProj.APIGateway.API/Dockerfile
+++ b/HwProj.APIGateway/HwProj.APIGateway.API/Dockerfile
@@ -1,7 +1,4 @@
-FROM mcr.microsoft.com/dotnet/core/aspnet:2.2-stretch-slim AS base
-WORKDIR /app
-
-FROM mcr.microsoft.com/dotnet/core/sdk:2.2-stretch AS build
+FROM mcr.microsoft.com/dotnet/sdk:6.0 as build
WORKDIR /src
COPY ["HwProj.APIGateway/HwProj.APIGateway.API/HwProj.APIGateway.API.csproj", "HwProj.APIGateway/HwProj.APIGateway.API/"]
COPY ["HwProj.NotificationsService/HwProj.NotificationsService.Client/HwProj.NotificationsService.Client.csproj", "HwProj.NotificationsService/HwProj.NotificationsService.Client/"]
@@ -14,15 +11,11 @@ COPY ["HwProj.CoursesService/HwProj.CoursesService.Client/HwProj.CoursesService.
COPY ["HwProj.AuthService/HwProj.AuthService.Client/HwProj.AuthService.Client.csproj", "HwProj.AuthService/HwProj.AuthService.Client/"]
COPY ["HwProj.SolutionsService/HwProj.SolutionsService.Client/HwProj.SolutionsService.Client.csproj", "HwProj.SolutionsService/HwProj.SolutionsService.Client/"]
COPY ["HwProj.Common/HwProj.Exceptions/HwProj.Exceptions.csproj", "HwProj.Common/HwProj.Exceptions/"]
-RUN dotnet restore "HwProj.APIGateway/HwProj.APIGateway.API/HwProj.APIGateway.API.csproj"
COPY . .
WORKDIR "/src/HwProj.APIGateway/HwProj.APIGateway.API"
-RUN dotnet build "HwProj.APIGateway.API.csproj" -c Release -o /app/build
-
-FROM build AS publish
RUN dotnet publish "HwProj.APIGateway.API.csproj" -c Release -o /app/publish
-FROM base AS final
+FROM build AS final
WORKDIR /app
-COPY --from=publish /app/publish .
-ENTRYPOINT ["dotnet", "HwProj.APIGateway.API.dll"]
+COPY --from=build /app/publish .
+ENTRYPOINT ["dotnet", "HwProj.APIGateway.API.dll"]
\ No newline at end of file
diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/ExceptionFilters/ForbiddenExceptionFilter.cs b/HwProj.APIGateway/HwProj.APIGateway.API/ExceptionFilters/ForbiddenExceptionFilter.cs
index 677cbaa64..74bfcf015 100644
--- a/HwProj.APIGateway/HwProj.APIGateway.API/ExceptionFilters/ForbiddenExceptionFilter.cs
+++ b/HwProj.APIGateway/HwProj.APIGateway.API/ExceptionFilters/ForbiddenExceptionFilter.cs
@@ -3,17 +3,16 @@
using HwProj.Exceptions;
-namespace HwProj.APIGateway.API.ExceptionFilters
+namespace HwProj.APIGateway.API.ExceptionFilters;
+
+public class ForbiddenExceptionFilter : Attribute, IExceptionFilter
{
- public class ForbiddenExceptionFilter : Attribute, IExceptionFilter
+ public void OnException(ExceptionContext context)
{
- public void OnException(ExceptionContext context)
+ if (context.Exception is ForbiddenException)
{
- if (context.Exception is ForbiddenException)
- {
- context.ExceptionHandled = true;
- context.HttpContext.Response.StatusCode = 403;
- }
+ context.ExceptionHandled = true;
+ context.HttpContext.Response.StatusCode = 403;
}
}
}
\ No newline at end of file
diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/HwProj.APIGateway.API.csproj b/HwProj.APIGateway/HwProj.APIGateway.API/HwProj.APIGateway.API.csproj
index 29e5d8b3c..2e077edf3 100644
--- a/HwProj.APIGateway/HwProj.APIGateway.API/HwProj.APIGateway.API.csproj
+++ b/HwProj.APIGateway/HwProj.APIGateway.API/HwProj.APIGateway.API.csproj
@@ -1,7 +1,7 @@
- netcoreapp2.2
+ net6.0
..\..\docker-compose.dcproj
Linux
..\..
@@ -10,10 +10,7 @@
-
-
-
-
+
diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Models/CoursePreviewView.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Models/CoursePreviewView.cs
index 7103dda92..3162b24ae 100644
--- a/HwProj.APIGateway/HwProj.APIGateway.API/Models/CoursePreviewView.cs
+++ b/HwProj.APIGateway/HwProj.APIGateway.API/Models/CoursePreviewView.cs
@@ -1,13 +1,12 @@
using HwProj.Models.AuthService.DTO;
-namespace HwProj.APIGateway.API.Models
+namespace HwProj.APIGateway.API.Models;
+
+public class CoursePreviewView
{
- public class CoursePreviewView
- {
- public long Id { get; set; }
- public string Name { get; set; }
- public string GroupName { get; set; }
- public bool IsCompleted { get; set; }
- public AccountDataDto[] Mentors { get; set; }
- }
-}
+ public long Id { get; set; }
+ public string Name { get; set; }
+ public string GroupName { get; set; }
+ public bool IsCompleted { get; set; }
+ public AccountDataDto[] Mentors { get; set; }
+}
\ No newline at end of file
diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Models/Solutions/SolutionPreviewView.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Models/Solutions/SolutionPreviewView.cs
index 8c7087709..3c50a3071 100644
--- a/HwProj.APIGateway/HwProj.APIGateway.API/Models/Solutions/SolutionPreviewView.cs
+++ b/HwProj.APIGateway/HwProj.APIGateway.API/Models/Solutions/SolutionPreviewView.cs
@@ -1,23 +1,22 @@
using System;
using HwProj.Models.AuthService.DTO;
-namespace HwProj.APIGateway.API.Models.Solutions
-{
- public class SolutionPreviewView
- {
- public AccountDataDto Student { get; set; }
- public string CourseTitle { get; set; }
- public long CourseId { get; set; }
- public string HomeworkTitle { get; set; }
- public string TaskTitle { get; set; }
- public long TaskId { get; set; }
- public DateTime PublicationDate { get; set; }
- public bool IsFirstTry { get; set; }
- public bool SentAfterDeadline { get; set; }
- }
+namespace HwProj.APIGateway.API.Models.Solutions;
- public class UnratedSolutionPreviews
- {
- public SolutionPreviewView[] UnratedSolutions { get; set; }
- }
+public class SolutionPreviewView
+{
+ public AccountDataDto Student { get; set; }
+ public string CourseTitle { get; set; }
+ public long CourseId { get; set; }
+ public string HomeworkTitle { get; set; }
+ public string TaskTitle { get; set; }
+ public long TaskId { get; set; }
+ public DateTime PublicationDate { get; set; }
+ public bool IsFirstTry { get; set; }
+ public bool SentAfterDeadline { get; set; }
}
+
+public class UnratedSolutionPreviews
+{
+ public SolutionPreviewView[] UnratedSolutions { get; set; }
+}
\ No newline at end of file
diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Models/Solutions/UserTaskSolutions.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Models/Solutions/UserTaskSolutions.cs
index 86d69a26e..bc5973ddf 100644
--- a/HwProj.APIGateway/HwProj.APIGateway.API/Models/Solutions/UserTaskSolutions.cs
+++ b/HwProj.APIGateway/HwProj.APIGateway.API/Models/Solutions/UserTaskSolutions.cs
@@ -1,11 +1,10 @@
using HwProj.Models.AuthService.DTO;
using HwProj.Models.SolutionsService;
-namespace HwProj.APIGateway.API.Models.Solutions
+namespace HwProj.APIGateway.API.Models.Solutions;
+
+public class UserTaskSolutions
{
- public class UserTaskSolutions
- {
- public Solution[] Solutions { get; set; }
- public AccountDataDto User { get; set; }
- }
-}
+ public Solution[] Solutions { get; set; }
+ public AccountDataDto User { get; set; }
+}
\ No newline at end of file
diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Models/StatisticsCourseMatesModel.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Models/StatisticsCourseMatesModel.cs
index 386ec0d83..2a7a68283 100644
--- a/HwProj.APIGateway/HwProj.APIGateway.API/Models/StatisticsCourseMatesModel.cs
+++ b/HwProj.APIGateway/HwProj.APIGateway.API/Models/StatisticsCourseMatesModel.cs
@@ -1,13 +1,12 @@
using System.Collections.Generic;
using HwProj.Models.StatisticsService;
-namespace HwProj.APIGateway.API.Models
+namespace HwProj.APIGateway.API.Models;
+
+public class StatisticsCourseMatesModel
{
- public class StatisticsCourseMatesModel
- {
- public string Id { get; set; }
- public string Name { get; set; }
- public string Surname { get; set; }
- public List Homeworks { get; set; } = new List();
- }
-}
+ public string Id { get; set; }
+ public string Name { get; set; }
+ public string Surname { get; set; }
+ public List Homeworks { get; set; } = new();
+}
\ No newline at end of file
diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Models/SystemInfo.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Models/SystemInfo.cs
index 56c142588..1463cc6d0 100644
--- a/HwProj.APIGateway/HwProj.APIGateway.API/Models/SystemInfo.cs
+++ b/HwProj.APIGateway/HwProj.APIGateway.API/Models/SystemInfo.cs
@@ -1,8 +1,7 @@
-namespace HwProj.APIGateway.API.Models
+namespace HwProj.APIGateway.API.Models;
+
+public class SystemInfo
{
- public class SystemInfo
- {
- public string Service { get; set; }
- public bool IsAvailable { get; set; }
- }
-}
+ public string Service { get; set; }
+ public bool IsAvailable { get; set; }
+}
\ No newline at end of file
diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Models/Tasks/TaskDeadlineView.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Models/Tasks/TaskDeadlineView.cs
index f45a58bd3..ef71107b5 100644
--- a/HwProj.APIGateway/HwProj.APIGateway.API/Models/Tasks/TaskDeadlineView.cs
+++ b/HwProj.APIGateway/HwProj.APIGateway.API/Models/Tasks/TaskDeadlineView.cs
@@ -1,13 +1,12 @@
using HwProj.Models.CoursesService.DTO;
using HwProj.Models.SolutionsService;
-namespace HwProj.APIGateway.API.Models.Tasks
+namespace HwProj.APIGateway.API.Models.Tasks;
+
+public class TaskDeadlineView
{
- public class TaskDeadlineView
- {
- public TaskDeadlineDto Deadline { get; set; }
- public SolutionState? SolutionState { get; set; }
- public long? Rating { get; set; }
- public long MaxRating { get; set; }
- }
-}
+ public TaskDeadlineDto Deadline { get; set; }
+ public SolutionState? SolutionState { get; set; }
+ public long? Rating { get; set; }
+ public long MaxRating { get; set; }
+}
\ No newline at end of file
diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Models/UserDataDto.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Models/UserDataDto.cs
index 50aaff051..5cc1d2d2b 100644
--- a/HwProj.APIGateway/HwProj.APIGateway.API/Models/UserDataDto.cs
+++ b/HwProj.APIGateway/HwProj.APIGateway.API/Models/UserDataDto.cs
@@ -1,12 +1,11 @@
using HwProj.APIGateway.API.Models.Tasks;
using HwProj.Models.AuthService.DTO;
-namespace HwProj.APIGateway.API.Models
+namespace HwProj.APIGateway.API.Models;
+
+public class UserDataDto
{
- public class UserDataDto
- {
- public AccountDataDto UserData { get; set; }
- public CoursePreviewView[] Courses { get; set; }
- public TaskDeadlineView[] TaskDeadlines { get; set; }
- }
-}
+ public AccountDataDto UserData { get; set; }
+ public CoursePreviewView[] Courses { get; set; }
+ public TaskDeadlineView[] TaskDeadlines { get; set; }
+}
\ No newline at end of file
diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Program.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Program.cs
index 9378edd4d..f165e74bf 100644
--- a/HwProj.APIGateway/HwProj.APIGateway.API/Program.cs
+++ b/HwProj.APIGateway/HwProj.APIGateway.API/Program.cs
@@ -2,21 +2,20 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
-namespace HwProj.APIGateway.API
+namespace HwProj.APIGateway.API;
+
+public static class Program
{
- public static class Program
+ public static void Main(string[] args)
{
- public static void Main(string[] args)
- {
- WebHost.CreateDefaultBuilder(args)
- .UseStartup()
- .ConfigureAppConfiguration((hostingContext, config) =>
- {
- config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
- .AddEnvironmentVariables();
- })
- .Build()
- .Run();
- }
+ WebHost.CreateDefaultBuilder(args)
+ .UseStartup()
+ .ConfigureAppConfiguration((hostingContext, config) =>
+ {
+ config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
+ .AddEnvironmentVariables();
+ })
+ .Build()
+ .Run();
}
}
diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Startup.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Startup.cs
index 81455dec1..ea6c395e6 100644
--- a/HwProj.APIGateway/HwProj.APIGateway.API/Startup.cs
+++ b/HwProj.APIGateway/HwProj.APIGateway.API/Startup.cs
@@ -10,50 +10,49 @@
using Microsoft.IdentityModel.Tokens;
using HwProj.Utils.Authorization;
-namespace HwProj.APIGateway.API
+namespace HwProj.APIGateway.API;
+
+public class Startup
{
- public class Startup
+ public Startup(IConfiguration configuration)
{
- public Startup(IConfiguration configuration)
- {
- Configuration = configuration;
- }
+ Configuration = configuration;
+ }
- public IConfiguration Configuration { get; }
+ public IConfiguration Configuration { get; }
- public void ConfigureServices(IServiceCollection services)
- {
- services.ConfigureHwProjServices("API Gateway");
+ public void ConfigureServices(IServiceCollection services)
+ {
+ services.ConfigureHwProjServices("API Gateway");
- const string authenticationProviderKey = "GatewayKey";
+ const string authenticationProviderKey = "GatewayKey";
- services.AddAuthentication()
- .AddJwtBearer(authenticationProviderKey, x =>
+ services.AddAuthentication()
+ .AddJwtBearer(authenticationProviderKey, x =>
+ {
+ x.RequireHttpsMetadata = false;
+ x.TokenValidationParameters = new TokenValidationParameters
{
- x.RequireHttpsMetadata = false;
- x.TokenValidationParameters = new TokenValidationParameters
- {
- ValidIssuer = "AuthService",
- ValidateIssuer = true,
- ValidateAudience = false,
- ValidateLifetime = true,
- IssuerSigningKey = AuthorizationKey.SecurityKey,
- ValidateIssuerSigningKey = true
- };
- });
-
- services.AddHttpClient();
- services.AddHttpContextAccessor();
-
- services.AddAuthServiceClient();
- services.AddCoursesServiceClient();
- services.AddSolutionServiceClient();
- services.AddNotificationsServiceClient();
- }
-
- public void Configure(IApplicationBuilder app, IHostingEnvironment env)
- {
- app.ConfigureHwProj(env, "API Gateway");
- }
+ ValidIssuer = "AuthService",
+ ValidateIssuer = true,
+ ValidateAudience = false,
+ ValidateLifetime = true,
+ IssuerSigningKey = AuthorizationKey.SecurityKey,
+ ValidateIssuerSigningKey = true
+ };
+ });
+
+ services.AddHttpClient();
+ services.AddHttpContextAccessor();
+
+ services.AddAuthServiceClient();
+ services.AddCoursesServiceClient();
+ services.AddSolutionServiceClient();
+ services.AddNotificationsServiceClient();
+ }
+
+ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
+ {
+ app.ConfigureHwProj(env, "API Gateway");
}
}
diff --git a/HwProj.AuthService/HwProj.AuthService.API/AppSettings.cs b/HwProj.AuthService/HwProj.AuthService.API/AppSettings.cs
index 2865a8e7a..6300da4f9 100644
--- a/HwProj.AuthService/HwProj.AuthService.API/AppSettings.cs
+++ b/HwProj.AuthService/HwProj.AuthService.API/AppSettings.cs
@@ -1,12 +1,11 @@
-namespace HwProj.AuthService.API
+namespace HwProj.AuthService.API;
+
+public class AppSettings
{
- public class AppSettings
- {
- public string SecurityKey { get; set; }
- public string ApiName { get; set; }
- public string ClientIdGitHub { get; set; }
- public string ClientSecretGitHub { get; set; }
- public double ExpireInForToken { get; set; }
- public double ExpireInForResponse { get; set; }
- }
+ public string SecurityKey { get; set; }
+ public string ApiName { get; set; }
+ public string ClientIdGitHub { get; set; }
+ public string ClientSecretGitHub { get; set; }
+ public double ExpireInForToken { get; set; }
+ public double ExpireInForResponse { get; set; }
}
\ No newline at end of file
diff --git a/HwProj.AuthService/HwProj.AuthService.API/ApplicationProfile.cs b/HwProj.AuthService/HwProj.AuthService.API/ApplicationProfile.cs
index fd607c4a2..eb32a8f82 100644
--- a/HwProj.AuthService/HwProj.AuthService.API/ApplicationProfile.cs
+++ b/HwProj.AuthService/HwProj.AuthService.API/ApplicationProfile.cs
@@ -2,16 +2,15 @@
using HwProj.Models.AuthService.DTO;
using HwProj.Models.AuthService.ViewModels;
-namespace HwProj.AuthService.API
+namespace HwProj.AuthService.API;
+
+public class ApplicationProfile : Profile
{
- public class ApplicationProfile : Profile
+ public ApplicationProfile()
{
- public ApplicationProfile()
- {
- CreateMap();
- CreateMap();
- CreateMap();
- CreateMap();
- }
+ CreateMap();
+ CreateMap();
+ CreateMap();
+ CreateMap();
}
-}
+}
\ No newline at end of file
diff --git a/HwProj.AuthService/HwProj.AuthService.API/Controllers/AccountController.cs b/HwProj.AuthService/HwProj.AuthService.API/Controllers/AccountController.cs
index b3ece17c5..8fb1ab465 100644
--- a/HwProj.AuthService/HwProj.AuthService.API/Controllers/AccountController.cs
+++ b/HwProj.AuthService/HwProj.AuthService.API/Controllers/AccountController.cs
@@ -1,4 +1,5 @@
-using System.Linq;
+using System.Collections.Generic;
+using System.Linq;
using System.Net;
using System.Threading.Tasks;
using AutoMapper;
@@ -9,136 +10,133 @@
using HwProj.Models.Result;
using Google.Apis.Auth;
using HwProj.Models.Roles;
+using Microsoft.AspNetCore.Identity;
-namespace HwProj.AuthService.API.Controllers
+namespace HwProj.AuthService.API.Controllers;
+
+[Route("api/[controller]")]
+[ApiController]
+public class AccountController : Controller
{
- [Route("api/account")]
- [ApiController]
- public class AccountController : ControllerBase
+ private readonly IAccountService _accountService;
+ private readonly UserManager _userManager;
+ private readonly IMapper _mapper;
+
+ public AccountController(IAccountService accountService, UserManager userManager, IMapper mapper)
+ {
+ _accountService = accountService;
+ _userManager = userManager;
+ _mapper = mapper;
+ }
+
+ [HttpGet("getUserData/{userId}")]
+ [ProducesResponseType(typeof(AccountDataDto), (int)HttpStatusCode.OK)]
+ public async Task GetUserDataById(string userId)
+ {
+ var accountData = await _accountService.GetAccountDataAsync(userId).ConfigureAwait(false);
+
+ return accountData != null
+ ? Ok(accountData)
+ : NotFound();
+ }
+
+ [HttpGet("getUsersData")]
+ public async Task GetUsersData([FromBody] string[] userIds)
+ {
+ return await _accountService.GetManyAccountDataAsync(userIds);
+ }
+
+ [HttpPost("register")]
+ [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)]
+ public async Task Register([FromBody] RegisterViewModel model)
+ {
+ var newModel = _mapper.Map(model);
+ var result = await _accountService.RegisterUserAsync(newModel).ConfigureAwait(false);
+ return Ok(result);
+ }
+
+ [HttpPost("login")]
+ [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)]
+ public async Task Login([FromBody] LoginViewModel model)
+ {
+ var tokenMeta = await _accountService.LoginUserAsync(model).ConfigureAwait(false);
+ return Ok(tokenMeta);
+ }
+
+ [HttpPut("edit/{userId}")]
+ [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)]
+ public async Task Edit([FromBody] EditAccountViewModel model, string userId)
+ {
+ var newModel = _mapper.Map(model);
+ var result = await _accountService.EditAccountAsync(userId, newModel).ConfigureAwait(false);
+ return Ok(result);
+ }
+
+ [HttpPost("inviteNewLecturer")]
+ [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)]
+ public async Task InviteNewLecturer(InviteLecturerViewModel model)
{
- private readonly IAccountService _accountService;
- private readonly IUserManager _userManager;
- private readonly IMapper _mapper;
-
- public AccountController(IAccountService accountService, IUserManager userManager, IMapper mapper)
- {
- _accountService = accountService;
- _userManager = userManager;
- _mapper = mapper;
- }
-
- [HttpGet("getUserData/{userId}")]
- [ProducesResponseType(typeof(AccountDataDto), (int)HttpStatusCode.OK)]
- public async Task GetUserDataById(string userId)
- {
- var accountData = await _accountService.GetAccountDataAsync(userId).ConfigureAwait(false);
-
- return accountData != null
- ? Ok(accountData) as IActionResult
- : NotFound();
- }
-
- [HttpGet("getUsersData")]
- public async Task GetUsersData([FromBody] string[] userIds)
- {
- var getAccountsDataTasks = userIds.Select(_accountService.GetAccountDataAsync).ToList();
- await Task.WhenAll(getAccountsDataTasks);
-
- return getAccountsDataTasks.Select(t => t.Result).ToArray();
- }
-
- [HttpPost("register")]
- [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)]
- public async Task Register([FromBody] RegisterViewModel model)
- {
- var newModel = _mapper.Map(model);
- var result = await _accountService.RegisterUserAsync(newModel).ConfigureAwait(false);
- return Ok(result);
- }
-
- [HttpPost("login")]
- [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)]
- public async Task Login([FromBody] LoginViewModel model)
- {
- var tokenMeta = await _accountService.LoginUserAsync(model).ConfigureAwait(false);
- return Ok(tokenMeta);
- }
-
- [HttpPut("edit/{userId}")]
- [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)]
- public async Task Edit([FromBody] EditAccountViewModel model, string userId)
- {
- var newModel = _mapper.Map(model);
- var result = await _accountService.EditAccountAsync(userId, newModel).ConfigureAwait(false);
- return Ok(result);
- }
-
- [HttpPost("inviteNewLecturer")]
- [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)]
- public async Task InviteNewLecturer(InviteLecturerViewModel model)
- {
- var result = await _accountService.InviteNewLecturer(model.Email).ConfigureAwait(false);
- return Ok(result);
- }
-
- [HttpPost("google/{tokenId}")]
- [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)]
- public async Task GoogleRegister(string tokenId)
- {
- var payload =
- await GoogleJsonWebSignature.ValidateAsync(tokenId, new GoogleJsonWebSignature.ValidationSettings());
- var result = await _accountService.LoginUserByGoogleAsync(payload).ConfigureAwait(false);
- return Ok(result);
- }
-
- [HttpPut("editExternal/{userId}")]
- [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)]
- public async Task EditExternal([FromBody] EditExternalViewModel model, string userId)
- {
- var newModel = _mapper.Map(model);
- var result = await _accountService.EditAccountAsync(userId, newModel).ConfigureAwait(false);
- return Ok(result);
- }
-
-
- [HttpGet("findByEmail/{email}")]
- [ProducesResponseType(typeof(User), (int)HttpStatusCode.OK)]
- public async Task FindByEmail(string email)
- {
- var user = await _userManager.FindByEmailAsync(email);
- return Ok(user);
- }
-
- [HttpGet("getRole")]
- [ProducesResponseType(typeof(string), (int)HttpStatusCode.OK)]
- public async Task GetRolesAsync([FromBody] User user)
- {
- var roles = await _userManager.GetRolesAsync(user);
- return Ok(roles[0]);
- }
-
- [HttpGet("getAllStudents")]
- [ProducesResponseType(typeof(AccountDataDto[]), (int)HttpStatusCode.OK)]
- public async Task GetAllStudents()
- {
- var allStudents = await _accountService.GetUsersInRole(Roles.StudentRole);
- var result = allStudents
- .Select(u =>
- new AccountDataDto(u.Id, u.Name, u.Surname, u.Email, Roles.StudentRole, u.IsExternalAuth,
- u.MiddleName))
- .ToArray();
-
- return Ok(result);
- }
-
- [HttpGet("getAllLecturers")]
- [ProducesResponseType(typeof(User[]), (int)HttpStatusCode.OK)]
- public async Task GetAllLecturers()
- {
- var allLecturers = await _accountService.GetUsersInRole(Roles.LecturerRole);
- var result = allLecturers.ToArray();
-
- return Ok(result);
- }
+ var result = await _accountService.InviteNewLecturerAsync(model.Email).ConfigureAwait(false);
+ return Ok(result);
+ }
+
+ [HttpPost("google/{tokenId}")]
+ [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)]
+ public async Task GoogleRegister(string tokenId)
+ {
+ var payload =
+ await GoogleJsonWebSignature.ValidateAsync(tokenId, new GoogleJsonWebSignature.ValidationSettings());
+ var result = await _accountService.LoginUserByGoogleAsync(payload).ConfigureAwait(false);
+ return Ok(result);
+ }
+
+ [HttpPut("editExternal/{userId}")]
+ [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)]
+ public async Task EditExternal([FromBody] EditExternalViewModel model, string userId)
+ {
+ var newModel = _mapper.Map(model);
+ var result = await _accountService.EditAccountAsync(userId, newModel).ConfigureAwait(false);
+ return Ok(result);
+ }
+
+
+ [HttpGet("findByEmail/{email}")]
+ [ProducesResponseType(typeof(User), (int)HttpStatusCode.OK)]
+ public async Task FindByEmail(string email)
+ {
+ var user = await _userManager.FindByEmailAsync(email);
+ return Ok(user);
+ }
+
+ [HttpGet("getRole")]
+ [ProducesResponseType(typeof(string), (int)HttpStatusCode.OK)]
+ public async Task GetRolesAsync([FromBody] User user)
+ {
+ var roles = await _userManager.GetRolesAsync(user);
+ return Ok(roles[0]);
+ }
+
+ [HttpGet("getAllStudents")]
+ [ProducesResponseType(typeof(AccountDataDto[]), (int)HttpStatusCode.OK)]
+ public async Task GetAllStudents()
+ {
+ var allStudents = await _accountService.GetUsersInRoleAsync(Roles.StudentRole);
+ var result = allStudents
+ .Select(u =>
+ new AccountDataDto(u.Id, u.Name, u.Surname, u.Email, Roles.StudentRole, u.IsExternalAuth,
+ u.MiddleName))
+ .ToArray();
+
+ return Ok(result);
+ }
+
+ [HttpGet("getAllLecturers")]
+ [ProducesResponseType(typeof(User[]), (int)HttpStatusCode.OK)]
+ public async Task GetAllLecturers()
+ {
+ var allLecturers = await _accountService.GetUsersInRoleAsync(Roles.LecturerRole);
+ var result = allLecturers.ToArray();
+
+ return Ok(result);
}
}
diff --git a/HwProj.AuthService/HwProj.AuthService.API/Controllers/SystemController.cs b/HwProj.AuthService/HwProj.AuthService.API/Controllers/SystemController.cs
index 13d72610a..62107115e 100644
--- a/HwProj.AuthService/HwProj.AuthService.API/Controllers/SystemController.cs
+++ b/HwProj.AuthService/HwProj.AuthService.API/Controllers/SystemController.cs
@@ -1,12 +1,11 @@
using Microsoft.AspNetCore.Mvc;
-namespace HwProj.AuthService.API.Controllers
+namespace HwProj.AuthService.API.Controllers;
+
+[Route("api/[controller]")]
+[ApiController]
+public class SystemController : ControllerBase
{
- [Route("api/[controller]")]
- [ApiController]
- public class SystemController : ControllerBase
- {
- [HttpGet("status")]
- public IActionResult Status() => Ok();
- }
-}
+ [HttpGet("status")]
+ public IActionResult Status() => Ok();
+}
\ No newline at end of file
diff --git a/HwProj.AuthService/HwProj.AuthService.API/Dockerfile b/HwProj.AuthService/HwProj.AuthService.API/Dockerfile
index 042ca5ad3..7b5720f46 100644
--- a/HwProj.AuthService/HwProj.AuthService.API/Dockerfile
+++ b/HwProj.AuthService/HwProj.AuthService.API/Dockerfile
@@ -1,22 +1,15 @@
-FROM mcr.microsoft.com/dotnet/core/aspnet:2.2-stretch-slim AS base
-WORKDIR /app
-
-FROM mcr.microsoft.com/dotnet/core/sdk:2.2-stretch AS build
+FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["HwProj.AuthService/HwProj.AuthService.API/HwProj.AuthService.API.csproj", "HwProj.AuthService/HwProj.AuthService.API/"]
COPY ["HwProj.Common/HwProj.Utils/HwProj.Utils.csproj", "HwProj.Common/HwProj.Utils/"]
COPY ["HwProj.EventBus/HwProj.EventBus.Client/HwProj.EventBus.Client.csproj", "HwProj.EventBus/HwProj.EventBus.Client/"]
COPY ["HwProj.Common/HwProj.Models/HwProj.Models.csproj", "HwProj.Common/HwProj.Models/"]
COPY ["HwProj.Common/HwProj.Repositories/HwProj.Repositories.csproj", "HwProj.Common/HwProj.Repositories/"]
-RUN dotnet restore "HwProj.AuthService/HwProj.AuthService.API/HwProj.AuthService.API.csproj"
COPY . .
WORKDIR "/src/HwProj.AuthService/HwProj.AuthService.API"
-RUN dotnet build "HwProj.AuthService.API.csproj" -c Release -o /app/build
-
-FROM build AS publish
RUN dotnet publish "HwProj.AuthService.API.csproj" -c Release -o /app/publish
-FROM base AS final
+FROM build AS final
WORKDIR /app
-COPY --from=publish /app/publish .
+COPY --from=build /app/publish .
ENTRYPOINT ["dotnet", "HwProj.AuthService.API.dll"]
diff --git a/HwProj.AuthService/HwProj.AuthService.API/Events/AdminRegisterEvent.cs b/HwProj.AuthService/HwProj.AuthService.API/Events/AdminRegisterEvent.cs
deleted file mode 100644
index 09fc75942..000000000
--- a/HwProj.AuthService/HwProj.AuthService.API/Events/AdminRegisterEvent.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-namespace HwProj.AuthService.API.Events
-{
- public class AdminRegisterEvent : RegisterEvent
- {
- public AdminRegisterEvent(string userId, string email, string name, string surname = "", string middleName = "")
- : base(userId, email, name, surname, middleName)
- {
-
- }
- }
-}
diff --git a/HwProj.AuthService/HwProj.AuthService.API/Events/InviteLecturerEvent.cs b/HwProj.AuthService/HwProj.AuthService.API/Events/InviteLecturerEvent.cs
deleted file mode 100644
index 345d6cc40..000000000
--- a/HwProj.AuthService/HwProj.AuthService.API/Events/InviteLecturerEvent.cs
+++ /dev/null
@@ -1,10 +0,0 @@
-using HwProj.EventBus.Client;
-
-namespace HwProj.AuthService.API.Events
-{
- public class InviteLecturerEvent : Event
- {
- public string UserId { get; set; }
- public string UserEmail { get; set; }
- }
-}
diff --git a/HwProj.AuthService/HwProj.AuthService.API/Events/RegisterEvent.cs b/HwProj.AuthService/HwProj.AuthService.API/Events/RegisterEvent.cs
deleted file mode 100644
index c2625e5ba..000000000
--- a/HwProj.AuthService/HwProj.AuthService.API/Events/RegisterEvent.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-using HwProj.EventBus.Client;
-
-namespace HwProj.AuthService.API.Events
-{
- public abstract class RegisterEvent : Event
- {
- public string UserId { get; set; }
- public string Name { get; set; }
- public string Surname { get; set; }
- public string MiddleName { get; set; }
- public string Email { get; set; }
-
- protected RegisterEvent(string userId, string email, string name, string surname = "", string middleName = "")
- {
- UserId = userId;
- Name = name;
- Surname = surname;
- MiddleName = middleName;
- Email = email;
- }
- }
-}
diff --git a/HwProj.AuthService/HwProj.AuthService.API/Events/StudentRegisterEvent.cs b/HwProj.AuthService/HwProj.AuthService.API/Events/StudentRegisterEvent.cs
deleted file mode 100644
index 5c894d2b8..000000000
--- a/HwProj.AuthService/HwProj.AuthService.API/Events/StudentRegisterEvent.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-namespace HwProj.AuthService.API.Events
-{
- public class StudentRegisterEvent : RegisterEvent
- {
- public StudentRegisterEvent(string userId, string email, string name, string surname = "", string middleName = "")
- : base(userId, email, name, surname, middleName)
- {
-
- }
- }
-}
diff --git a/HwProj.AuthService/HwProj.AuthService.API/Extensions/IdentityResultExtensions.cs b/HwProj.AuthService/HwProj.AuthService.API/Extensions/IdentityResultExtensions.cs
index f51da37ab..3bacb9b7d 100644
--- a/HwProj.AuthService/HwProj.AuthService.API/Extensions/IdentityResultExtensions.cs
+++ b/HwProj.AuthService/HwProj.AuthService.API/Extensions/IdentityResultExtensions.cs
@@ -2,37 +2,36 @@
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
-namespace HwProj.AuthService.API.Extensions
+namespace HwProj.AuthService.API.Extensions;
+
+public static class IdentityResultExtensions
{
- public static class IdentityResultExtensions
+ public static async Task Then(this Task task,
+ Func> continuation)
{
- public static async Task Then(this Task task,
- Func> continuation)
+ var result = await task.ConfigureAwait(false);
+ return result.Succeeded
+ ? await continuation().ConfigureAwait(false)
+ : result;
+ }
+
+ public static string TryGetIdentityError(this SignInResult result)
+ {
+ if (result.IsLockedOut)
{
- var result = await task.ConfigureAwait(false);
- return result.Succeeded
- ? await continuation().ConfigureAwait(false)
- : result;
+ return nameof(result.IsLockedOut);
}
- public static string TryGetIdentityError(this SignInResult result)
+ if (result.IsNotAllowed)
{
- if (result.IsLockedOut)
- {
- return nameof(result.IsLockedOut);
- }
-
- if (result.IsNotAllowed)
- {
- return nameof(result.IsNotAllowed);
- }
+ return nameof(result.IsNotAllowed);
+ }
- if (result.RequiresTwoFactor)
- {
- return nameof(result.RequiresTwoFactor);
- }
-
- return "Неправильный логин или пароль";
+ if (result.RequiresTwoFactor)
+ {
+ return nameof(result.RequiresTwoFactor);
}
+
+ return "Неправильный логин или пароль";
}
}
\ No newline at end of file
diff --git a/HwProj.AuthService/HwProj.AuthService.API/HwProj.AuthService.API.csproj b/HwProj.AuthService/HwProj.AuthService.API/HwProj.AuthService.API.csproj
index 1a272c31b..06a2dbc61 100644
--- a/HwProj.AuthService/HwProj.AuthService.API/HwProj.AuthService.API.csproj
+++ b/HwProj.AuthService/HwProj.AuthService.API/HwProj.AuthService.API.csproj
@@ -1,7 +1,7 @@
- netcoreapp2.2
+ net6.0
Linux
..\..\docker-compose.dcproj
..\..
@@ -11,15 +11,15 @@
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
@@ -28,8 +28,4 @@
-
-
-
-
diff --git a/HwProj.AuthService/HwProj.AuthService.API/Models/IdentityContext.cs b/HwProj.AuthService/HwProj.AuthService.API/Models/IdentityContext.cs
index 6f35c9636..166311b09 100644
--- a/HwProj.AuthService/HwProj.AuthService.API/Models/IdentityContext.cs
+++ b/HwProj.AuthService/HwProj.AuthService.API/Models/IdentityContext.cs
@@ -1,15 +1,13 @@
using HwProj.Models.AuthService.ViewModels;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
+namespace HwProj.AuthService.API.Models;
-namespace HwProj.AuthService.API.Models
+public sealed class IdentityContext : IdentityDbContext
{
- public sealed class IdentityContext : IdentityDbContext
+ public IdentityContext(DbContextOptions options)
+ : base(options)
{
- public IdentityContext(DbContextOptions options)
- : base(options)
- {
- Database.EnsureCreated();
- }
+ Database.EnsureCreated();
}
-}
+}
\ No newline at end of file
diff --git a/HwProj.AuthService/HwProj.AuthService.API/Models/IdentityResults.cs b/HwProj.AuthService/HwProj.AuthService.API/Models/IdentityResults.cs
index 77a7dbe30..f5effa3b7 100644
--- a/HwProj.AuthService/HwProj.AuthService.API/Models/IdentityResults.cs
+++ b/HwProj.AuthService/HwProj.AuthService.API/Models/IdentityResults.cs
@@ -1,21 +1,20 @@
using Microsoft.AspNetCore.Identity;
-namespace HwProj.AuthService.API.Models
-{
- public static class IdentityResults
- {
- public static IdentityResult UserNotFound => IdentityResult.Failed(IdentityErrors.UserNotFound);
- public static IdentityResult WrongPassword => IdentityResult.Failed(IdentityErrors.WrongPassword);
+namespace HwProj.AuthService.API.Models;
- public static IdentityResult UserExists =>
- IdentityResult.Failed(new IdentityError { Description = "User exists" });
- }
+public static class IdentityResults
+{
+ public static IdentityResult UserNotFound => IdentityResult.Failed(IdentityErrors.UserNotFound);
+ public static IdentityResult WrongPassword => IdentityResult.Failed(IdentityErrors.WrongPassword);
- public static class IdentityErrors
- {
- public static IdentityError EmailNotConfirmed => new IdentityError { Description = "Email not confirmed" };
- public static IdentityError UserNotFound => new IdentityError { Description = "User not found" };
- public static IdentityError WrongPassword => new IdentityError { Description = "Wrong login or password" };
- public static IdentityError PasswordTooShort => new IdentityError { Description = "Пароль должен содержать не менее 6 символов" };
- }
+ public static IdentityResult UserExists =>
+ IdentityResult.Failed(new IdentityError { Description = "User exists" });
}
+
+public static class IdentityErrors
+{
+ public static IdentityError EmailNotConfirmed => new() { Description = "Email not confirmed" };
+ public static IdentityError UserNotFound => new() { Description = "User not found" };
+ public static IdentityError WrongPassword => new() { Description = "Wrong login or password" };
+ public static IdentityError PasswordTooShort => new() { Description = "Пароль должен содержать не менее 6 символов" };
+}
\ No newline at end of file
diff --git a/HwProj.AuthService/HwProj.AuthService.API/Program.cs b/HwProj.AuthService/HwProj.AuthService.API/Program.cs
index d0443a9a6..096d32001 100644
--- a/HwProj.AuthService/HwProj.AuthService.API/Program.cs
+++ b/HwProj.AuthService/HwProj.AuthService.API/Program.cs
@@ -1,17 +1,16 @@
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
-namespace HwProj.AuthService.API
+namespace HwProj.AuthService.API;
+
+public class Program
{
- public class Program
+ public static void Main(string[] args)
{
- public static void Main(string[] args)
- {
- CreateWebHostBuilder(args).Build().Run();
- }
-
- public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
- WebHost.CreateDefaultBuilder(args)
- .UseStartup();
+ CreateWebHostBuilder(args).Build().Run();
}
-}
+
+ public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
+ WebHost.CreateDefaultBuilder(args)
+ .UseStartup();
+}
\ No newline at end of file
diff --git a/HwProj.AuthService/HwProj.AuthService.API/RoleInitializer.cs b/HwProj.AuthService/HwProj.AuthService.API/RoleInitializer.cs
index f3bcd0143..e68847872 100644
--- a/HwProj.AuthService/HwProj.AuthService.API/RoleInitializer.cs
+++ b/HwProj.AuthService/HwProj.AuthService.API/RoleInitializer.cs
@@ -5,44 +5,43 @@
using HwProj.Models.Roles;
using HwProj.Models.AuthService.ViewModels;
-namespace HwProj.AuthService.API
+namespace HwProj.AuthService.API;
+
+public class RoleInitializer
{
- public class RoleInitializer
+ public static async Task InitializeAsync(UserManager userManager, RoleManager roleManager, IEventBus eventBus)
{
- public static async Task InitializeAsync(UserManager userManager, RoleManager roleManager, IEventBus eventBus)
+ if(await roleManager.FindByNameAsync(Roles.LecturerRole) == null)
{
- if(await roleManager.FindByNameAsync(Roles.LecturerRole) == null)
- {
- await roleManager.CreateAsync(Roles.Lecturer);
- }
+ await roleManager.CreateAsync(Roles.Lecturer);
+ }
- if (await roleManager.FindByNameAsync(Roles.StudentRole) == null)
- {
- await roleManager.CreateAsync(Roles.Student);
- }
+ if (await roleManager.FindByNameAsync(Roles.StudentRole) == null)
+ {
+ await roleManager.CreateAsync(Roles.Student);
+ }
- const string email = "admin@gmail.com";
- const string password = "Admin@1234";
+ const string email = "admin@gmail.com";
+ const string password = "Admin@1234";
- if (await userManager.FindByEmailAsync(email) == null)
- {
- var admin = new User {
- Email = email,
- Name = "Admin",
- UserName = "Admin"
- };
+ if (await userManager.FindByEmailAsync(email) == null)
+ {
+ var admin = new User {
+ Email = email,
+ Name = "Admin",
+ UserName = "Admin"
+ };
- var result = await userManager.CreateAsync(admin, password);
+ var result = await userManager.CreateAsync(admin, password);
- if (result.Succeeded)
- {
- await userManager.AddToRoleAsync(admin, Roles.LecturerRole); //TODO: dangerous
- admin.EmailConfirmed = true;
- await userManager.UpdateAsync(admin);
- var @event = new AdminRegisterEvent(admin.Id, admin.Email, admin.Name);
- eventBus.Publish(@event);
- }
+ if (result.Succeeded)
+ {
+ await userManager.AddToRoleAsync(admin, Roles.LecturerRole); //TODO: dangerous
+ admin.EmailConfirmed = true;
+ await userManager.UpdateAsync(admin);
+ var @event = new AdminRegisterEvent(admin.Id, admin.Email, admin.Name);
+ eventBus.Publish(@event);
}
}
}
-}
+}
\ No newline at end of file
diff --git a/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs b/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs
index b60ad7ef5..c31a7ec16 100644
--- a/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs
+++ b/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs
@@ -9,231 +9,255 @@
using HwProj.AuthService.API.Events;
using HwProj.EventBus.Client.Interfaces;
using HwProj.Models.AuthService.DTO;
+using HwProj.Models.AuthService.Events;
using HwProj.Models.AuthService.ViewModels;
using HwProj.Models.Result;
+using Microsoft.EntityFrameworkCore;
-namespace HwProj.AuthService.API.Services
+namespace HwProj.AuthService.API.Services;
+
+public class AccountService : IAccountService
{
- public class AccountService : IAccountService
+ private readonly UserManager _userManager;
+ private readonly SignInManager _signInManager;
+ private readonly IAuthTokenService _tokenService;
+ private readonly IEventBus _eventBus;
+ private readonly IMapper _mapper;
+
+ public AccountService(UserManager userManager,
+ SignInManager signInManager,
+ IAuthTokenService authTokenService,
+ IEventBus eventBus,
+ IMapper mapper)
{
- private readonly IUserManager _userManager;
- private readonly SignInManager _signInManager;
- private readonly IAuthTokenService _tokenService;
- private readonly IEventBus _eventBus;
- private readonly IMapper _mapper;
+ _userManager = userManager;
+ _signInManager = signInManager;
+ _tokenService = authTokenService;
+ _eventBus = eventBus;
+ _mapper = mapper;
+ }
- public AccountService(IUserManager userManager,
- SignInManager signInManager,
- IAuthTokenService authTokenService,
- IEventBus eventBus,
- IMapper mapper)
+
+ public async Task GetAccountDataAsync(string userId)
+ {
+ var user = await _userManager.FindByIdAsync(userId).ConfigureAwait(false);
+ if (user == null)
{
- _userManager = userManager;
- _signInManager = signInManager;
- _tokenService = authTokenService;
- _eventBus = eventBus;
- _mapper = mapper;
+ return null;
}
- public async Task GetAccountDataAsync(string userId)
+ var userRoles = await _userManager.GetRolesAsync(user).ConfigureAwait(false);
+ var userRole = userRoles.FirstOrDefault() ?? Roles.StudentRole;
+ return new AccountDataDto(user.Id, user.Name, user.Surname, user.Email, userRole, user.IsExternalAuth,
+ user.MiddleName);
+ }
+
+ public async Task GetManyAccountDataAsync(string[] userIds)
+ {
+ var users = await _userManager.Users.Where(user => userIds.Contains(user.Id)).ToArrayAsync().ConfigureAwait(false);
+ var orderedByIdUsers = new User[users.Length];
+ for (var i = 0; i < users.Length; i++)
{
- var user = await _userManager.FindByIdAsync(userId).ConfigureAwait(false);
- if (user == null)
- {
- return null;
- }
+ orderedByIdUsers[i] = users.First(user => user.Id == userIds[i]);
+ }
+
+ var usersDto = new List();
+ var lecturerIds = (await _userManager.GetUsersInRoleAsync(Roles.LecturerRole)).Select(l => l.Id).ToHashSet();
+ // TODO сразу роли получить
+ foreach (var user in orderedByIdUsers)
+ {
+ var userRole = lecturerIds.Contains(user.Id) ? Roles.LecturerRole : Roles.StudentRole;
+ usersDto.Add(new AccountDataDto(user.Id, user.Name, user.Surname, user.Email,
+ userRole, user.IsExternalAuth, user.MiddleName));
+ }
+
+ return usersDto.ToArray();
+ }
- var userRoles = await _userManager.GetRolesAsync(user).ConfigureAwait(false);
- var userRole = userRoles.FirstOrDefault() ?? Roles.StudentRole;
- return new AccountDataDto(user.Id, user.Name, user.Surname, user.Email, userRole, user.IsExternalAuth,
- user.MiddleName);
+ public async Task EditAccountAsync(string id, EditDataDTO model)
+ {
+ var user = await _userManager.FindByIdAsync(id).ConfigureAwait(false);
+ if (user == null)
+ {
+ return Result.Failed("Пользователь не найден");
}
- public async Task EditAccountAsync(string id, EditDataDTO model)
+ if (!user.IsExternalAuth && !await _userManager.CheckPasswordAsync(user, model.CurrentPassword))
{
- var user = await _userManager.FindByIdAsync(id).ConfigureAwait(false);
- if (user == null)
- {
- return Result.Failed("Пользователь не найден");
- }
+ return Result.Failed("Неправильный логин или пароль");
+ }
- if (!user.IsExternalAuth && !await _userManager.CheckPasswordAsync(user, model.CurrentPassword))
- {
- return Result.Failed("Неправильный логин или пароль");
- }
+ var result = user.IsExternalAuth
+ ? await ChangeUserNameTask(user, model)
+ : await ChangeUserNameTask(user, model).Then(() => ChangePasswordAsync(user, model));
- var result = user.IsExternalAuth
- ? await ChangeUserNameTask(user, model)
- : await ChangeUserNameTask(user, model).Then(() => ChangePasswordAsync(user, model));
+ if (result.Succeeded)
+ {
+ return Result.Success();
+ }
- if (result.Succeeded)
- {
- return Result.Success();
- }
+ return Result.Failed();
+ }
- return Result.Failed();
+ public async Task> LoginUserAsync(LoginViewModel model)
+ {
+ if (await _userManager.FindByEmailAsync(model.Email).ConfigureAwait(false)
+ is var user && user == null)
+ {
+ return Result.Failed("Пользователь не найден");
}
- public async Task> LoginUserAsync(LoginViewModel model)
+ var result = await _signInManager.PasswordSignInAsync(
+ user,
+ model.Password,
+ model.RememberMe,
+ false).ConfigureAwait(false);
+
+ if (!result.Succeeded)
{
- if (await _userManager.FindByEmailAsync(model.Email).ConfigureAwait(false)
- is var user && user == null)
- {
- return Result.Failed("Пользователь не найден");
- }
+ return Result.Failed(result.TryGetIdentityError());
+ }
- var result = await _signInManager.PasswordSignInAsync(
- user,
- model.Password,
- model.RememberMe,
- false).ConfigureAwait(false);
+ var token = await _tokenService.GetTokenAsync(user).ConfigureAwait(false);
+ return Result.Success(token);
+ }
- if (!result.Succeeded)
+ public async Task> LoginUserByGoogleAsync(GoogleJsonWebSignature.Payload payload)
+ {
+ if (await _userManager.FindByEmailAsync(payload.Email).ConfigureAwait(false)
+ is var user && user == null)
+ {
+ var userModel = new RegisterDataDTO()
{
- return Result.Failed(result.TryGetIdentityError());
- }
+ Email = payload.Email,
+ Name = payload.GivenName,
+ Surname = payload.FamilyName,
+ IsExternalAuth = true
+ };
- var token = await _tokenService.GetTokenAsync(user).ConfigureAwait(false);
- return Result.Success(token);
+ return await RegisterUserAsync(userModel);
}
- public async Task> LoginUserByGoogleAsync(GoogleJsonWebSignature.Payload payload)
- {
- if (await _userManager.FindByEmailAsync(payload.Email).ConfigureAwait(false)
- is var user && user == null)
- {
- var userModel = new RegisterDataDTO()
- {
- Email = payload.Email,
- Name = payload.GivenName,
- Surname = payload.FamilyName,
- IsExternalAuth = true
- };
-
- return await RegisterUserAsync(userModel);
- }
+ return await GetToken(user);
+ }
- return await GetToken(user);
+ public async Task> RegisterUserAsync(RegisterDataDTO model)
+ {
+ if (await _userManager.FindByEmailAsync(model.Email) != null)
+ {
+ return Result.Failed("Пользователь уже зарегистрирован");
}
- public async Task> RegisterUserAsync(RegisterDataDTO model)
+ if (!model.IsExternalAuth && model.Password.Length < 6)
{
- if (await _userManager.FindByEmailAsync(model.Email) != null)
- {
- return Result.Failed("Пользователь уже зарегистрирован");
- }
-
- if (!model.IsExternalAuth && model.Password.Length < 6)
- {
- return Result.Failed("Пароль должен содержать не менее 6 символов");
- }
-
- var user = _mapper.Map(model);
- user.UserName = user.Email.Split('@')[0];
+ return Result.Failed("Пароль должен содержать не менее 6 символов");
+ }
- var createUserTask = model.IsExternalAuth
- ? _userManager.CreateAsync(user)
- : _userManager.CreateAsync(user, model.Password);
+ var user = _mapper.Map(model);
+ user.UserName = user.Email.Split('@')[0];
- if (!model.IsExternalAuth && createUserTask.Result.Succeeded &&
- !await _userManager.CheckPasswordAsync(user, model.PasswordConfirm))
- {
- return Result.Failed("Пароли не совпадают");
- }
+ var createUserTask = model.IsExternalAuth
+ ? _userManager.CreateAsync(user)
+ : _userManager.CreateAsync(user, model.Password);
- var result = await createUserTask
- .Then(() => _userManager.AddToRoleAsync(user, Roles.StudentRole))
- .Then(() =>
- {
- user.EmailConfirmed = true;
- return _userManager.UpdateAsync(user);
- });
+ if (!model.IsExternalAuth && createUserTask.Result.Succeeded &&
+ !await _userManager.CheckPasswordAsync(user, model.PasswordConfirm))
+ {
+ return Result.Failed("Пароли не совпадают");
+ }
- if (result.Succeeded)
+ var result = await createUserTask
+ .Then(() => _userManager.AddToRoleAsync(user, Roles.StudentRole))
+ .Then(() =>
{
- var newUser = await _userManager.FindByEmailAsync(model.Email).ConfigureAwait(false);
- var registerEvent = new StudentRegisterEvent(newUser.Id, newUser.Email, newUser.Name,
- newUser.Surname, newUser.MiddleName);
- _eventBus.Publish(registerEvent);
-
- if (!model.IsExternalAuth)
- {
- await SignIn(user, model.Password);
- }
-
- return await GetToken(user);
- }
+ user.EmailConfirmed = true;
+ return _userManager.UpdateAsync(user);
+ });
- return Result.Failed(result.Errors.Select(errors => errors.Description).ToArray());
- }
-
- public async Task InviteNewLecturer(string emailOfInvitedUser)
+ if (result.Succeeded)
{
- var invitedUser = await _userManager.FindByEmailAsync(emailOfInvitedUser).ConfigureAwait(false);
+ var newUser = await _userManager.FindByEmailAsync(model.Email).ConfigureAwait(false);
+ var registerEvent = new StudentRegisterEvent(newUser.Id, newUser.Email, newUser.Name,
+ newUser.Surname, newUser.MiddleName);
+ _eventBus.Publish(registerEvent);
- if (invitedUser == null)
+ if (!model.IsExternalAuth)
{
- return Result.Failed("Пользователь не найден");
+ await SignIn(user, model.Password);
}
- var result = await _userManager.AddToRoleAsync(invitedUser, Roles.LecturerRole)
- .Then(() => _userManager.RemoveFromRoleAsync(invitedUser, Roles.StudentRole)).ConfigureAwait(false);
+ return await GetToken(user);
+ }
- if (result.Succeeded)
- {
- var inviteEvent = new InviteLecturerEvent
- {
- UserId = invitedUser.Id,
- UserEmail = invitedUser.Email
- };
- _eventBus.Publish(inviteEvent);
- return Result.Success();
- }
+ return Result.Failed(result.Errors.Select(errors => errors.Description).ToArray());
+ }
- return Result.Failed("Пользователь уже является преподавателем");
- }
+ public async Task InviteNewLecturerAsync(string emailOfInvitedUser)
+ {
+ var invitedUser = await _userManager.FindByEmailAsync(emailOfInvitedUser).ConfigureAwait(false);
- public async Task> GetUsersInRole(string role)
+ if (invitedUser == null)
{
- return await _userManager.GetUsersInRoleAsync(role);
+ return Result.Failed("Пользователь не найден");
}
- private Task ChangeUserNameTask(User user, EditDataDTO model)
- {
- if (!string.IsNullOrWhiteSpace(model.Name))
- {
- user.Name = model.Name;
- }
+ var result = await _userManager.AddToRoleAsync(invitedUser, Roles.LecturerRole)
+ .Then(() => _userManager.RemoveFromRoleAsync(invitedUser, Roles.StudentRole)).ConfigureAwait(false);
- if (!string.IsNullOrWhiteSpace(model.Name))
+ if (result.Succeeded)
+ {
+ var inviteEvent = new InviteLecturerEvent
{
- user.Surname = model.Surname;
- }
+ UserId = invitedUser.Id,
+ UserEmail = invitedUser.Email
+ };
+ _eventBus.Publish(inviteEvent);
+ return Result.Success();
+ }
- if (!string.IsNullOrWhiteSpace(model.Name))
- {
- user.MiddleName = model.MiddleName;
- }
+ return Result.Failed("Пользователь уже является преподавателем");
+ }
- return _userManager.UpdateAsync(user);
- }
+ public async Task> GetUsersInRoleAsync(string role)
+ {
+ return await _userManager.GetUsersInRoleAsync(role);
+ }
- private Task ChangePasswordAsync(User user, EditDataDTO model)
+ private Task ChangeUserNameTask(User user, EditDataDTO model)
+ {
+ if (!string.IsNullOrWhiteSpace(model.Name))
{
- return !string.IsNullOrWhiteSpace(model.NewPassword)
- ? _userManager.ChangePasswordAsync(user, model.CurrentPassword, model.NewPassword)
- : Task.FromResult(IdentityResult.Success);
+ user.Name = model.Name;
}
- private async Task SignIn(User user, string password)
+ if (!string.IsNullOrWhiteSpace(model.Name))
{
- await _signInManager.PasswordSignInAsync(user, password, false, false)
- .ConfigureAwait(false);
+ user.Surname = model.Surname;
}
- private async Task> GetToken(User user)
+ if (!string.IsNullOrWhiteSpace(model.Name))
{
- return Result.Success(await _tokenService.GetTokenAsync(user).ConfigureAwait(false));
+ user.MiddleName = model.MiddleName;
}
+
+ return _userManager.UpdateAsync(user);
+ }
+
+ private Task ChangePasswordAsync(User user, EditDataDTO model)
+ {
+ return !string.IsNullOrWhiteSpace(model.NewPassword)
+ ? _userManager.ChangePasswordAsync(user, model.CurrentPassword, model.NewPassword)
+ : Task.FromResult(IdentityResult.Success);
+ }
+
+ private async Task SignIn(User user, string password)
+ {
+ await _signInManager.PasswordSignInAsync(user, password, false, false)
+ .ConfigureAwait(false);
+ }
+
+ private async Task> GetToken(User user)
+ {
+ return Result.Success(await _tokenService.GetTokenAsync(user).ConfigureAwait(false));
}
-}
+}
\ No newline at end of file
diff --git a/HwProj.AuthService/HwProj.AuthService.API/Services/AuthTokenService.cs b/HwProj.AuthService/HwProj.AuthService.API/Services/AuthTokenService.cs
index cd7d9e778..e48a7ff5f 100644
--- a/HwProj.AuthService/HwProj.AuthService.API/Services/AuthTokenService.cs
+++ b/HwProj.AuthService/HwProj.AuthService.API/Services/AuthTokenService.cs
@@ -11,45 +11,44 @@
using HwProj.Models.AuthService.DTO;
using HwProj.Models.AuthService.ViewModels;
-namespace HwProj.AuthService.API.Services
+namespace HwProj.AuthService.API.Services;
+
+public class AuthTokenService : IAuthTokenService
{
- public class AuthTokenService : IAuthTokenService
+ private readonly UserManager _userManager;
+ private readonly IConfigurationSection _configuration;
+
+ public AuthTokenService(UserManager userManager, IConfiguration configuration)
{
- private readonly UserManager _userManager;
- private readonly IConfigurationSection _configuration;
+ _userManager = userManager;
+ _configuration = configuration.GetSection("AppSettings");
+ }
- public AuthTokenService(UserManager userManager, IConfiguration configuration)
- {
- _userManager = userManager;
- _configuration = configuration.GetSection("AppSettings");
- }
+ public async Task GetTokenAsync(User user)
+ {
+ var securityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_configuration["SecurityKey"]));
+ var timeNow = DateTime.UtcNow;
- public async Task GetTokenAsync(User user)
- {
- var securityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_configuration["SecurityKey"]));
- var timeNow = DateTime.UtcNow;
-
- var userRoles = await _userManager.GetRolesAsync(user).ConfigureAwait(false);
-
- var token = new JwtSecurityToken(
- issuer: _configuration["ApiName"],
- notBefore: timeNow,
- expires: timeNow.AddMinutes(int.Parse(_configuration["ExpiresIn"])),
- claims: new[]
- {
- new Claim("_userName", user.UserName),
- new Claim("_id", user.Id),
- new Claim(ClaimTypes.Email, user.Email),
- new Claim(ClaimTypes.Role, userRoles.FirstOrDefault() ?? Roles.StudentRole)
- },
- signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256));
-
- var tokenCredentials = new TokenCredentials
+ var userRoles = await _userManager.GetRolesAsync(user).ConfigureAwait(false);
+
+ var token = new JwtSecurityToken(
+ issuer: _configuration["ApiName"],
+ notBefore: timeNow,
+ expires: timeNow.AddMinutes(int.Parse(_configuration["ExpiresIn"])),
+ claims: new[]
{
- AccessToken = new JwtSecurityTokenHandler().WriteToken(token)
- };
+ new Claim("_userName", user.UserName),
+ new Claim("_id", user.Id),
+ new Claim(ClaimTypes.Email, user.Email),
+ new Claim(ClaimTypes.Role, userRoles.FirstOrDefault() ?? Roles.StudentRole)
+ },
+ signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256));
+
+ var tokenCredentials = new TokenCredentials
+ {
+ AccessToken = new JwtSecurityTokenHandler().WriteToken(token)
+ };
- return tokenCredentials;
- }
+ return tokenCredentials;
}
-}
+}
\ No newline at end of file
diff --git a/HwProj.AuthService/HwProj.AuthService.API/Services/IAccountService.cs b/HwProj.AuthService/HwProj.AuthService.API/Services/IAccountService.cs
index 183e5524e..cb55c2478 100644
--- a/HwProj.AuthService/HwProj.AuthService.API/Services/IAccountService.cs
+++ b/HwProj.AuthService/HwProj.AuthService.API/Services/IAccountService.cs
@@ -5,16 +5,16 @@
using HwProj.Models.AuthService.ViewModels;
using HwProj.Models.Result;
-namespace HwProj.AuthService.API.Services
+namespace HwProj.AuthService.API.Services;
+
+public interface IAccountService
{
- public interface IAccountService
- {
- Task GetAccountDataAsync(string userId);
- Task> RegisterUserAsync(RegisterDataDTO model);
- Task EditAccountAsync(string accountId, EditDataDTO model);
- Task> LoginUserAsync(LoginViewModel model);
- Task> LoginUserByGoogleAsync(GoogleJsonWebSignature.Payload payload);
- Task InviteNewLecturer(string emailOfInvitedUser);
- Task> GetUsersInRole(string role);
- }
-}
+ Task GetAccountDataAsync(string userId);
+ Task GetManyAccountDataAsync(string[] userIds);
+ Task> RegisterUserAsync(RegisterDataDTO model);
+ Task EditAccountAsync(string accountId, EditDataDTO model);
+ Task> LoginUserAsync(LoginViewModel model);
+ Task> LoginUserByGoogleAsync(GoogleJsonWebSignature.Payload payload);
+ Task InviteNewLecturerAsync(string emailOfInvitedUser);
+ Task> GetUsersInRoleAsync(string role);
+}
\ No newline at end of file
diff --git a/HwProj.AuthService/HwProj.AuthService.API/Services/IAuthTokenService.cs b/HwProj.AuthService/HwProj.AuthService.API/Services/IAuthTokenService.cs
index ee0caef99..48f8873cb 100644
--- a/HwProj.AuthService/HwProj.AuthService.API/Services/IAuthTokenService.cs
+++ b/HwProj.AuthService/HwProj.AuthService.API/Services/IAuthTokenService.cs
@@ -2,10 +2,9 @@
using HwProj.Models.AuthService.ViewModels;
using System.Threading.Tasks;
-namespace HwProj.AuthService.API.Services
+namespace HwProj.AuthService.API.Services;
+
+public interface IAuthTokenService
{
- public interface IAuthTokenService
- {
- Task