aboutsummaryrefslogtreecommitdiff
path: root/ExamTemplate/Data/Repositories/UserRepository.cs
blob: 04e1f459c12b861a9df9877a76a780a416e0bb1b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using System.Threading.Tasks;
using ExamTemplate.Data.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;

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<User> GetByUsernameAsync(string username)
		{
			return await this._userManager.Users
				.Include(x => x.Roles)
				.FirstOrDefaultAsync(x => x.UserName == username);
		}

		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;
		}

		public async Task<bool> VerifyPasswordAsync(User user, string password)
		{
			return await this._userManager.CheckPasswordAsync(user, password);
		}
	}
}