Commit a8be0ff8 authored by hasan khaddour's avatar hasan khaddour

add authentication mmanager

parent 143feeb8
......@@ -7,12 +7,15 @@
<ItemGroup>
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="5.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="5.0.17" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.17">
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.17" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.17">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.17" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="5.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.17">
<PrivateAssets>all</PrivateAssets>
......
using ApplicationCore.DTOs;
using ApplicationCore.Interfaces.IAuthentication;
using ApplicationDomain.Entities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
namespace ApplicationCore.Authentication
{
public class AuthenticationManager : IAuthenticationManager
{
private readonly UserManager<User> _userManager;
private readonly SignInManager<User> _signInManager;
public AuthenticationManager(
SignInManager<User> signInManager,
UserManager<User> userManager
)
{
_userManager = userManager;
_signInManager = signInManager;
}
public async Task<bool> Authenticate(LoginInputDTO loginInputDTO)
{
var result = await _signInManager.PasswordSignInAsync(loginInputDTO.Email, loginInputDTO.Password, loginInputDTO.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
return true;
}
else
{
return false;
}
}
public async Task<IdentityResult> Register(RegisterInputDTO registerInputDTO)
{
var patient = new Patient {
BIO =registerInputDTO.Patient.BIO
};
var user = new User
{
NormalizedEmail = registerInputDTO.Email,
FirstName = registerInputDTO.FirstName,
LastName = registerInputDTO.LastName,
Avatar = registerInputDTO.ImageName,
UserName = registerInputDTO.Email,
Email = registerInputDTO.Email,
Patient =patient,
CreationTime = DateTime.Now,
};
var result = await _userManager.CreateAsync(user, registerInputDTO.Password);
if (result.Succeeded)
{
result = await _userManager.AddToRoleAsync(user, "patient");
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return IdentityResult.Success;
}
else {
return result;
}
}
return result;
}
public async Task SignIn(User user, bool isPersisted)
{
await _signInManager.SignInAsync(user, isPersistent: false);
}
public async Task SignOut()
{
await _signInManager.SignOutAsync();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ApplicationCore.DTOs
{
public class LoginInputDTO : DTOBase
{
public string Email { get; set; }
public string Password { get; set; }
public bool RememberMe { get; set; }
public String ReturnUrl { get; set; }
}
}
using ApplicationDomain.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ApplicationCore.DTOs
{
public class RegisterInputDTO :DTOBase
{
public string Email { get; set; }
public string ImageName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public PatientDTO Patient { get; set; }
public string Password { get; set; }
public string ConfirmPassword { get; set; }
public string ReturnUrl { get; set; }
}
}
using ApplicationCore.DTOs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using ApplicationDomain.Entities;
namespace ApplicationCore.Interfaces.IAuthentication
{
public interface IAuthenticationManager
{
Task<Boolean> Authenticate(LoginInputDTO loginInputDTO);
Task<IdentityResult> Register(RegisterInputDTO registerInputDTO);
Task SignOut();
Task SignIn(User user , bool isPersisted );
}
}
......@@ -52,6 +52,10 @@
"target": "Package",
"version": "[5.0.17, )"
},
"Microsoft.AspNetCore.Mvc.NewtonsoftJson": {
"target": "Package",
"version": "[5.0.17, )"
},
"Microsoft.EntityFrameworkCore.Design": {
"include": "Runtime, Build, Native, ContentFiles, Analyzers, BuildTransitive",
"suppressParent": "All",
......@@ -67,6 +71,10 @@
"suppressParent": "All",
"target": "Package",
"version": "[5.0.17, )"
},
"Microsoft.VisualStudio.Web.CodeGeneration.Design": {
"target": "Package",
"version": "[5.0.2, )"
}
},
"imports": [
......
......@@ -19,7 +19,7 @@
<Import Project="$(NuGetPackageRoot)microsoft.entityframeworkcore.design\5.0.17\build\netcoreapp3.0\Microsoft.EntityFrameworkCore.Design.props" Condition="Exists('$(NuGetPackageRoot)microsoft.entityframeworkcore.design\5.0.17\build\netcoreapp3.0\Microsoft.EntityFrameworkCore.Design.props')" />
</ImportGroup>
<PropertyGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
<PkgNewtonsoft_Json Condition=" '$(PkgNewtonsoft_Json)' == '' ">C:\Users\HASAN\.nuget\packages\newtonsoft.json\10.0.1</PkgNewtonsoft_Json>
<PkgMicrosoft_CodeAnalysis_Analyzers Condition=" '$(PkgMicrosoft_CodeAnalysis_Analyzers)' == '' ">C:\Users\HASAN\.nuget\packages\microsoft.codeanalysis.analyzers\3.0.0</PkgMicrosoft_CodeAnalysis_Analyzers>
<PkgMicrosoft_EntityFrameworkCore_Tools Condition=" '$(PkgMicrosoft_EntityFrameworkCore_Tools)' == '' ">C:\Users\HASAN\.nuget\packages\microsoft.entityframeworkcore.tools\5.0.17</PkgMicrosoft_EntityFrameworkCore_Tools>
</PropertyGroup>
</Project>
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed.
a27bbfb63f049ec92be79add681b9cd85b4b3841
816e78209bf7330cb31e3171dc7776ccedcc0d60
......@@ -52,6 +52,10 @@
"target": "Package",
"version": "[5.0.17, )"
},
"Microsoft.AspNetCore.Mvc.NewtonsoftJson": {
"target": "Package",
"version": "[5.0.17, )"
},
"Microsoft.EntityFrameworkCore.Design": {
"include": "Runtime, Build, Native, ContentFiles, Analyzers, BuildTransitive",
"suppressParent": "All",
......@@ -67,6 +71,10 @@
"suppressParent": "All",
"target": "Package",
"version": "[5.0.17, )"
},
"Microsoft.VisualStudio.Web.CodeGeneration.Design": {
"target": "Package",
"version": "[5.0.2, )"
}
},
"imports": [
......
......@@ -19,7 +19,7 @@
<Import Project="$(NuGetPackageRoot)microsoft.entityframeworkcore.design\5.0.17\build\netcoreapp3.0\Microsoft.EntityFrameworkCore.Design.props" Condition="Exists('$(NuGetPackageRoot)microsoft.entityframeworkcore.design\5.0.17\build\netcoreapp3.0\Microsoft.EntityFrameworkCore.Design.props')" />
</ImportGroup>
<PropertyGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
<PkgNewtonsoft_Json Condition=" '$(PkgNewtonsoft_Json)' == '' ">C:\Users\HASAN\.nuget\packages\newtonsoft.json\10.0.1</PkgNewtonsoft_Json>
<PkgMicrosoft_CodeAnalysis_Analyzers Condition=" '$(PkgMicrosoft_CodeAnalysis_Analyzers)' == '' ">C:\Users\HASAN\.nuget\packages\microsoft.codeanalysis.analyzers\3.0.0</PkgMicrosoft_CodeAnalysis_Analyzers>
<PkgMicrosoft_EntityFrameworkCore_Tools Condition=" '$(PkgMicrosoft_EntityFrameworkCore_Tools)' == '' ">C:\Users\HASAN\.nuget\packages\microsoft.entityframeworkcore.tools\5.0.17</PkgMicrosoft_EntityFrameworkCore_Tools>
</PropertyGroup>
</Project>
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed.
......@@ -7,6 +7,8 @@ using System;
using System.Threading.Tasks;
using WebPresentation.Filters.ImageLoad;
using AutoMapper;
using ApplicationCore.Interfaces.IAuthentication;
using ApplicationCore.DTOs;
namespace WebPresentation.Controllers
{
......@@ -15,62 +17,52 @@ namespace WebPresentation.Controllers
public class AccessController : Controller
{
private readonly IMapper _mapper;
private readonly UserManager<User> _userManager;
private readonly SignInManager<User> _signInManager;
public AccessController(SignInManager<User> signInManager,
UserManager<User> userManager,
private readonly IAuthenticationManager _authenticationManager;
public AccessController(IAuthenticationManager authenticationManager,
IMapper mapper )
{
_mapper = mapper;
_userManager = userManager;
_signInManager = signInManager;
_authenticationManager = authenticationManager;
}
public string ErrorMessage { get; set; }
public IActionResult Login(string returnUrl )
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
public IActionResult Register(string returnUrl = null)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
[HttpPost]
public async Task<IActionResult> Login(LoginInuptModel Input)
{
Input.ReturnUrl ??= Url.Content("/Home/Index");
public async Task<IActionResult> Login(LoginInuptModel Input)
{
Input.ReturnUrl ??= Url.Content("/Home/Index");
ViewBag.ReturUrl = Input.ReturnUrl;
ViewBag.ReturUrl = Input.ReturnUrl;
if (ModelState.IsValid)
if (ModelState.IsValid){
LoginInputDTO loginInupt = _mapper.Map<LoginInputDTO>(Input);
var result = await _authenticationManager.Authenticate(loginInupt);
if (result)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
return Redirect(Input.ReturnUrl);
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View();
}
return Redirect(Input.ReturnUrl);
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View();
}
// If we got this far, something failed, redisplay form
return View();
}
public IActionResult Register(string returnUrl = null)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
[HttpPost]
[ImageLoadFilter]
public async Task<IActionResult> Register(RegisterationInputModel Input)
......@@ -80,29 +72,13 @@ namespace WebPresentation.Controllers
ViewBag.ReturUrl = Input.ReturnUrl;
if (ModelState.IsValid)
{
var patient = _mapper.Map<Patient>(Input.Patient);
var user = new User {
NormalizedEmail = Input.Email,
FirstName=Input.FirstName,
LastName=Input.LastName,
Avatar=Input.ImageName,
UserName = Input.Email,
Email = Input.Email,
Patient = patient,
CreationTime = DateTime.Now,
};
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)
{
result = await _userManager.AddToRoleAsync(user, "patient");
}
RegisterInputDTO registerInput = _mapper.Map<RegisterInputDTO>(Input);
var result = await _authenticationManager.Register(registerInput);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return LocalRedirect(Input.ReturnUrl);
return LocalRedirect(Input.ReturnUrl);
}
foreach (var error in result.Errors)
......@@ -111,13 +87,12 @@ namespace WebPresentation.Controllers
}
}
// If we got this far, something failed, redisplay form
return View();
}
public async Task<IActionResult> Logout(string returnUrl = null)
{
await _signInManager.SignOutAsync();
await _authenticationManager.SignOut();
if (returnUrl != null)
{
return Redirect(returnUrl);
......
using ApplicationCore.DTOs;
using ApplicationDomain.Entities;
using AutoMapper;
using WebPresentation.ViewModel.Identity;
using WebPresentation.ViewModels;
namespace ApplicationCore.Mappere
......@@ -39,6 +40,8 @@ namespace ApplicationCore.Mappere
CreateMap<CategoryDTO, CategoryViewModel>().ReverseMap();
CreateMap<MedicineTypeDTO, MedicineTypeViewModel>().ReverseMap();
CreateMap<RegisterInputDTO, RegisterationInputModel>().ReverseMap();
CreateMap<LoginInputDTO, LoginInuptModel>().ReverseMap();
CreateMap<MedicalStateMedicineDTO, MedicalStateMedicineVModel>().ReverseMap();
......
Support for ASP.NET Core Identity was added to your project.
For setup and configuration information, see https://go.microsoft.com/fwlink/?linkid=2116645.
......@@ -22,6 +22,8 @@ using Microsoft.AspNetCore.Http;
using ApplicationCore.Mappere;
using WebPresentation.Filters.ModelStateValidation;
using WebPresentation.Services;
using ApplicationCore.Interfaces.IAuthentication;
using ApplicationCore.Authentication;
namespace WebPresentation
{
......@@ -37,10 +39,22 @@ namespace WebPresentation
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
#region ADD DB Context
services.AddScoped<DbContext, MedicDbContext>();
services.AddDbContext<MedicDbContext>(
options => {
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
});
# endregion ADD DB Context
#region Mapper Config
services.AddScoped<Mapper>();
services.AddAutoMapper(typeof(ObjectMapper), typeof(ViewModelObjectMapper));
#endregion Mpper Config
#region Cors
services.AddCors(options =>
{
......@@ -52,9 +66,9 @@ namespace WebPresentation
.AllowCredentials());
});
#endregion Cors
services.AddAutoMapper(typeof(ObjectMapper),typeof(ViewModelObjectMapper));
#region ADD Scoped Repository
#region ADD Scopped Repository
services.AddScoped(typeof(IUnitOfWork<>),typeof(UnitOfWork<>));
services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
......@@ -63,24 +77,15 @@ namespace WebPresentation
services.AddScoped<IPatientRepository, PatientRepository>();
services.AddScoped<IIngredientRepository, IngredientRepository>();
#endregion ADD Scope dRepository
#endregion ADD Scopped Repository
#region ADD Scoped Services
#region ADD Scopped Services
services.AddScoped<IPatientService, PatientService>();
services.AddScoped<IMedicalStateService, MedicalStateService>();
services.AddScoped<IMedicineService, MedicineService>();
services.AddScoped<IIngredientService, IngredientService>();
#endregion ADD Scoped Services
#endregion ADD Scopped Services
#region ADD DB Context
services.AddDbContext<MedicDbContext>(options => {
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
;
}
); ;
# endregion ADD DB Context
#region ADD Identity
services
.AddIdentity<User, IdentityRole>()
......@@ -90,6 +95,7 @@ namespace WebPresentation
#endregion ADD Identity
#region ADD Authentication Schema
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(
options =>
......@@ -125,13 +131,27 @@ namespace WebPresentation
);
#endregion ADD Authentication Schema
#region ADD Session
services.AddSession();
#endregion ADD Session
#region register image service
services.AddScoped<IImageService,ImageService>();
#endregion register image service
#region ADD atuhentication manager
services.AddScoped<IAuthenticationManager,AuthenticationManager>();
#endregion ADD atuhentication manager
services.AddScoped<StateValidationFilter>();
services.AddControllersWithViews().AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
services.AddControllersWithViews()
.AddNewtonsoftJson(
options =>
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
}
......
......@@ -1955,7 +1955,9 @@
"ApplicationDomain": "1.0.0",
"AutoMapper.Extensions.Microsoft.DependencyInjection": "5.0.1",
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "5.0.17",
"Microsoft.EntityFrameworkCore.SqlServer": "5.0.17"
"Microsoft.AspNetCore.Mvc.NewtonsoftJson": "5.0.17",
"Microsoft.EntityFrameworkCore.SqlServer": "5.0.17",
"Microsoft.VisualStudio.Web.CodeGeneration.Design": "5.0.2"
},
"runtime": {
"ApplicationCore.dll": {}
......
......@@ -52,6 +52,10 @@
"target": "Package",
"version": "[5.0.17, )"
},
"Microsoft.AspNetCore.Mvc.NewtonsoftJson": {
"target": "Package",
"version": "[5.0.17, )"
},
"Microsoft.EntityFrameworkCore.Design": {
"include": "Runtime, Build, Native, ContentFiles, Analyzers, BuildTransitive",
"suppressParent": "All",
......@@ -67,6 +71,10 @@
"suppressParent": "All",
"target": "Package",
"version": "[5.0.17, )"
},
"Microsoft.VisualStudio.Web.CodeGeneration.Design": {
"target": "Package",
"version": "[5.0.2, )"
}
},
"imports": [
......
......@@ -2156,7 +2156,9 @@
"ApplicationDomain": "1.0.0",
"AutoMapper.Extensions.Microsoft.DependencyInjection": "5.0.1",
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "5.0.17",
"Microsoft.EntityFrameworkCore.SqlServer": "5.0.17"
"Microsoft.AspNetCore.Mvc.NewtonsoftJson": "5.0.17",
"Microsoft.EntityFrameworkCore.SqlServer": "5.0.17",
"Microsoft.VisualStudio.Web.CodeGeneration.Design": "5.0.2"
},
"compile": {
"bin/placeholder/ApplicationCore.dll": {}
......
{
"version": 2,
"dgSpecHash": "aE4Ew/iUWdocDBn0xTuc9FBCMrp4DcFmFOQ4/3nqi2ERl4yCO6t34MzVyYa28vRRUpjD1b6jq3b9ZjyXzCICVw==",
"dgSpecHash": "Es0EFeAcbWbgIN8iLV78jpXPvlj41iwwnUZwiRCo2slTnRC9b4Ps3lPLVE9zRF1PqrCPGd2GnAxhNbTpxcORrg==",
"success": true,
"projectFilePath": "C:\\Users\\HASAN\\Desktop\\Medic\\WebPresentation\\WebPresentation.csproj",
"expectedPackageFiles": [
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment