-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
250 lines (207 loc) · 11.3 KB
/
Copy pathProgram.cs
File metadata and controls
250 lines (207 loc) · 11.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
using CleanAuthSystem.Config;
using CleanAuthSystem.Data;
using CleanAuthSystem.DTOs;
using CleanAuthSystem.Services;
using CleanAuthSystem.Services.Interfaces;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
// Консольний додаток "Система авторизації" з чистою архітектурою.
// Демонструє використання Dependency Injection, Entity Framework Core,
// конфігурації та безпечної роботи з паролями.
namespace CleanAuthSystem
{
class Program
{
// Інтерфейс сервісу авторизації, який буде отримано через DI-контейнер
// https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection
// https://dotnettutorials.net/lesson/dependency-injection-design-pattern-csharp/
private static IAuthService _authService = null!;
static async Task Main(string[] args)
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
// Налаштовуємо DI-контейнер та всі залежності
// https://dotnettutorials.net/lesson/asp-net-core-dependency-injection/
var serviceProvider = ConfigureServices();
// Отримуємо сервіс авторизації через Dependency Injection
// https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.serviceproviderserviceextensions.getrequiredservice
_authService = serviceProvider.GetRequiredService<IAuthService>();
// Запускаємо головне меню додатку
// https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection/basics
await RunMenuAsync();
}
// Центральний метод налаштування всіх сервісів додатку
// https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection
// https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/
private static ServiceProvider ConfigureServices()
{
// Створюємо конфігурацію програми з кількох джерел
// Порядок важливий: appsettings.json -> User Secrets
// (User Secrets перезаписують значення)
// https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.configuration.configurationbuilder
// https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets
// https://dotnettutorials.net/lesson/asp-net-core-appsettings-json-file/
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false,
reloadOnChange: true)
.AddUserSecrets<Program>()
.Build();
// Створюємо нову колекцію сервісів
// https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.servicecollection
var services = new ServiceCollection();
// Прив'язуємо конфігурацію до strongly-typed класу AppConfig
// https://learn.microsoft.com/en-us/dotnet/core/extensions/options
// https://dotnettutorials.net/lesson/asp-net-core-web-api-appsettings-json-file/
services.Configure<AppConfig>(config =>
{
configuration.Bind(config);
});
// Реєстрація DbContext з SQL Server
// https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/
services.AddDbContext<AppDbContext>(options =>
{
var connectionString = configuration
.GetConnectionString("DefaultConnection");
if (string.IsNullOrEmpty(connectionString))
{
throw new InvalidOperationException(
"Connection string не знайдено в User Secrets " +
"або appsettings.json!");
}
// https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.sqlserverdbcontextoptionsextensions.usesqlserver
// https://learn.microsoft.com/en-us/ef/core/providers/sql-server/?tabs=dotnet-core-cli%2Csqlserver
options.UseSqlServer(connectionString);
});
// Реєстрація сервісів авторизації
// https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection/service-lifetimes
// https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.servicecollectionserviceextensions.addscoped
services.AddScoped<IPasswordHasher, PasswordHasher>();
services.AddScoped<IAuthService, AuthService>();
// Будуємо провайдер сервісів
// https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.servicecollectioncontainerbuilderextensions.buildserviceprovider
var serviceProvider = services.BuildServiceProvider();
// Ініціалізація бази даних при першому запуску (EnsureCreated)
// https://learn.microsoft.com/en-us/ef/core/managing-schemas/ensure-created
// https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.serviceproviderserviceextensions.createscope
using var scope = serviceProvider.CreateScope();
var dbContext = scope.ServiceProvider
.GetRequiredService<AppDbContext>();
dbContext.Database.EnsureCreated();
// в індустрії краще використовувати Migrations, а не EnsureCreated
// https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/
Console.WriteLine("Базу даних успішно ініціалізовано!");
return serviceProvider;
}
// Головний цикл меню програми
private static async Task RunMenuAsync()
{
while (true)
{
ShowHeader();
Console.WriteLine("1. Увійти");
Console.WriteLine("2. Зареєструватися");
Console.WriteLine("3. Вийти з програми");
Console.Write("\nВиберіть дію (1-3): ");
var choice = Console.ReadLine()?.Trim();
switch (choice)
{
case "1":
await HandleLoginAsync();
break;
case "2":
await HandleRegisterAsync();
break;
case "3":
Console.WriteLine("\nБувайте!");
return;
default:
Console.WriteLine("Невірний вибір! Спробуйте ще раз.");
break;
}
Console.WriteLine("\nНатисніть будь-яку клавішу для " +
"продовження...");
Console.ReadKey(true);
}
}
// Відображення заголовка програми
private static void ShowHeader()
{
Console.Clear();
Console.WriteLine("=== СИСТЕМА АВТОРИЗАЦІЇ ===");
Console.WriteLine();
}
// Обробка реєстрації нового користувача
private static async Task HandleRegisterAsync()
{
ShowHeader();
Console.Write("Придумайте логін: ");
var username = Console.ReadLine()?.Trim() ?? "";
Console.Write("Введіть пароль: ");
var password = ReadPassword();
Console.Write("Повторіть пароль: ");
var confirmPassword = ReadPassword();
var dto = new RegisterDto
{
Username = username,
Password = password,
ConfirmPassword = confirmPassword
};
var (success, message) = await _authService.RegisterAsync(dto);
Console.WriteLine($"\n{message}");
}
// Обробка входу користувача в систему
private static async Task HandleLoginAsync()
{
ShowHeader();
Console.Write("Логін: ");
var username = Console.ReadLine()?.Trim() ?? "";
Console.Write("Пароль: ");
var password = ReadPassword();
var dto = new LoginDto
{
Username = username,
Password = password,
};
var (success, message, user) = await _authService.LoginAsync(dto);
Console.WriteLine($"\n{message}");
if (success && user != null)
{
Console.WriteLine($"Останній вхід: {user.LastLoginDate?
.ToString("yyyy-MM-dd HH:mm:ss") ?? "Вперше"}");
}
}
// Безпечне введення пароля без відображення символів.
// Користувач вводить пароль, але на екрані показуються "зірочки".
// Підтримується видалення символів клавішею Backspace.
// Введення завершується після натискання Enter.
private static string ReadPassword()
{
var password = String.Empty;
ConsoleKey key;
do
{
// Читаємо натиснуту клавішу без відображення її в консолі
// intercept: true -> символ не буде показаний
// https://learn.microsoft.com/en-us/dotnet/api/system.console.readkey
var keyInfo = Console.ReadKey(intercept: true);
key = keyInfo.Key;
if (key == ConsoleKey.Backspace && password.Length > 0)
{
password = password[..^1];
// видаляємо останній символ із рядка
Console.Write("\b \b");
// створюємо ефект стирання останнього символа на екрані
}
else if (!char.IsControl(keyInfo.KeyChar))
{ // Якщо натиснута клавіша не є службовою (Enter, Ctrl тощо)
password += keyInfo.KeyChar;
Console.Write("*");
}
} while (key != ConsoleKey.Enter);
Console.WriteLine();
return password;
}
}
}