blob: 3e5ceaa57f283ad6a7b3326fd3ba3ef09c1a8c25 (
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
54
55
56
57
58
59
60
61
62
63
64
65
66
|
using System.Security.Claims;
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<User> GetByClaimsAsync(ClaimsPrincipal claimsPrincipal)
{
return await this._userManager.GetUserAsync(claimsPrincipal);
}
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> EditUserAsync(User user)
{
IdentityResult result = await this._userManager.UpdateAsync(user);
return result.Succeeded;
}
public async Task<bool> VerifyPasswordAsync(User user, string password)
{
return await this._userManager.CheckPasswordAsync(user, password);
}
}
}
|