上接:
在实现了角色的各种管理接口后,下一步就是实现对用户的管理,对用户管理的接口相对多一些,必须要实现的有如下三个:
1 public interface IUserRoleStore<TUser> : IUserStore<TUser>, IDisposable where TUser : class
2
3 public interface IUserPasswordStore<TUser> : IUserStore<TUser>, IDisposable where TUser : class
4
5 public interface IQueryableUserStore<TUser> : IUserStore<TUser>, IDisposable where TUser : class
第一个是关于用户和角色关系的接口,定义了和角色相关的几个方法。
第二个是关于密码的,定义了用户密码的读取和设置等方法。
最后一个是关于用户本身的,定义了用户增删改查等方法。
下面是具体的代码:
1 public class HDUserStore<TUser> :
2 IUserRoleStore<TUser>,
3 IUserPasswordStore<TUser>,
4 IQueryableUserStore<TUser>
5 where TUser : HDUser, new()
6 {
7 /// <summary>
8 /// 存储用户列表
9 /// </summary>
10 private readonly Dictionary<string, TUser> _users = new Dictionary<string, TUser>();
11
12 public IQueryable<TUser> Users
13 {
14 get
15 {
16 if (_users.Count == 0)
17 {
18 //生成用户
19 TUser user = CreateNewUser("1", "daxia", "qingdao");
20 //设置用户角色
21 user.Roles.Add(new HDUserRole() { UserId = "1", RoleId = "power" });
22 _users.Add(user.Id, user);
23
24 user = CreateNewUser("2", "aspnet5", "mvc6");
25 user.Roles.Add(new HDUserRole() { UserId = "2", RoleId = "admin" });
26 _users.Add(user.Id, user);
27 }
28 return _users.Values.AsQueryable();
29 }
30 }
31
32 /// <summary>
33 /// 生成用户
34 /// </summary>
35 /// <param name="id"></param>
36 /// <param name="name"></param>
37 /// <param name="pwd"></param>
38 /// <returns></returns>
39 private TUser CreateNewUser(string id, string name, string pwd)
40 {
41 TUser user = new TUser();
42 user.PassWord = pwd;
43 user.Id = id;
44 user.UserName = name;
45 user.NormalizedUserName = name.ToUpper();
46 PasswordHasher<TUser> hash = new PasswordHasher<TUser>();
47 user.PasswordHash = hash.HashPassword(user, user.PassWord);
48
49 return user;
50 }
51
52 public Task AddToRoleAsync(TUser user, string roleId, CancellationToken cancellationToken)
53 {
54 user.Roles.Add(new HDUserRole { RoleId = roleId, UserId = user.Id });
55 return Task.FromResult(0);
56 }
57
58 public Task<IdentityResult> CreateAsync(TUser user, CancellationToken cancellationToken)
59 {
60 _users[user.Id] = user;
61 return Task.FromResult(IdentityResult.Success);
62 }
63
64 public Task<IdentityResult> DeleteAsync(TUser user, CancellationToken cancellationToken)
65 {
66 if (user == null || !_users.ContainsKey(user.Id))
67 {
68 throw new InvalidOperationException("Unknown user");
69 }
70 _users.Remove(user.Id);
71 return Task.FromResult(IdentityResult.Success);
72 }
73
74 public void Dispose()
75 {
76
77 }
78
79 public Task<TUser> FindByIdAsync(string userId, CancellationToken cancellationToken)
80 {
81 if (_users.ContainsKey(userId))
82 {
83 return Task.FromResult(_users[userId]);
84 }
85 return Task.FromResult<TUser>(null