forked from kabdelrazek-do/SecurityAndAuthentication
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUserController.cs
More file actions
418 lines (371 loc) · 15.3 KB
/
UserController.cs
File metadata and controls
418 lines (371 loc) · 15.3 KB
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
using System;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Results;
using SafeVault.Security;
using SafeVault.Data;
using System.Net;
using System.Net.Http;
using System.Web;
namespace SafeVault.Controllers
{
/// <summary>
/// Secure API controller for user management operations
/// </summary>
[RoutePrefix("api/users")]
public class UserController : ApiController
{
private readonly SecureDatabaseManager _dbManager;
private readonly string _connectionString;
public UserController()
{
// In production, use dependency injection and configuration
_connectionString = "Server=localhost;Database=SafeVault;Integrated Security=true;TrustServerCertificate=true;";
_dbManager = new SecureDatabaseManager(_connectionString);
}
/// <summary>
/// Creates a new user with secure validation
/// </summary>
/// <param name="request">User creation request</param>
/// <returns>Creation result</returns>
[HttpPost]
[Route("")]
public async Task<IHttpActionResult> CreateUser([FromBody] CreateUserRequest request)
{
try
{
// Get client information for audit logging
var clientInfo = GetClientInfo();
// Validate input
if (request == null)
{
await _dbManager.LogAuditEventAsync(null, "USER_CREATION_FAILED", "Null request received", clientInfo.IpAddress, clientInfo.UserAgent);
return BadRequest("Request cannot be null");
}
// Validate username
var usernameValidation = SecureInputValidator.ValidateUsername(request.Username);
if (!usernameValidation.IsValid)
{
await _dbManager.LogAuditEventAsync(null, "USER_CREATION_FAILED", $"Invalid username: {usernameValidation.ErrorMessage}", clientInfo.IpAddress, clientInfo.UserAgent);
return BadRequest($"Username validation failed: {usernameValidation.ErrorMessage}");
}
// Validate email
var emailValidation = SecureInputValidator.ValidateEmail(request.Email);
if (!emailValidation.IsValid)
{
await _dbManager.LogAuditEventAsync(null, "USER_CREATION_FAILED", $"Invalid email: {emailValidation.ErrorMessage}", clientInfo.IpAddress, clientInfo.UserAgent);
return BadRequest($"Email validation failed: {emailValidation.ErrorMessage}");
}
// Validate password if provided
if (!string.IsNullOrEmpty(request.Password))
{
var passwordValidation = SecureInputValidator.ValidatePassword(request.Password);
if (!passwordValidation.IsValid)
{
await _dbManager.LogAuditEventAsync(null, "USER_CREATION_FAILED", $"Invalid password: {passwordValidation.ErrorMessage}", clientInfo.IpAddress, clientInfo.UserAgent);
return BadRequest($"Password validation failed: {passwordValidation.ErrorMessage}");
}
}
// Generate salt and hash password
string salt = SecureInputValidator.GenerateSalt();
string passwordHash = SecureInputValidator.HashPassword(request.Password ?? "defaultPassword123!", salt);
// Create user in database
int userId = await _dbManager.CreateUserAsync(
usernameValidation.SanitizedValue,
emailValidation.SanitizedValue,
passwordHash,
salt,
clientInfo.IpAddress,
clientInfo.UserAgent
);
if (userId > 0)
{
var response = new CreateUserResponse
{
Success = true,
UserId = userId,
Message = "User created successfully"
};
return Ok(response);
}
else
{
await _dbManager.LogAuditEventAsync(null, "USER_CREATION_FAILED", "Database operation failed", clientInfo.IpAddress, clientInfo.UserAgent);
return InternalServerError(new Exception("Failed to create user"));
}
}
catch (InvalidOperationException ex)
{
var clientInfo = GetClientInfo();
await _dbManager.LogAuditEventAsync(null, "USER_CREATION_FAILED", ex.Message, clientInfo.IpAddress, clientInfo.UserAgent);
return BadRequest(ex.Message);
}
catch (Exception ex)
{
var clientInfo = GetClientInfo();
await _dbManager.LogAuditEventAsync(null, "USER_CREATION_ERROR", ex.Message, clientInfo.IpAddress, clientInfo.UserAgent);
return InternalServerError(ex);
}
}
/// <summary>
/// Authenticates a user with secure validation
/// </summary>
/// <param name="request">Authentication request</param>
/// <returns>Authentication result</returns>
[HttpPost]
[Route("authenticate")]
public async Task<IHttpActionResult> AuthenticateUser([FromBody] AuthenticateUserRequest request)
{
try
{
var clientInfo = GetClientInfo();
// Validate input
if (request == null)
{
await _dbManager.LogAuditEventAsync(null, "AUTHENTICATION_FAILED", "Null request received", clientInfo.IpAddress, clientInfo.UserAgent);
return BadRequest("Request cannot be null");
}
// Validate username
var usernameValidation = SecureInputValidator.ValidateUsername(request.Username);
if (!usernameValidation.IsValid)
{
await _dbManager.LogAuditEventAsync(null, "AUTHENTICATION_FAILED", $"Invalid username format", clientInfo.IpAddress, clientInfo.UserAgent);
return BadRequest("Invalid username format");
}
if (string.IsNullOrEmpty(request.Password))
{
await _dbManager.LogAuditEventAsync(null, "AUTHENTICATION_FAILED", "Empty password", clientInfo.IpAddress, clientInfo.UserAgent);
return BadRequest("Password is required");
}
// Hash the provided password (in real implementation, you'd need to retrieve the salt from database)
// For this example, we'll use a simple hash
string passwordHash = SecureInputValidator.HashPassword(request.Password, "defaultSalt");
// Authenticate user
var authResult = await _dbManager.AuthenticateUserAsync(
usernameValidation.SanitizedValue,
passwordHash,
clientInfo.IpAddress,
clientInfo.UserAgent
);
if (authResult.IsSuccess)
{
var response = new AuthenticateUserResponse
{
Success = true,
UserId = authResult.UserId,
Message = "Authentication successful"
};
return Ok(response);
}
else
{
return Unauthorized();
}
}
catch (Exception ex)
{
var clientInfo = GetClientInfo();
await _dbManager.LogAuditEventAsync(null, "AUTHENTICATION_ERROR", ex.Message, clientInfo.IpAddress, clientInfo.UserAgent);
return InternalServerError(ex);
}
}
/// <summary>
/// Retrieves user information by ID
/// </summary>
/// <param name="id">User ID</param>
/// <returns>User information</returns>
[HttpGet]
[Route("{id}")]
public async Task<IHttpActionResult> GetUser(int id)
{
try
{
var clientInfo = GetClientInfo();
if (id <= 0)
{
await _dbManager.LogAuditEventAsync(null, "USER_RETRIEVAL_FAILED", "Invalid user ID", clientInfo.IpAddress, clientInfo.UserAgent);
return BadRequest("Invalid user ID");
}
var user = await _dbManager.GetUserByIdAsync(id);
if (user == null)
{
await _dbManager.LogAuditEventAsync(null, "USER_RETRIEVAL_FAILED", $"User not found: {id}", clientInfo.IpAddress, clientInfo.UserAgent);
return NotFound();
}
await _dbManager.LogAuditEventAsync(id, "USER_RETRIEVED", "User information retrieved", clientInfo.IpAddress, clientInfo.UserAgent);
// Return sanitized user information (exclude sensitive data)
var response = new GetUserResponse
{
Success = true,
User = new UserDto
{
UserId = user.UserId,
Username = user.Username,
Email = user.Email,
CreatedAt = user.CreatedAt,
LastLogin = user.LastLogin,
IsActive = user.IsActive
}
};
return Ok(response);
}
catch (Exception ex)
{
var clientInfo = GetClientInfo();
await _dbManager.LogAuditEventAsync(null, "USER_RETRIEVAL_ERROR", ex.Message, clientInfo.IpAddress, clientInfo.UserAgent);
return InternalServerError(ex);
}
}
/// <summary>
/// Searches users with secure input validation
/// </summary>
/// <param name="searchTerm">Search term</param>
/// <param name="limit">Maximum results</param>
/// <returns>Search results</returns>
[HttpGet]
[Route("search")]
public async Task<IHttpActionResult> SearchUsers([FromUri] string searchTerm, [FromUri] int limit = 50)
{
try
{
var clientInfo = GetClientInfo();
// Validate limit
if (limit <= 0 || limit > 100)
{
limit = 50;
}
var users = await _dbManager.SearchUsersAsync(searchTerm, limit);
await _dbManager.LogAuditEventAsync(null, "USER_SEARCH", $"Search performed: {searchTerm}", clientInfo.IpAddress, clientInfo.UserAgent);
var response = new SearchUsersResponse
{
Success = true,
Users = users.ConvertAll(u => new UserDto
{
UserId = u.UserId,
Username = u.Username,
Email = u.Email,
CreatedAt = u.CreatedAt,
LastLogin = u.LastLogin,
IsActive = u.IsActive
}),
Count = users.Count
};
return Ok(response);
}
catch (ArgumentException ex)
{
var clientInfo = GetClientInfo();
await _dbManager.LogAuditEventAsync(null, "USER_SEARCH_FAILED", ex.Message, clientInfo.IpAddress, clientInfo.UserAgent);
return BadRequest(ex.Message);
}
catch (Exception ex)
{
var clientInfo = GetClientInfo();
await _dbManager.LogAuditEventAsync(null, "USER_SEARCH_ERROR", ex.Message, clientInfo.IpAddress, clientInfo.UserAgent);
return InternalServerError(ex);
}
}
/// <summary>
/// Tests the API health and database connection
/// </summary>
/// <returns>Health status</returns>
[HttpGet]
[Route("health")]
public async Task<IHttpActionResult> HealthCheck()
{
try
{
bool dbConnected = await _dbManager.TestConnectionAsync();
var response = new HealthCheckResponse
{
Success = true,
DatabaseConnected = dbConnected,
Timestamp = DateTime.UtcNow,
Message = dbConnected ? "All systems operational" : "Database connection failed"
};
return Ok(response);
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
/// <summary>
/// Gets client information for audit logging
/// </summary>
/// <returns>Client information</returns>
private ClientInfo GetClientInfo()
{
var request = HttpContext.Current?.Request;
return new ClientInfo
{
IpAddress = request?.UserHostAddress ?? "Unknown",
UserAgent = request?.UserAgent ?? "Unknown"
};
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_dbManager?.Dispose();
}
base.Dispose(disposing);
}
}
// Request/Response models
public class CreateUserRequest
{
public string Username { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
public class CreateUserResponse
{
public bool Success { get; set; }
public int UserId { get; set; }
public string Message { get; set; }
}
public class AuthenticateUserRequest
{
public string Username { get; set; }
public string Password { get; set; }
}
public class AuthenticateUserResponse
{
public bool Success { get; set; }
public int UserId { get; set; }
public string Message { get; set; }
}
public class GetUserResponse
{
public bool Success { get; set; }
public UserDto User { get; set; }
}
public class SearchUsersResponse
{
public bool Success { get; set; }
public System.Collections.Generic.List<UserDto> Users { get; set; }
public int Count { get; set; }
}
public class HealthCheckResponse
{
public bool Success { get; set; }
public bool DatabaseConnected { get; set; }
public DateTime Timestamp { get; set; }
public string Message { get; set; }
}
public class UserDto
{
public int UserId { get; set; }
public string Username { get; set; }
public string Email { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime? LastLogin { get; set; }
public bool IsActive { get; set; }
}
public class ClientInfo
{
public string IpAddress { get; set; }
public string UserAgent { get; set; }
}
}