You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AuthenticateRepository.cs 2.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using Microsoft.AspNetCore.Mvc;
  2. using Microsoft.Extensions.Options;
  3. using Microsoft.IdentityModel.Tokens;
  4. using ProRestaurant.Classes;
  5. using ProRestaurant.Containers;
  6. using ProRestaurant.DBContexts;
  7. using ProRestaurant.Models.Accounts;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.IdentityModel.Tokens.Jwt;
  11. using System.Linq;
  12. using System.Security.Claims;
  13. using System.Text;
  14. using System.Threading.Tasks;
  15. namespace ProRestaurant.Repository.Accounts
  16. {
  17. public interface IAuthenticateRepository
  18. {
  19. AuthenticationContiner Login(AuthenticationContiner user);
  20. AuthenticationContiner GetAuthenticationContiner();
  21. }
  22. public class AuthenticateRepository : IAuthenticateRepository
  23. {
  24. private readonly DBContext dBContext;
  25. private readonly AppSettings appSettings;
  26. public AuthenticateRepository(DBContext _DB, IOptions<AppSettings> _AppSettings)
  27. {
  28. dBContext = _DB;
  29. appSettings = _AppSettings.Value;
  30. }
  31. public AuthenticationContiner GetAuthenticationContiner()
  32. {
  33. return new AuthenticationContiner();
  34. }
  35. public AuthenticationContiner Login(AuthenticationContiner user)
  36. {
  37. var getUser = dBContext.Users.Where(u => u.EmailAddress == user.EmailAddress).FirstOrDefault();
  38. if (getUser != null)
  39. {
  40. if (getUser.Password == user.Password)
  41. {
  42. var tokenHandler = new JwtSecurityTokenHandler();
  43. var key = Encoding.ASCII.GetBytes(appSettings.Secret);
  44. var tokenDescription = new SecurityTokenDescriptor
  45. {
  46. Subject = new ClaimsIdentity(new Claim[]
  47. {
  48. new Claim(ClaimTypes.Name, getUser.Id.ToString())
  49. }),
  50. Expires = DateTime.UtcNow.AddHours(1),
  51. SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
  52. };
  53. var token = tokenHandler.CreateToken(tokenDescription);
  54. user.Token = tokenHandler.WriteToken(token);
  55. user.Result = "Access Granted";
  56. user.Name = getUser.FirstName;
  57. user.Surname = getUser.Surname;
  58. user.EmailAddress = getUser.EmailAddress;
  59. user.Password = "";
  60. user.Role = getUser.SystemRole.ToString();
  61. }
  62. else
  63. {
  64. user.Result = "Incorrect Password";
  65. }
  66. }
  67. else
  68. {
  69. user.Result = "User Not Found.";
  70. }
  71. return user;
  72. }
  73. }
  74. }