-
Notifications
You must be signed in to change notification settings - Fork 193
/
Copy pathSqlUsersDatabase.cs
274 lines (234 loc) · 8.96 KB
/
SqlUsersDatabase.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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using Opc.Ua.Gds.Server.Database.Sql;
using Opc.Ua.Gds.Server.DB;
using Opc.Ua.Server;
using Opc.Ua.Server.UserDatabase;
namespace Opc.Ua.Gds.Server
{
public class SqlUsersDatabase: IUserDatabase
{
#region IUsersDatabase
public void Initialize()
{
using (usersdbEntities entities = new usersdbEntities())
{
//only run initizailation logic if the database does not work -> throwS an exception
try
{
CheckCredentials("Test", "Test");
}
catch (Exception e)
{
Utils.LogError(e, "Could not connect to the Database!");
var ie = e.InnerException;
while (ie != null)
{
Utils.LogInfo(ie, "");
ie = ie.InnerException;
}
Utils.LogInfo("Initialize Database tables!");
Assembly assembly = typeof(SqlApplicationsDatabase).GetTypeInfo().Assembly;
StreamReader istrm = new StreamReader(assembly.GetManifestResourceStream("Opc.Ua.Gds.Server.DB.usersdb.edmx.sql"));
string tables = istrm.ReadToEnd();
entities.Database.Initialize(true);
entities.Database.CreateIfNotExists();
var parts = tables.Split(new string[] { "GO" }, System.StringSplitOptions.None);
foreach (var part in parts) { entities.Database.ExecuteSqlCommand(part); }
entities.SaveChanges();
Utils.LogInfo("Database Initialized!");
}
}
}
public bool CreateUser(string userName, string password, IEnumerable<Role> roles)
{
if (string.IsNullOrEmpty(userName))
{
throw new ArgumentException("UserName cannot be empty.", nameof(userName));
}
if (string.IsNullOrEmpty(password))
{
throw new ArgumentException("Password cannot be empty.", nameof(password));
}
using (usersdbEntities entities = new usersdbEntities())
{
if (//User Exists
entities.UserSet.SingleOrDefault(x => x.UserName == userName) != null)
{
return false;
}
string hash = Hash(password);
var sqlRoles = new List<SqlRole>();
foreach (var role in roles)
{
sqlRoles.Add((SqlRole)role);
}
var user = new User { ID = Guid.NewGuid(), UserName = userName, Hash = hash, Roles = sqlRoles };
entities.UserSet.Add(user);
entities.SaveChanges();
return true;
}
}
public bool DeleteUser(string userName)
{
if (string.IsNullOrEmpty(userName))
{
throw new ArgumentException("UserName cannot be empty.", nameof(userName));
}
using (usersdbEntities entities = new usersdbEntities())
{
var user = entities.UserSet.SingleOrDefault(x => x.UserName == userName);
if (user == null)
{
return false;
}
entities.UserSet.Remove(user);
entities.SaveChanges();
return true;
}
}
public bool CheckCredentials(string userName, string password)
{
if (string.IsNullOrEmpty(userName))
{
throw new ArgumentException("UserName cannot be empty.", nameof(userName));
}
if (string.IsNullOrEmpty(password))
{
throw new ArgumentException("Password cannot be empty.", nameof(password));
}
using (usersdbEntities entities = new usersdbEntities())
{
var user = entities.UserSet.SingleOrDefault(x => x.UserName == userName);
if (user == null)
{
return false;
}
return Check(user.Hash, password);
}
}
public IEnumerable<Role> GetUserRoles(string userName)
{
if (string.IsNullOrEmpty(userName))
{
throw new ArgumentException("UserName cannot be empty.", nameof(userName));
}
using (usersdbEntities entities = new usersdbEntities())
{
var user = entities.UserSet.SingleOrDefault(x => x.UserName == userName);
if (user == null)
{
throw new ArgumentException("No user found with the UserName " + userName);
}
var roles = new List<Role>();
foreach (var role in user.Roles)
{
roles.Add((Role)role);
}
return roles;
}
}
public bool ChangePassword(string userName, string oldPassword, string newPassword)
{
if (string.IsNullOrEmpty(userName))
{
throw new ArgumentException("UserName cannot be empty.", nameof(userName));
}
if (string.IsNullOrEmpty(oldPassword))
{
throw new ArgumentException("Current Password cannot be empty.", nameof(oldPassword));
}
if (string.IsNullOrEmpty(newPassword))
{
throw new ArgumentException("New Password cannot be empty.", nameof(newPassword));
}
using (usersdbEntities entities = new usersdbEntities())
{
var user = entities.UserSet.SingleOrDefault(x => x.UserName == userName);
if (user == null)
{
return false;
}
if (Check(user.Hash, oldPassword))
{
var newHash = Hash(newPassword);
user.Hash = newHash;
entities.SaveChanges();
return true;
}
return false;
}
}
#endregion
#region IPasswordHasher
private string Hash(string password)
{
#if NETSTANDARD2_0 || NET462
#pragma warning disable CA5379 // Ensure Key Derivation Function algorithm is sufficiently strong
using (var algorithm = new Rfc2898DeriveBytes(
password,
kSaltSize,
kIterations))
{
#pragma warning restore CA5379 // Ensure Key Derivation Function algorithm is sufficiently strong
#else
using (var algorithm = new Rfc2898DeriveBytes(
password,
kSaltSize,
kIterations,
HashAlgorithmName.SHA512))
{
#endif
var key = Convert.ToBase64String(algorithm.GetBytes(kKeySize));
var salt = Convert.ToBase64String(algorithm.Salt);
return $"{kIterations}.{salt}.{key}";
}
}
private bool Check(string hash, string password)
{
var separator = new Char[] { '.' };
var parts = hash.Split(separator, 3);
if (parts.Length != 3)
{
throw new FormatException("Unexpected hash format. " +
"Should be formatted as `{iterations}.{salt}.{hash}`");
}
var iterations = Convert.ToInt32(parts[0], CultureInfo.InvariantCulture.NumberFormat);
var salt = Convert.FromBase64String(parts[1]);
var key = Convert.FromBase64String(parts[2]);
#if NETSTANDARD2_0 || NET462
#pragma warning disable CA5379 // Ensure Key Derivation Function algorithm is sufficiently strong
using (var algorithm = new Rfc2898DeriveBytes(
password,
salt,
iterations))
{
#pragma warning restore CA5379 // Ensure Key Derivation Function algorithm is sufficiently strong
#else
using (var algorithm = new Rfc2898DeriveBytes(
password,
salt,
iterations,
HashAlgorithmName.SHA512))
{
#endif
var keyToCheck = algorithm.GetBytes(kKeySize);
var verified = keyToCheck.SequenceEqual(key);
return verified;
}
}
#endregion
#region Internal Members
#endregion
#region Internal Fields
private const int kSaltSize = 16; // 128 bit
private const int kIterations = 10000; // 10k
private const int kKeySize = 32; // 256 bit
#endregion
}
}