aboutsummaryrefslogtreecommitdiff
path: root/ExamTemplate/Data/Repositories/UserRepository.cs
diff options
context:
space:
mode:
Diffstat (limited to 'ExamTemplate/Data/Repositories/UserRepository.cs')
-rw-r--r--ExamTemplate/Data/Repositories/UserRepository.cs40
1 files changed, 40 insertions, 0 deletions
diff --git a/ExamTemplate/Data/Repositories/UserRepository.cs b/ExamTemplate/Data/Repositories/UserRepository.cs
new file mode 100644
index 0000000..97eb21b
--- /dev/null
+++ b/ExamTemplate/Data/Repositories/UserRepository.cs
@@ -0,0 +1,40 @@
+using System.Threading.Tasks;
+using ExamTemplate.Data.Models;
+using Microsoft.AspNetCore.Identity;
+
+namespace ExamTemplate.Data.Repositories
+{
+ public class UserRepository
+ {
+ private readonly TemplateContext _context;
+ private readonly UserManager<User> _userManager;
+ private readonly RoleManager<Role> _roleManager;
+
+ public UserRepository(TemplateContext templateContext, UserManager<User> userManager, RoleManager<Role> roleManager)
+ {
+ this._context = templateContext;
+ this._userManager = userManager;
+ this._roleManager = roleManager;
+ }
+
+ public async Task<bool> AddAsync(User user, string password)
+ {
+ user.PasswordHash = this._userManager.PasswordHasher.HashPassword(user, password);
+ IdentityResult result = await this._userManager.CreateAsync(user);
+
+ return result.Succeeded;
+ }
+
+ public async Task<bool> AddRoleToUserAsync(User user, string roleName)
+ {
+ bool succeeded = (await this._userManager.AddToRoleAsync(user, roleName)).Succeeded;
+ if (succeeded)
+ {
+ user.Roles.Add(await this._roleManager.FindByNameAsync(roleName));
+ succeeded = await this._context.SaveChangesAsync() >= 1;
+ }
+
+ return succeeded;
+ }
+ }
+}