-
Notifications
You must be signed in to change notification settings - Fork 560
/
UserAppService.cs
224 lines (190 loc) · 8.23 KB
/
UserAppService.cs
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Domain.Entities;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.IdentityFramework;
using Abp.Linq.Extensions;
using Abp.Localization;
using Abp.Runtime.Session;
using Abp.UI;
using AbpCompanyName.AbpProjectName.Authorization;
using AbpCompanyName.AbpProjectName.Authorization.Accounts;
using AbpCompanyName.AbpProjectName.Authorization.Roles;
using AbpCompanyName.AbpProjectName.Authorization.Users;
using AbpCompanyName.AbpProjectName.Roles.Dto;
using AbpCompanyName.AbpProjectName.Users.Dto;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
namespace AbpCompanyName.AbpProjectName.Users
{
[AbpAuthorize(PermissionNames.Pages_Users)]
public class UserAppService : AsyncCrudAppService<User, UserDto, long, PagedUserResultRequestDto, CreateUserDto, UserDto>, IUserAppService
{
private readonly UserManager _userManager;
private readonly RoleManager _roleManager;
private readonly IRepository<Role> _roleRepository;
private readonly IPasswordHasher<User> _passwordHasher;
private readonly IAbpSession _abpSession;
private readonly LogInManager _logInManager;
public UserAppService(
IRepository<User, long> repository,
UserManager userManager,
RoleManager roleManager,
IRepository<Role> roleRepository,
IPasswordHasher<User> passwordHasher,
IAbpSession abpSession,
LogInManager logInManager)
: base(repository)
{
_userManager = userManager;
_roleManager = roleManager;
_roleRepository = roleRepository;
_passwordHasher = passwordHasher;
_abpSession = abpSession;
_logInManager = logInManager;
}
public override async Task<UserDto> Create(CreateUserDto input)
{
CheckCreatePermission();
var user = ObjectMapper.Map<User>(input);
user.TenantId = AbpSession.TenantId;
user.IsEmailConfirmed = true;
await _userManager.InitializeOptionsAsync(AbpSession.TenantId);
CheckErrors(await _userManager.CreateAsync(user, input.Password));
if (input.RoleNames != null)
{
CheckErrors(await _userManager.SetRoles(user, input.RoleNames));
}
CurrentUnitOfWork.SaveChanges();
return MapToEntityDto(user);
}
public override async Task<UserDto> Update(UserDto input)
{
CheckUpdatePermission();
var user = await _userManager.GetUserByIdAsync(input.Id);
MapToEntity(input, user);
CheckErrors(await _userManager.UpdateAsync(user));
if (input.RoleNames != null)
{
CheckErrors(await _userManager.SetRoles(user, input.RoleNames));
}
return await Get(input);
}
public override async Task Delete(EntityDto<long> input)
{
var user = await _userManager.GetUserByIdAsync(input.Id);
await _userManager.DeleteAsync(user);
}
public async Task<ListResultDto<RoleDto>> GetRoles()
{
var roles = await _roleRepository.GetAllListAsync();
return new ListResultDto<RoleDto>(ObjectMapper.Map<List<RoleDto>>(roles));
}
public async Task ChangeLanguage(ChangeUserLanguageDto input)
{
await SettingManager.ChangeSettingForUserAsync(
AbpSession.ToUserIdentifier(),
LocalizationSettingNames.DefaultLanguage,
input.LanguageName
);
}
protected override User MapToEntity(CreateUserDto createInput)
{
var user = ObjectMapper.Map<User>(createInput);
user.SetNormalizedNames();
return user;
}
protected override void MapToEntity(UserDto input, User user)
{
ObjectMapper.Map(input, user);
user.SetNormalizedNames();
}
protected override UserDto MapToEntityDto(User user)
{
var roles = _roleManager.Roles.Where(r => user.Roles.Any(ur => ur.RoleId == r.Id)).Select(r => r.NormalizedName);
var userDto = base.MapToEntityDto(user);
userDto.RoleNames = roles.ToArray();
return userDto;
}
protected override IQueryable<User> CreateFilteredQuery(PagedUserResultRequestDto input)
{
return Repository.GetAllIncluding(x => x.Roles)
.WhereIf(!input.Keyword.IsNullOrWhiteSpace(), x => x.UserName.Contains(input.Keyword) || x.Name.Contains(input.Keyword) || x.EmailAddress.Contains(input.Keyword))
.WhereIf(input.IsActive.HasValue, x => x.IsActive == input.IsActive);
}
protected override async Task<User> GetEntityByIdAsync(long id)
{
var user = await Repository.GetAllIncluding(x => x.Roles).FirstOrDefaultAsync(x => x.Id == id);
if (user == null)
{
throw new EntityNotFoundException(typeof(User), id);
}
return user;
}
protected override IQueryable<User> ApplySorting(IQueryable<User> query, PagedUserResultRequestDto input)
{
return query.OrderBy(r => r.UserName);
}
protected virtual void CheckErrors(IdentityResult identityResult)
{
identityResult.CheckErrors(LocalizationManager);
}
public async Task<bool> ChangePassword(ChangePasswordDto input)
{
if (_abpSession.UserId == null)
{
throw new UserFriendlyException("Please log in before attemping to change password.");
}
long userId = _abpSession.UserId.Value;
var user = await _userManager.GetUserByIdAsync(userId);
var loginAsync = await _logInManager.LoginAsync(user.UserName, input.CurrentPassword, shouldLockout: false);
if (loginAsync.Result != AbpLoginResultType.Success)
{
throw new UserFriendlyException("Your 'Existing Password' did not match the one on record. Please try again or contact an administrator for assistance in resetting your password.");
}
if (!new Regex(AccountAppService.PasswordRegex).IsMatch(input.NewPassword))
{
throw new UserFriendlyException("Passwords must be at least 8 characters, contain a lowercase, uppercase, and number.");
}
user.Password = _passwordHasher.HashPassword(user, input.NewPassword);
CurrentUnitOfWork.SaveChanges();
return true;
}
public async Task<bool> ResetPassword(ResetPasswordDto input)
{
if (_abpSession.UserId == null)
{
throw new UserFriendlyException("Please log in before attemping to reset password.");
}
long currentUserId = _abpSession.UserId.Value;
var currentUser = await _userManager.GetUserByIdAsync(currentUserId);
var loginAsync = await _logInManager.LoginAsync(currentUser.UserName, input.AdminPassword, shouldLockout: false);
if (loginAsync.Result != AbpLoginResultType.Success)
{
throw new UserFriendlyException("Your 'Admin Password' did not match the one on record. Please try again.");
}
if (currentUser.IsDeleted || !currentUser.IsActive)
{
return false;
}
var roles = await _userManager.GetRolesAsync(currentUser);
if (!roles.Contains(StaticRoleNames.Tenants.Admin))
{
throw new UserFriendlyException("Only administrators may reset passwords.");
}
var user = await _userManager.GetUserByIdAsync(input.UserId);
if (user != null)
{
user.Password = _passwordHasher.HashPassword(user, input.NewPassword);
CurrentUnitOfWork.SaveChanges();
}
return true;
}
}
}