-
Notifications
You must be signed in to change notification settings - Fork 42
/
MembershipService.cs
226 lines (179 loc) · 9.66 KB
/
MembershipService.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
224
225
226
using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web.Security;
using JetBrains.Annotations;
using Orchard.Localization;
using Orchard.Logging;
using Orchard.ContentManagement;
using Orchard.Security;
using Orchard.Users.Events;
using Orchard.Users.Models;
using Orchard.Messaging.Services;
using System.Collections.Generic;
using Orchard.Services;
namespace Orchard.Users.Services {
[UsedImplicitly]
public class MembershipService : IMembershipService {
private readonly IOrchardServices _orchardServices;
private readonly IMessageManager _messageManager;
private readonly IEnumerable<IUserEventHandler> _userEventHandlers;
private readonly IEncryptionService _encryptionService;
public MembershipService(IOrchardServices orchardServices, IMessageManager messageManager, IEnumerable<IUserEventHandler> userEventHandlers, IClock clock, IEncryptionService encryptionService) {
_orchardServices = orchardServices;
_messageManager = messageManager;
_userEventHandlers = userEventHandlers;
_encryptionService = encryptionService;
Logger = NullLogger.Instance;
T = NullLocalizer.Instance;
}
public ILogger Logger { get; set; }
public Localizer T { get; set; }
public MembershipSettings GetSettings() {
var settings = new MembershipSettings();
// accepting defaults
return settings;
}
public IUser CreateUser(CreateUserParams createUserParams) {
Logger.Information("CreateUser {0} {1}", createUserParams.Username, createUserParams.Email);
var registrationSettings = _orchardServices.WorkContext.CurrentSite.As<RegistrationSettingsPart>();
var user = _orchardServices.ContentManager.New<UserPart>("User");
user.Record.UserName = createUserParams.Username;
user.Record.Email = createUserParams.Email;
user.Record.NormalizedUserName = createUserParams.Username.ToLowerInvariant();
user.Record.HashAlgorithm = "SHA1";
SetPassword(user.Record, createUserParams.Password);
if ( registrationSettings != null ) {
user.Record.RegistrationStatus = registrationSettings.UsersAreModerated ? UserStatus.Pending : UserStatus.Approved;
user.Record.EmailStatus = registrationSettings.UsersMustValidateEmail ? UserStatus.Pending : UserStatus.Approved;
}
if(createUserParams.IsApproved) {
user.Record.RegistrationStatus = UserStatus.Approved;
user.Record.EmailStatus = UserStatus.Approved;
}
var userContext = new UserContext {User = user, Cancel = false};
foreach(var userEventHandler in _userEventHandlers) {
userEventHandler.Creating(userContext);
}
if(userContext.Cancel) {
return null;
}
_orchardServices.ContentManager.Create(user);
foreach ( var userEventHandler in _userEventHandlers ) {
userEventHandler.Created(userContext);
if (user.RegistrationStatus == UserStatus.Approved) {
userEventHandler.Approved(user);
}
}
if ( registrationSettings != null && registrationSettings.UsersAreModerated && registrationSettings.NotifyModeration && !createUserParams.IsApproved ) {
var usernames = String.IsNullOrWhiteSpace(registrationSettings.NotificationsRecipients)
? new string[0]
: registrationSettings.NotificationsRecipients.Split(new[] {',', ' '}, StringSplitOptions.RemoveEmptyEntries);
foreach ( var userName in usernames ) {
if (String.IsNullOrWhiteSpace(userName)) {
continue;
}
var recipient = GetUser(userName);
if (recipient != null)
_messageManager.Send(recipient.ContentItem.Record, MessageTypes.Moderation, "email" , new Dictionary<string, string> { { "UserName", createUserParams.Username}, { "Email" , createUserParams.Email } });
}
}
return user;
}
public IUser GetUser(string username) {
var lowerName = username == null ? "" : username.ToLowerInvariant();
return _orchardServices.ContentManager.Query<UserPart, UserPartRecord>().Where(u => u.NormalizedUserName == lowerName).List().FirstOrDefault();
}
public IUser ValidateUser(string userNameOrEmail, string password) {
var lowerName = userNameOrEmail == null ? "" : userNameOrEmail.ToLowerInvariant();
var user = _orchardServices.ContentManager.Query<UserPart, UserPartRecord>().Where(u => u.NormalizedUserName == lowerName).List().FirstOrDefault();
if (user == null)
user = _orchardServices.ContentManager.Query<UserPart, UserPartRecord>().Where(u => u.Email == lowerName).List().FirstOrDefault();
if ( user == null || ValidatePassword(user.As<UserPart>().Record, password) == false )
return null;
if ( user.EmailStatus != UserStatus.Approved )
return null;
if ( user.RegistrationStatus != UserStatus.Approved )
return null;
return user;
}
public void SetPassword(IUser user, string password) {
if (!user.Is<UserPart>())
throw new InvalidCastException();
var userRecord = user.As<UserPart>().Record;
SetPassword(userRecord, password);
}
void SetPassword(UserPartRecord partRecord, string password) {
switch (GetSettings().PasswordFormat) {
case MembershipPasswordFormat.Clear:
SetPasswordClear(partRecord, password);
break;
case MembershipPasswordFormat.Hashed:
SetPasswordHashed(partRecord, password);
break;
case MembershipPasswordFormat.Encrypted:
SetPasswordEncrypted(partRecord, password);
break;
default:
throw new ApplicationException(T("Unexpected password format value").ToString());
}
}
private bool ValidatePassword(UserPartRecord partRecord, string password) {
// Note - the password format stored with the record is used
// otherwise changing the password format on the site would invalidate
// all logins
switch (partRecord.PasswordFormat) {
case MembershipPasswordFormat.Clear:
return ValidatePasswordClear(partRecord, password);
case MembershipPasswordFormat.Hashed:
return ValidatePasswordHashed(partRecord, password);
case MembershipPasswordFormat.Encrypted:
return ValidatePasswordEncrypted(partRecord, password);
default:
throw new ApplicationException("Unexpected password format value");
}
}
private static void SetPasswordClear(UserPartRecord partRecord, string password) {
partRecord.PasswordFormat = MembershipPasswordFormat.Clear;
partRecord.Password = password;
partRecord.PasswordSalt = null;
}
private static bool ValidatePasswordClear(UserPartRecord partRecord, string password) {
return partRecord.Password == password;
}
private static void SetPasswordHashed(UserPartRecord partRecord, string password) {
var saltBytes = new byte[0x10];
using (var random = new RNGCryptoServiceProvider()) {
random.GetBytes(saltBytes);
}
var passwordBytes = Encoding.Unicode.GetBytes(password);
var combinedBytes = saltBytes.Concat(passwordBytes).ToArray();
byte[] hashBytes;
using (var hashAlgorithm = HashAlgorithm.Create(partRecord.HashAlgorithm)) {
hashBytes = hashAlgorithm.ComputeHash(combinedBytes);
}
partRecord.PasswordFormat = MembershipPasswordFormat.Hashed;
partRecord.Password = Convert.ToBase64String(hashBytes);
partRecord.PasswordSalt = Convert.ToBase64String(saltBytes);
}
private static bool ValidatePasswordHashed(UserPartRecord partRecord, string password) {
var saltBytes = Convert.FromBase64String(partRecord.PasswordSalt);
var passwordBytes = Encoding.Unicode.GetBytes(password);
var combinedBytes = saltBytes.Concat(passwordBytes).ToArray();
byte[] hashBytes;
using (var hashAlgorithm = HashAlgorithm.Create(partRecord.HashAlgorithm)) {
hashBytes = hashAlgorithm.ComputeHash(combinedBytes);
}
return partRecord.Password == Convert.ToBase64String(hashBytes);
}
private void SetPasswordEncrypted(UserPartRecord partRecord, string password) {
partRecord.Password = Convert.ToBase64String(_encryptionService.Encode(Encoding.UTF8.GetBytes(password)));
partRecord.PasswordSalt = null;
partRecord.PasswordFormat = MembershipPasswordFormat.Encrypted;
}
private bool ValidatePasswordEncrypted(UserPartRecord partRecord, string password) {
return String.Equals(password, Encoding.UTF8.GetString(_encryptionService.Decode(Convert.FromBase64String(partRecord.Password))), StringComparison.Ordinal);
}
}
}