Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
7.3 kB
1
Indexable
Never
// configuring jwt in startup.cs/program.cs
services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = true;
                x.SaveToken = true;

                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ClockSkew = TimeSpan.Zero,
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });

app.UseAuthentication();
----------------------------------------------------------------------------------------------

// creating token
var tokenHandler = new JwtSecurityTokenHandler();
                var key = Encoding.ASCII.GetBytes(Helpers.KeyVault.GetJwtSecretKey());
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim(ClaimTypes.Name, ad.email),
                        new Claim(ClaimTypes.Role, "Admin")
                    }),

                    Expires = DateTime.Now.AddMinutes(15),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key),
                    SecurityAlgorithms.HmacSha256Signature)
                };
                var token = tokenHandler.CreateToken(tokenDescriptor);
                at.token = tokenHandler.WriteToken(token); // Getting jwt token.


-------------------------------------------------------------------------------------------------

// Authentication and Authorization
Authorize(Roles = "Admin")


--------------------------------------------------------------------------------------------------
using cesapi.Models;
using cesapi.Models.HelperModels;
using cesapi.Provider.IProvider;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace cesapi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class PersonController : ControllerBase
    {
        private readonly IProviderPerson _context;

        public PersonController(IProviderPerson context)
        {
            _context = context;
        }

        [HttpGet]
        public List<listPerson> ListAllPersons()
        {
            return _context.ListAllPerson();
        }

        [HttpGet("{id}"), Authorize(Roles = "Admin")]
        public ReturnEmployeeByIdModel GetPersonById(int id)
        {
            return _context.GetPersonById(id);
        }

        [HttpPost, Authorize(Roles = "Admin")]
        public statusWithValue AddPerson([FromForm] addPersonFE fe)
        {
            return _context.AddPerson(fe);
        }

        [HttpPost, Authorize(Roles = "Admin")]
        public string ValidateImage([FromForm] image fe)
        {
            return _context.ValidateImage(fe);
        }

        [HttpDelete("{id}"), Authorize(Roles = "Admin")]
        public bool DeletePerson(int id)
        {
            return _context.DeletePerson(id);
        }

        [HttpPut("{id}"), Authorize(Roles = "Admin")]
        public statusWithValue EditPerson(int id, [FromForm] addPersonFE person)
        {
            return _context.EditPerson(id, person);
        }

        [HttpPost, Authorize(Roles = "Admin")]
        public string UploadQR([FromForm] qrupload qr)
        {
            return _context.UploadQR(qr);
        }

        [HttpGet("{email}"), Authorize(Roles = "Admin")]
        public bool ValidateEmail(string email)
        {
            return _context.ValidateEmail(email);
        }

        [HttpGet("{empid}"), Authorize(Roles = "Admin")]
        public bool ValidateEmployee(int empid)
        {
            return _context.ValidateEmployee(empid);
        }

        [HttpGet("{facilityId}/{cameraId}/{decodeqr}")]
        public ReturnValueForQR ValidateQR(int facilityId, int cameraId, string decodeqr)
        {
            return _context.ValidateEmployee(facilityId, cameraId, decodeqr);
        }

        [HttpGet("{token}"), Authorize(Roles = "Admin")]
        public string RequestDoor(string token)
        {
            return _context.RequestDoor(token);
        }

        [HttpPost]
        public ReturndoorLockStatus GetLockStatus(DoorLockStatus ds)
        {
            return _context.GetDoorStatus(ds);
        }


        [HttpPost]
        public IActionResult FailureNonRegularized([FromForm] nonRegularized nr)
        {
            bool result = _context.failureLogs(nr);

            if (result)
                return Ok();

            return BadRequest("Invalid Credentials!");
        }

        [HttpPost]
        public IActionResult FailureRegularized([FromForm] regularized nr)
        {
            bool result = _context.failureLogs(nr);

            if (result)
                return Ok();

            return BadRequest("Invalid Credentials!");
        }

        [HttpPost]
        public IActionResult GetPersonAccess(inputPersonAccess ipa)
        {
            string result = _context.GetPersonAccess(ipa);
            personAccessResult par = new personAccessResult()
            {
                accessStatus = result == "True" ? true : false
            };

            if (result.Equals("Invalid"))
                return BadRequest("Invalid Credentials!");

            return Ok(par);
        }

        [HttpPost]
        public IActionResult CheckIn(checkIn ci)
        {
            var result = _context.CheckIn(ci);
            if (result != null)
                return Ok(result);

            return BadRequest("Invalid AzpersonId or DoorCameraId");
        }

        [HttpPost]
        public IActionResult CheckOut(checkIn ci)
        {
            string result = _context.CheckOut(ci);

            if (result.Equals("Success"))
                return Ok();

            return BadRequest(result);
        }

        [HttpPost]
        public IActionResult GetEmpDetails(azdoor ad)
        {
            var result = _context.getEmpDetails(ad);
            if (result != null)
                return Ok(result);

            return BadRequest("Invalid AzpersonId or DoorCameraId");
        }

        [HttpPost]
        public IActionResult DoorLockClose(inputDoorCameraId idc)
        {
            bool result = _context.DoorLockClose(idc);

            if (result)
                return Ok();

            return BadRequest("Invalid Credentials!");
        }


        [HttpGet("{email}/{name}/{lnk}/{code}")]
        public string SendMail(string email, string name, string lnk, string code)
        {
            return _context.SendMail(email, name, lnk, code);
        }



    }
}