using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using ProRestaurant.Classes; using ProRestaurant.Containers; using ProRestaurant.DBContexts; using ProRestaurant.Models.Accounts; using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using System.Text; using System.Threading.Tasks; namespace ProRestaurant.Repository.Accounts { public interface IAuthenticateRepository { AuthenticationContiner Login(AuthenticationContiner user); AuthenticationContiner GetAuthenticationContiner(); } public class AuthenticateRepository : IAuthenticateRepository { private readonly DBContext dBContext; private readonly AppSettings appSettings; public AuthenticateRepository(DBContext _DB, IOptions _AppSettings) { dBContext = _DB; appSettings = _AppSettings.Value; } public AuthenticationContiner GetAuthenticationContiner() { return new AuthenticationContiner(); } public AuthenticationContiner Login(AuthenticationContiner user) { var getUser = dBContext.Users.Where(u => u.EmailAddress == user.EmailAddress).FirstOrDefault(); if (getUser != null) { if (getUser.Password == user.Password) { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(appSettings.Secret); var tokenDescription = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, getUser.Id.ToString()) }), Expires = DateTime.UtcNow.AddHours(1), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescription); user.Token = tokenHandler.WriteToken(token); user.Result = "Access Granted"; user.Name = getUser.FirstName; user.Surname = getUser.Surname; user.EmailAddress = getUser.EmailAddress; user.Password = ""; user.Role = getUser.SystemRole.ToString(); } else { user.Result = "Incorrect Password"; } } else { user.Result = "User Not Found."; } return user; } } }