Changeset d23bf72 for Farmatiko


Ignore:
Timestamp:
11/05/20 06:57:35 (4 years ago)
Author:
DimitarSlezenkovski <dslezenkovski@…>
Branches:
master
Children:
afc9a9a
Parents:
1f4846d
Message:

Add SystemService, Auth, fix a lil bugs :)

Location:
Farmatiko
Files:
2 added
1 deleted
11 edited

Legend:

Unmodified
Added
Removed
  • Farmatiko/ClientApp/src/app/login/login.component.html

    r1f4846d rd23bf72  
    66  <div class="example-container">
    77    <mat-form-field>
    8       <input matInput placeholder="Email" [(ngModel)]="this.username" formControlName="email">
     8      <input matInput placeholder="Email" [(ngModel)]="this.username" formControlName="username">
    99    </mat-form-field>
    1010
  • Farmatiko/ClientApp/src/app/shared/interfaces.ts

    r1f4846d rd23bf72  
    5555    Passwd: string;
    5656    Name: string;
     57    originalUserName?: string;
    5758    Role?: string;
    5859
  • Farmatiko/ClientApp/src/app/shared/services/auth.service.ts

    r1f4846d rd23bf72  
    1111  username: string;
    1212  role: string;
     13  originalUserName?: string;
    1314  accessToken: string;
    1415  refreshToken: string;
    15   head: IPharmacyHead;
     16  head?: IPharmacyHead;
    1617}
    1718
     
    3536        this.http.get<LoginResult>(`${this.apiUrl}/user`).subscribe((x) => {
    3637          this._user.next({
    37             Email: x.username,
    38             Role: x.role,
     38            Email: x.head.Email,
     39            Role: x.head.Role,
     40            originalUserName: x.head.originalUserName,
    3941            Passwd: x.head.Passwd,
    40             Name: x.head.Name
     42            Name: x.head.Name,
     43            PharmacyMedicines: x.head.PharmacyMedicines,
     44            Pharmacy: x.head.Pharmacy
    4145          });
    4246        });
     
    6064        map((x) => {
    6165          this._user.next({
    62             Email: x.username,
    63             Role: x.role,
     66            Email: x.head.Email,
     67            Role: x.head.Role,
     68            originalUserName: x.head.originalUserName,
    6469            Passwd: x.head.Passwd,
    65             Name: x.head.Name
     70            Name: x.head.Name,
     71            PharmacyMedicines: x.head.PharmacyMedicines,
     72            Pharmacy: x.head.Pharmacy
    6673          });
    6774          this.setLocalStorage(x);
     
    98105        map((x) => {
    99106          this._user.next({
    100             Email: x.username,
    101             Role: x.role,
     107            Email: x.head.Email,
     108            Role: x.head.Role,
     109            originalUserName: x.head.originalUserName,
    102110            Passwd: x.head.Passwd,
    103             Name: x.head.Name
     111            Name: x.head.Name,
     112            PharmacyMedicines: x.head.PharmacyMedicines,
     113            Pharmacy: x.head.Pharmacy
    104114          });
    105115          this.setLocalStorage(x);
  • Farmatiko/ClientApp/src/environments/environment.ts

    r1f4846d rd23bf72  
    55export const environment = {
    66  production: false,
    7   baseApiUrl: 'https://localhost:44342/',
     7  baseApiUrl: 'https://localhost:5001/',
    88};
    99
  • Farmatiko/Controllers/AdminController.cs

    r1f4846d rd23bf72  
    55using FarmatikoData.Models;
    66using FarmatikoServices.FarmatikoServiceInterfaces;
     7using Microsoft.AspNetCore.Authorization;
    78using Microsoft.AspNetCore.Mvc;
    89
    910namespace Farmatiko.Controllers
    1011{
     12    [ApiController]
     13    [Authorize(Roles = "PharmacyHead")]
    1114    public class AdminController : Controller
    1215    {
     
    4043        [HttpPost]
    4144        [Route("api/pharmacyhead/add")]
    42         public async Task<IActionResult> AddPharmacyHead(PharmacyHead pharmacyHead)
     45        public async Task<IActionResult> AddPharmacyHead([FromBody]PharmacyHead pharmacyHead)
    4346        {
    4447            await _service.AddPharmacyHead(pharmacyHead);
     
    4649        }
    4750
    48         [HttpPost]
     51        [HttpDelete]
    4952        [Route("api/pharmacyhead/delete/{Id}")]
    50         public async Task<IActionResult> RemovePharmacyHead([FromQuery]int Id)
     53        public async Task<IActionResult> RemovePharmacyHead([FromRoute] int Id)
    5154        {
    5255            await _service.RemovePharmacyHead(Id);
    5356            return Ok();
    5457        }
    55         [HttpPost]
    56         public IActionResult RejectRequset(RequestPharmacyHead req)
     58        [HttpDelete]
     59        [Route("api/pharmacyhead/requests/{Id}")]
     60        public IActionResult RejectRequest([FromRoute] int Id)
    5761        {
    58             bool Success = _adminService.RejectRequest(req);
     62            bool Success = _adminService.RejectRequest(Id);
    5963            return Ok(Success);
    6064        }
    6165        [HttpPost]
    62         public async Task<IActionResult> ApproveRequest(PharmacyHead pharmacyHead)
     66        [Route("api/pharmacyhead/{Id}")]
     67        public async Task<IActionResult> ApproveRequest([FromRoute]int Id, [FromBody]PharmacyHead pharmacyHead)
    6368        {
     69            int id = Id;
    6470            await _phservice.UpdatePharmacyHead(pharmacyHead);
    6571            return Ok();
  • Farmatiko/Controllers/ErrorController.cs

    r1f4846d rd23bf72  
    1 using System;
    2 using System.Collections.Generic;
    3 using System.Linq;
    4 using System.Threading.Tasks;
     1using System.Net;
     2using Microsoft.AspNetCore.Diagnostics;
    53using Microsoft.AspNetCore.Mvc;
     4using Microsoft.Extensions.Logging;
    65
    76namespace Farmatiko.Controllers
    87{
     8    [ApiController]
    99    public class ErrorController : Controller
    1010    {
    11         public IActionResult Index()
     11        private readonly ILogger<ErrorController> _logger;
     12
     13        public ErrorController(ILogger<ErrorController> logger)
    1214        {
    13             return View();
     15            _logger = logger;
     16        }
     17        [Route("/Error")]
     18        public IActionResult Error()
     19        {
     20            var exception = HttpContext.Features.Get<IExceptionHandlerFeature>();
     21            var statusCode = exception.Error.GetType().Name switch
     22            {
     23                "ArgumentException" => HttpStatusCode.BadRequest,
     24                "Exception" => HttpStatusCode.InternalServerError,
     25                /*"NotFoundResult" => HttpStatusCode.NotFound,*/
     26                _ => HttpStatusCode.ServiceUnavailable
     27            };
     28            _logger.LogInformation(statusCode.ToString() + " " + exception.ToString());
     29            return Problem(detail: exception.Error.Message, statusCode: (int)statusCode);
    1430        }
    1531    }
  • Farmatiko/Controllers/FarmatikoController.cs

    r1f4846d rd23bf72  
    1111    {
    1212        private readonly IService _service;
    13         public FarmatikoController(IService service)
     13        private readonly IProcessJSONService _JSONservice;
     14        public FarmatikoController(IService service, IProcessJSONService JSONservice)
    1415        {
    1516            _service = service;
     17            _JSONservice = JSONservice;
    1618        }
    1719        // Workers
    1820        //Get
     21        [HttpGet]
     22        [Route("api/getData")]
     23        public void InsertData()
     24        {
     25            //_JSONservice.DownloadPharmaciesExcel();
     26            //_JSONservice.GetProcessedHealthcareWorkersFromJSON();
     27            //_JSONservice.GetProcessedHealthFacilitiesFromJSON();
     28            //_JSONservice.GetProcessedMedicinesFromJSON();
     29            //_JSONservice.GetProcessedPandemicsFromJSONApi();
     30        }
    1931        [HttpGet]
    2032        [Route("api/workers")]
     
    2537        }
    2638        [HttpGet]
    27         [Route("api/workers/search/{Query}")]
    28         public async Task<IEnumerable<HealthcareWorker>> SearchWorkers(string Query)
     39        [Route("api/workers/search/{query}")]
     40        public async Task<IEnumerable<HealthcareWorker>> SearchWorkers([FromRoute]string query)
    2941        {
    30             return await _service.SearchWorkers(Query);
     42            return await _service.SearchWorkers(query);
    3143        }
    3244        [HttpGet]
    3345        [Route("api/workers/{id}")]
    34         public async Task<HealthcareWorker> GetWorker(int Id)
     46        public async Task<HealthcareWorker> GetWorker([FromRoute] int Id)
    3547        {
    3648            return await _service.GetWorker(Id);
     
    4860        }
    4961        [HttpGet]
    50         [Route("api/facilities/search/{Query}")]
    51         public async Task<IEnumerable<HealthFacility>> SearchFacilities(string Query)
     62        [Route("api/facilities/search/{query}")]
     63        public async Task<IEnumerable<HealthFacility>> SearchFacilities([FromRoute] string query)
    5264        {
    53             return await _service.SearchFacilities(Query);
     65            return await _service.SearchFacilities(query);
    5466        }
    5567        [HttpGet]
    56         [Route("api/facilities/{Id}")]
    57         public async Task<HealthFacility> GetFacility(int Id)
     68        [Route("api/facilities/{id}")]
     69        public async Task<HealthFacility> GetFacility([FromRoute] int id)
    5870        {
    59             return await _service.GetFacility(Id);
     71            return await _service.GetFacility(id);
    6072        }
    6173        //Post
     
    7082        }
    7183        [HttpGet]
    72         [Route("api/medicines/search/{Query}")]
    73         public async Task<IEnumerable<Medicine>> SearchMedicines(string Query)
     84        [Route("api/medicines/search/{query}")]
     85        public async Task<IEnumerable<Medicine>> SearchMedicines([FromRoute] string query)
    7486        {
    75             return await _service.SearchMedicines(Query);
     87            return await _service.SearchMedicines(query);
    7688        }
    7789        [HttpGet]
    7890        [Route("api/medicines/{Id}")]
    79         public async Task<Medicine> GetMedicine(int Id)
     91        public async Task<Medicine> GetMedicine([FromRoute] int Id)
    8092        {
    8193            return await _service.GetMedicine(Id);
     
    98110        [HttpGet]
    99111        [Route("api/pharmacy/search/{Query}")]
    100         public async Task<IEnumerable<Pharmacy>> SearchPharmacies(string Query)
     112        public async Task<IEnumerable<Pharmacy>> SearchPharmacies([FromRoute] string Query)
    101113        {
    102114            return await _service.SearchPharmacies(Query);
     
    104116        [HttpGet]
    105117        [Route("api/pharmacy/{Id}")]
    106         public async Task<Pharmacy> GetPharmacy(int Id)
     118        public async Task<Pharmacy> GetPharmacy([FromRoute] int Id)
    107119        {
    108120            return await _service.GetPharmacy(Id);
  • Farmatiko/Controllers/PharmacyHeadController.cs

    r1f4846d rd23bf72  
    1 using System.Collections;
    2 using System.Collections.Generic;
    3 using System.Linq;
     1using System.Collections.Generic;
    42using System.Threading.Tasks;
    5 using FarmatikoData.FarmatikoRepoInterfaces;
    63using FarmatikoData.Models;
    74using FarmatikoServices.FarmatikoServiceInterfaces;
     5using Microsoft.AspNetCore.Authorization;
    86using Microsoft.AspNetCore.Mvc;
    97
     
    119{
    1210    [ApiController]
     11    [Authorize(Roles = "PharmacyHead")]
    1312    public class PharmacyHeadController : Controller
    1413    {
     
    2019
    2120        //GET
    22         //Mi trebaat rutite
    23         [HttpGet]
     21        /*[HttpGet]
    2422        [Route("api/pharmacyhead")]
    25         public async Task<IEnumerable<PharmacyHead>> GetPharmacyHeadInfo(string Token)
     23        public async Task<IEnumerable<PharmacyHead>> GetPharmacyHeadInfo()
    2624        {
    27             var PHeads = await _PHService.GetPharmacyHeadInfo(Token);
     25            var PHeads = await _PHService.GetPharmacyHeadInfo();
    2826            return PHeads;
    29         }
     27        }*/
    3028        [HttpGet]
    3129        [Route("api/pharmacyhead/{Id}")]
    32         public async Task<PharmacyHead> GetPharmacyHeadById(int Id)
     30        public async Task<PharmacyHead> GetPharmacyHeadById([FromRoute]int Id)
    3331        {
    3432            var Phead = await _PHService.GetPharmacyHeadByIdAsync(Id);
     
    3836        [HttpPost]
    3937        [Route("api/pharmacyhead/add")]
    40         public async Task<IActionResult> AddPharmacyHead(PharmacyHead pharmacyHead)
     38        public async Task<IActionResult> AddPharmacyHead([FromBody]PharmacyHead pharmacyHead)
    4139        {
    4240            bool Success = await _PHService.Add(pharmacyHead);
     
    4442        }
    4543
    46         [HttpPost]
     44        /*[HttpPost]
    4745        [Route("api/pharmacyhead/login")]
    4846        public async Task<int> Login([FromBody]PharmacyHead pharmacyHead)
    4947        {
    5048            return await _PHService.Login(pharmacyHead);
    51         }
     49        }*/
    5250        [HttpPut]
    5351        [Route("api/pharmacyhead/{Id}")]
     
    5856        [HttpPost]
    5957        [Route("api/pharmacyhead/requests")]
    60         public async Task<IActionResult> ClaimPharmacy(RequestPharmacyHead pharmacy)
     58        public async Task<IActionResult> ClaimPharmacy([FromBody]RequestPharmacyHead pharmacy)
    6159        {
    6260            bool Success = await _PHService.ClaimPharmacy(pharmacy);
     
    6563        [HttpDelete]
    6664        [Route("api/pharmacyhead/delete/{Id}")]
    67         public async Task<IActionResult> Remove([FromQuery] int Id)
     65        public async Task<IActionResult> Remove([FromRoute] int Id)
    6866        {
    6967            bool Success = await _PHService.Remove(Id);
     
    7270        [HttpPost]
    7371        [Route("api/pharmacyhead/requests/{Id}")]
    74         public async Task<IActionResult> RemoveClaimingRequest([FromQuery] int Id)
     72        public async Task<IActionResult> RemoveClaimingRequest([FromRoute] int Id)
    7573        {
    7674            bool Success = await _PHService.RemoveClaimingRequest(Id);
  • Farmatiko/Farmatiko.csproj

    r1f4846d rd23bf72  
    1414
    1515  <ItemGroup>
     16    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.9" />
    1617    <PackageReference Include="Microsoft.AspNetCore.SpaServices.Extensions" Version="3.1.6" />
    1718    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.6" />
  • Farmatiko/Startup.cs

    r1f4846d rd23bf72  
    77using FarmatikoData;
    88using Microsoft.EntityFrameworkCore;
    9 using FarmatikoServices;
    109using FarmatikoData.FarmatikoRepoInterfaces;
    1110using FarmatikoData.FarmatikoRepo;
     
    1312using FarmatikoServices.Services;
    1413using Microsoft.Extensions.Logging;
     14using Microsoft.AspNetCore.Authentication.JwtBearer;
     15using Microsoft.IdentityModel.Tokens;
     16using System.Text;
     17using FarmatikoServices.Auth;
     18using FarmatikoServices.Infrastructure;
     19using System;
    1520
    1621namespace Farmatiko
     
    5964
    6065            services.AddTransient<ILogger, Logger<ProcessJSONService>>();
     66
     67            // services.AddTransient<ISystemService, SystemService>();
     68
     69
     70            var jwtTokenConfig = Configuration.GetSection("jwtTokenConfig").Get<JwtTokenConfig>();
     71            services.AddSingleton(jwtTokenConfig);
     72
     73            services.AddAuthentication(o =>
     74            {
     75                o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
     76                o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
     77                o.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
     78            }).AddJwtBearer(x =>
     79            {
     80                x.RequireHttpsMetadata = true;
     81                x.SaveToken = true;
     82                x.TokenValidationParameters = new TokenValidationParameters
     83                {
     84                    ValidateIssuer = true,
     85                    ValidIssuer = jwtTokenConfig.Issuer,
     86                    ValidateIssuerSigningKey = true,
     87                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtTokenConfig.Secret)),
     88                    ValidAudience = jwtTokenConfig.Audience,
     89                    ValidateAudience = true,
     90                    ValidateLifetime = true,
     91                    ClockSkew = TimeSpan.FromMinutes(1)
     92                };
     93            });
     94
     95            /*.AddJwtBearer(cfg =>
     96                     {
     97                         cfg.RequireHttpsMetadata = false;
     98                         cfg.SaveToken = true;
     99                         cfg.IncludeErrorDetails = true;
     100                         cfg.TokenValidationParameters = new TokenValidationParameters()
     101                         {
     102                             ValidIssuer = Configuration.GetSection("TokenIssuer").Value,
     103                             ValidAudience = Configuration.GetSection("TokenIssuer").Value,
     104                             IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetSection("SecretKey").Value))
     105                         };
     106
     107                     });
     108*/
     109            services.AddSingleton<IJwtAuthManager, JwtAuthManager>();
     110            services.AddHostedService<JwtRefreshTokenCache>();
     111            services.AddScoped<IAuthService, AuthService>();
     112            //If we add imgs
     113            /*services.Configure<FormOptions>(o => {
     114                o.ValueLengthLimit = int.MaxValue;
     115                o.MultipartBodyLengthLimit = int.MaxValue;
     116                o.MemoryBufferThreshold = int.MaxValue;
     117            });*/
     118
    61119        }
    62120
     
    74132                app.UseHsts();
    75133            }
    76 
     134            app.UseExceptionHandler("/Error");
    77135            app.UseHttpsRedirection();
    78136            app.UseStaticFiles();
     137
     138            // if we add imgs
     139            /*app.UseStaticFiles(new StaticFileOptions()
     140            {
     141                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot")),
     142                RequestPath = new PathString("/wwwroot")
     143            });*/
     144
    79145            if (!env.IsDevelopment())
    80146            {
     
    84150            app.UseRouting();
    85151
     152            app.UseAuthentication();
     153            app.UseAuthorization();
     154
    86155            app.UseCors(MyAllowSpecificOrigins);
    87156
     
    90159                endpoints.MapControllerRoute(
    91160                    name: "default",
    92                     pattern: "{controller}/{action=Index}/{id?}");
     161                    pattern: "api/{controller}/{action=Index}/{id?}");
    93162            });
    94163
  • Farmatiko/appsettings.json

    r1f4846d rd23bf72  
    1212  "EPPlus": {
    1313    "ExcelPackage": {
    14       "LicenseContext": "NonCommercial" 
     14      "LicenseContext": "NonCommercial"
    1515    }
    1616  },
    17   "AllowedHosts": "*"
     17  "AllowedHosts": "*",
     18  "jwtTokenConfig": {
     19    "secret": "1234567890123456789",
     20    "issuer": "FARMATIKO",
     21    "audience": "FARMATIKO",
     22    "accessTokenExpiration": 20,
     23    "refreshTokenExpiration": 60
     24  },
     25  "SecretKey": "PEJcK2bD4E2BKdNmAlUl",
     26  "TokenIssuer": "FARMATIKOISSUER"
    1827}
Note: See TracChangeset for help on using the changeset viewer.