TirsvadCLI Portfolio Library
Loading...
Searching...
No Matches
UserManager.cs
1using Microsoft.AspNetCore.Cryptography.KeyDerivation;
2using Microsoft.EntityFrameworkCore;
3
7
40public class UserManager
41{
42 private readonly Func<IApplicationDbContext> _dbContextFactory;
43
48 public UserManager(Func<IApplicationDbContext> dbContextFactory)
49 {
50 _dbContextFactory = dbContextFactory;
51 }
52
58 public async Task<ApplicationUser?> FindByNameAsync(string username)
59 {
60 IApplicationDbContext context = _dbContextFactory();
61 try
62 {
63 return await context.Users.FirstOrDefaultAsync(u => u.UserName == username);
64 }
65 finally
66 {
67 (context as IDisposable)?.Dispose();
68 }
69 }
70
80 public static Task<bool> CheckPasswordAsync(ApplicationUser user, string password)
81 {
82 // Assumes PasswordHash is stored as "base64Salt:base64Hash"
83 if (string.IsNullOrEmpty(user.PasswordHash) || !user.PasswordHash.Contains(':'))
84 return Task.FromResult(false);
85
86 string[] parts = user.PasswordHash.Split(':');
87 if (parts.Length != 2)
88 return Task.FromResult(false);
89
90 byte[] saltBytes = Convert.FromBase64String(parts[0]);
91 string storedHash = parts[1];
92
93 string hash = HashPassword(password, saltBytes);
94 return Task.FromResult(storedHash == hash);
95 }
96
101 public async Task AddUserAsync(ApplicationUser user)
102 {
103 IApplicationDbContext context = _dbContextFactory();
104 try
105 {
106 _ = context.Users.Add(user);
107 _ = await context.SaveChangesAsync();
108 }
109 finally
110 {
111 (context as IDisposable)?.Dispose();
112 }
113 }
114
124 private static string HashPassword(string password, byte[] salt)
125 {
126 return Convert.ToBase64String(
127 KeyDerivation.Pbkdf2(
128 password: password,
129 salt: salt,
130 prf: KeyDerivationPrf.HMACSHA256,
131 iterationCount: 10000,
132 numBytesRequested: 256 / 8));
133 }
134}
static Task< bool > CheckPasswordAsync(ApplicationUser user, string password)
Verifies a user's password against the stored password hash.
async Task AddUserAsync(ApplicationUser user)
Asynchronously adds a new user to the database.
async Task< ApplicationUser?> FindByNameAsync(string username)
Asynchronously finds a user by their username.
UserManager(Func< IApplicationDbContext > dbContextFactory)
Initializes a new instance of the UserManager class with the specified database context factory.
Represents an application user entity for authentication and authorization. Inherits from IdentityUse...