Skip to content
Snippets Groups Projects

Authentication added & role based authorization implemented

Merged Laxmana Arasavilli requested to merge master into main
13 files
+ 153
93
Compare changes
  • Side-by-side
  • Inline
Files
13
using Course_Management_System.Database.Entities;
using Course_Management_System.Services.DTO.RequestDTO;
using Course_Management_System.Services.Interfaces;
using Course_Management_System.Utility.CustomResponseTypes;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace Course_Management_System.API.Controllers;
@@ -10,89 +11,30 @@ namespace Course_Management_System.API.Controllers;
[Route("[controller]/[Action]")]
public class AuthenticationController : ControllerBase
{
private readonly UserManager<UserEntity> _userManager;
//signInManager will hold the SignInManager instance
private readonly SignInManager<UserEntity> _signInManager;
//Both UserManager and SignInManager services are injected into the AccountController
//using constructor injection
public AuthenticationController(UserManager<UserEntity> userManager, SignInManager<UserEntity> signInManager)
private readonly IAuthenticationServices _authenticationServices;
public AuthenticationController(IAuthenticationServices authenticationServices)
{
_userManager = userManager;
_signInManager = signInManager;
_authenticationServices = authenticationServices;
}
[HttpPost]
public async Task<IActionResult> Register([FromForm] UserRegisterRequestDTO newUser)
[AllowAnonymous]
public async Task<CustomResponse> Register([FromForm] UserRegisterRequestDTO newUser)
{
if (ModelState.IsValid)
{
// Copy data from RegisterViewModel to UserEntity
var user = new UserEntity
{
UserName = newUser.UserName,
Email = newUser.Email,
CreatedAt = DateTime.Now,
UpdatedAt = DateTime.Now,
UpdatedBy =$"{newUser.UserName}" ,
CreatedBy = $"{newUser.UserName}",
IsActive = false,
RoleType = newUser.RoleType
};
// Store user data in AspNetUsers database table
var result = await _userManager.CreateAsync(user, newUser.Password);
// If user is successfully created, sign-in the user using
// SignInManager and redirect to index action of HomeController
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
await _userManager.AddToRoleAsync(user,newUser.RoleType.ToString());
return Ok("Registered successfully");
}
// If there are any errors, add them to the ModelState object
// which will be displayed by the validation summary tag helper
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
return BadRequest();
return await _authenticationServices.RegisterNewUser(newUser);
}
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login([FromForm] UserLoginRequestDTO userToLogin)
public async Task<CustomResponse> Login([FromForm] UserLoginRequestDTO userToLogin)
{
if (ModelState.IsValid)
{
var result = await _signInManager.PasswordSignInAsync(userToLogin.UserName, userToLogin.Password, userToLogin.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
// Handle successful login
// return RedirectToAction(nameof(HomeController.Index), "Home");
var loggedInUser = _userManager.Users.Where(u=> u.UserName == userToLogin.UserName).FirstOrDefault();
loggedInUser.IsActive = true;
await _userManager.UpdateAsync(loggedInUser);
return Ok("Logged in successfully");
}
else
{
// Handle failure
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return BadRequest();
}
}
return Ok();
return await _authenticationServices.LoginUser(userToLogin);
}
[HttpPost]
public async Task<IActionResult> Logout()
{
var loggedInUser = _userManager.Users.Where(u=> u.IsActive==true).FirstOrDefault();
loggedInUser.IsActive = false;
await _userManager.UpdateAsync(loggedInUser);
await _signInManager.SignOutAsync();
return Ok("Logout Successfully");
[AllowAnonymous]
public async Task<CustomResponse> Logout()
{
return await _authenticationServices.LogOutUser();
}
}
\ No newline at end of file
Loading