Commit 60ef3ecb authored by hasan khaddour's avatar hasan khaddour

add api project

parent 508ae697
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace API.Models
{
public class LoginInuptModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Display(Name = "Remember me")]
public bool RememberMe { get; set; }
public String ReturnUrl { get; set; }
}
}
using ApplicationDomain.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace API.Models
{
public class RegisterationInputModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
public string Avatar { get; set; }
[Required]
public Patient Patient { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 3)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
public string ReturnUrl { get; set; }
}
}
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="5.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" 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.EntityFrameworkCore.Tools" Version="5.0.17">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="5.0.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ApplicationCore\ApplicationCore.csproj" />
<ProjectReference Include="..\ApplicationDomain\ApplicationDomain.csproj" />
<ProjectReference Include="..\Infrastructure\Infrastructure.csproj" />
</ItemGroup>
</Project>
using API.Models;
using ApplicationCore.DomainModel;
using ApplicationCore.Interfaces.IServices;
using ApplicationDomain.Entities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
namespace WebPresentation.Controllers
{
[Route("api/[controller]")]
[ApiController]
[AllowAnonymous]
public class AccessAPIController : BaseController
{
private readonly SignInManager<User> _signInManager;
private readonly IPatientService _patientSerivce;
public AccessAPIController(UserManager<User> userManager,
SignInManager<User> signInManager,
IPatientService patientService):base(userManager)
{
_signInManager = signInManager;
_patientSerivce = patientService;
}
[HttpPost("register")]
public async Task<IActionResult> Register([FromBody] RegisterationInputModel Input)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
var user = new User
{
NormalizedEmail = Input.Email,
FirstName = Input.FirstName,
LastName = Input.LastName,
Avatar = Input.Avatar,
UserName = Input.Email,
Email = Input.Email,
Patient = Input.Patient,
CreationTime = DateTime.Now,
};
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
PatientModel p =await _patientSerivce.GetByUserEmail(Input.Email);
return Ok(new {patient =p});
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
return BadRequest(ModelState);
}
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] LoginInuptModel model)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
PatientModel p = await _patientSerivce.GetByUserEmail(model.Email);
return Ok(new
{
message = "Registration successful"
,
patient = p
});
}
if (result.IsLockedOut)
{
return Forbid("User is locked out.");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return Unauthorized(ModelState);
}
}
[HttpGet("log")]
public IActionResult i()
{
return Ok(new { message = "Logout successful" });
}
[HttpPost("logout")]
public async Task<IActionResult> Logout()
{
await _signInManager.SignOutAsync();
return Ok(new { message = "Logout successful" });
}
}
}
\ No newline at end of file
using ApplicationDomain.Entities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using System;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
namespace WebPresentation.Controllers
{
[Authorize]
[ApiController]
public abstract class BaseController : ControllerBase
{
protected readonly UserManager<User> _userManager;
public BaseController(UserManager<User> userManager ) {
_userManager = userManager;
}
#region Current User Details
protected User GetCurrentUser() {
User usr = GetCurrentUserAsync().Result;
return usr;
}
private Task<User> GetCurrentUserAsync()
{
return _userManager.GetUserAsync(User);
}
protected String GetUserName() {
return GetCurrentUser().UserName;
}
protected String GetUserId() {
return GetCurrentUser().Id;
}
#endregion Current User Details
}
}
using ApplicationCore.DomainModel;
using ApplicationCore.Interfaces;
using ApplicationDomain.Entities;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace WebPresentation.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CrudAPIController<TModel> : BaseController where TModel : DomainBase
{
protected readonly IService<TModel> _service;
public CrudAPIController(
IService<TModel> service,
UserManager<User> userManager)
: base(userManager)
{
_service = service;
}
public async virtual Task<IActionResult> GetAll()
{
IEnumerable<TModel> models = await _service.GetAll();
return Ok(models);
}
[HttpGet("{id}")]
public async Task<IActionResult> GetById(int id)
{
var model = await _service.GetDetails(id);
if (model == null)
{
return NotFound();
}
return Ok(model);
}
[HttpPost("update")]
public IActionResult Update(int id, TModel model )
{
if (id != model.Id)
return Unauthorized();
var ModifiedModel = _service.Update(model);
return Ok(ModifiedModel);
}
[HttpPut("delete")]
public IActionResult Delete(int id)
{
_service.Delete(id);
return Ok(new { mesage ="deleted"});
}
[HttpPost("create")]
public IActionResult Create(TModel model)
{
_service.Create(model);
return Ok(new { mesage = "deleted" });
}
}
}
using ApplicationCore.DomainModel;
using ApplicationCore.Interfaces.IServices;
using ApplicationDomain.Entities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebPresentation.Controllers
{
[Route("api/[controller]")]
[ApiController]
[AllowAnonymous]
public class MedicalStateApiController : CrudAPIController<MedicalStateModel>
{
private readonly IPatientService _patientService;
public MedicalStateApiController(
IMedicalStateService medicalstateService,
IPatientService patientService,
UserManager<User> userManager)
:base(medicalstateService, userManager)
{
_patientService = patientService;
}
public override async Task<IActionResult> GetAll()
{
string u = GetUserId();
var ps = await _patientService.GetAll();
var pId=ps.Where(p => p.User.Id == u).FirstOrDefault().Id;
var meds = ((IMedicalStateService)_service).GetAllPatientMedicalStates(pId);
return Ok(meds);
}
[HttpGet("GetMedicines")]
public async Task<IActionResult> GetMedicalStateMedicine(int id)
{
var r = await ((IMedicalStateService)_service).GetDetails(id);
return Ok(r.Medicines);
}
}
}
using ApplicationCore.DomainModel;
using ApplicationCore.Interfaces.IServices;
using ApplicationDomain.Entities;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebPresentation.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class MedicineAPIController : CrudAPIController<MedicineModel>
{
public MedicineAPIController(
IMedicineService medicalstateService,
UserManager<User> userManager)
: base(medicalstateService, userManager)
{
}
[HttpPost("AddMedicineT")]
public IActionResult AddMedicineT(int id, int med)
{
try
{
((IMedicineService)_service).AddToMedicalState(new MedicalStateMedicineModel { MedicalStateId = id, MedicineId = med });
return Ok(new {message= "Added"});
}
catch
{
return NotFound(new { message = "faild" });
}
}
[HttpPost("RemoveMedicineJ")]
public IActionResult RemoveMedicineJ(int id, int med)
{
((IMedicineService)_service).RemoveFromMedicalState(new MedicalStateMedicineModel { MedicalStateId = id, MedicineId = med });
return Ok(new { message = "REmoved" });
}
}
}
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace API
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:34139",
"sslPort": 44390
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": false,
"launchUrl": "weatherforecast",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"API": {
"commandName": "Project",
"dotnetRunMessages": "true",
"launchBrowser": false,
"launchUrl": "weatherforecast",
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
using ApplicationCore.Interfaces.IServices;
using ApplicationCore.Mapper;
using ApplicationCore.Services;
using ApplicationDomain.Abstraction;
using ApplicationDomain.Repositories;
using Infrastructure.Data;
using Infrastructure.Repository;
using Infrastructure.UnitOfWork;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using ApplicationDomain.Entities;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using AutoMapper;
namespace API
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSession( );
services.AddDistributedMemoryCache();
services.AddScoped<DbContext, MedicDbContext>();
services.AddScoped<Mapper>();
services.AddCors(options =>
{
options.AddPolicy("AllowFrontend",
builder => builder
.WithOrigins("http://localhost:3000") // Add your frontend URL here
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials());
});
services.AddAutoMapper(typeof(ObjectMapper));
#region ADD Scoped Repository
services.AddScoped(typeof(IUnitOfWork<>), typeof(UnitOfWork<>));
services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
services.AddScoped<IMedicalStateRepository, MedicalStateRepository>();
services.AddScoped<IMedicineRepository, MedicineRepository>();
services.AddScoped<IPatientRepository, PatientRepository>();
services.AddScoped<IIngredientRepository, IngredientRepository>();
#endregion ADD Scope dRepository
#region ADD Scoped Services
services.AddScoped<IPatientService, PatientService>();
services.AddScoped<IMedicalStateService, MedicalStateService>();
services.AddScoped<IMedicineService, MedicineService>();
services.AddScoped<IIngredientService, IngredientService>();
#endregion ADD Scoped 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>()
.AddEntityFrameworkStores<MedicDbContext>()
.AddDefaultTokenProviders();
#endregion ADD Identity
#region ADD Authentication Schema
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(
options =>
{
options.LoginPath = "/Accessapi/Login";
options.LogoutPath = "/Accessapi/Logout";
options.AccessDeniedPath = "/Accessapi/Login";
}
);
services.ConfigureApplicationCookie(options =>
{
options.Cookie.HttpOnly = true;
options.Cookie.SameSite = SameSiteMode.None;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
options.LoginPath = "/accessapi/login";
options.LogoutPath = "/accessapi/logout";
options.AccessDeniedPath = "/accessapi/login";
options.SlidingExpiration = true;
});
services.AddAuthorization(
);
#endregion ADD Authentication Schema
services.AddControllers().AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors("AllowFrontend");
app.UseSession();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Data Source=.\\sqlexpress;Initial Catalog=portfoilo ;Integrated Security=True"
}
}
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