forked from RomFAN/UserService-test-task
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUserService.cs
More file actions
60 lines (52 loc) · 1.79 KB
/
UserService.cs
File metadata and controls
60 lines (52 loc) · 1.79 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
public class UserService
{
public void CreateUser(string name, string email, string password, string role)
{
if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password))
{
throw new Exception("Invalid input");
}
var emailRegex = new System.Text.RegularExpressions.Regex(@"^[^@\s]+@[^@\s]+\.[^@\s]+$");
if (!emailRegex.IsMatch(email))
{
throw new Exception("Invalid email");
}
var passwordHash = BCrypt.Net.BCrypt.HashPassword(password);
using (var db = new SqlConnection("connectionString"))
{
db.Open();
var command = new SqlCommand($"INSERT INTO Users (Name, Email, PasswordHash, Role) VALUES ('{name}', '{email}', '{passwordHash}', '{role}')", db);
command.ExecuteNonQuery();
}
}
public List<string> GetUsers()
{
var users = new List<string>();
using (var db = new SqlConnection("connectionString"))
{
db.Open();
var command = new SqlCommand("SELECT Name FROM Users", db);
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
users.Add(reader.GetString(0));
}
}
}
return users;
}
public void UpdateUserRole(int userId, string newRole)
{
if (newRole != "Admin" && newRole != "User")
{
throw new Exception("Invalid role");
}
using (var db = new SqlConnection("connectionString"))
{
db.Open();
var command = new SqlCommand($"UPDATE Users SET Role = '{newRole}' WHERE Id = {userId}", db);
command.ExecuteNonQuery();
}
}
}