-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
230 lines (195 loc) · 8.67 KB
/
Copy pathProgram.cs
File metadata and controls
230 lines (195 loc) · 8.67 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
using Microsoft.EntityFrameworkCore;
using API.Data;
using API.Entities;
using Microsoft.AspNetCore.Identity;
using Microsoft.CodeAnalysis.Options;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using API.Interfaces;
using API.Services;
using API.Repository;
using Microsoft.OpenApi.Models;
using System.Security.Claims;
using API.Entities.Email;
using API.Helpers;
using API.Hubs;
using API.SignalR;
using API.Interfaces.IRepositories;
using API.Interfaces.IServices;
using API.Entities.Cloudinary;
using Microsoft.Bot.Connector.Authentication;
using Microsoft.Bot.Builder.Integration.AspNet.Core;
using Microsoft.Bot.Builder;
using System.Text.Json.Serialization;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
})
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
// chuyển các giá trị kiểu enum thành chữ chứ không còn là 0, 1, 2,...
options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
});
builder.Services.AddSignalR()
.AddJsonProtocol(options => {
// Cấu hình riêng cho SignalR để đảm bảo nó cũng bỏ qua vòng lặp
options.PayloadSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
});
// swagger
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(option =>
{
option.SwaggerDoc("v1", new OpenApiInfo { Title = "Demo API", Version = "v1" });
option.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Description = "Please enter a valid token",
Name = "Authorization",
Type = SecuritySchemeType.Http,
BearerFormat = "JWT",
Scheme = "Bearer"
});
option.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type=ReferenceType.SecurityScheme,
Id="Bearer"
}
},
new string[]{}
}
});
});
builder.Services.AddDbContext<AppDbContext>(opt =>
{
opt.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
}); // connect with sql server
builder.Services.AddCors(); //allow client connect to API
// config for password
builder.Services.AddIdentity<AppUser, IdentityRole>(options =>
{
options.SignIn.RequireConfirmedEmail = true;
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireUppercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequiredLength = 12;
})
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders();
builder.Services.AddAuthentication().AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidateAudience = true,
ValidAudience = builder.Configuration["Jwt:Audience"],
ValidateIssuerSigningKey = true,
RoleClaimType = ClaimTypes.Role,
IssuerSigningKey = new SymmetricSecurityKey(
System.Text.Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])
),
};
options.Events = new JwtBearerEvents // WebSocket không cho phép trình duyệt thêm 'custom header' -> dùng (Authorization: Bearer ...)
{
OnMessageReceived = context => // mỗi khi có request yêu cầu xthuc jwt
{
var accessToken = context.Request.Query["access_token"];//Lấy giá trị token nằm trong query string của request
var path = context.HttpContext.Request.Path; //Lấy đường dẫn của request hiện tại: /hubs/presence [?access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6...]
if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs"))
{
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});
// --- Đăng ký repository (tầng data)
builder.Services.AddScoped<IReservationRepository, ReservationRepository>();
builder.Services.AddScoped<IChargingPostRepository, ChargingPostRepository>();
builder.Services.AddScoped<IStationRepository, StationRepository>();
builder.Services.AddScoped<IVehicleRepository, VehicleRepository>();
builder.Services.AddScoped<IWalletRepository, WalletRepository>();
builder.Services.AddScoped<IWalletTransactionRepository, WalletTransactionRepository>();
builder.Services.AddScoped<IChargingPackageRepository, ChargingPackageRepository>();
builder.Services.AddScoped<IDriverPackageRepository, DriverPackageRepository>();
builder.Services.AddScoped<IVehicleModelRepository, VehicleModelRepository>();
builder.Services.AddScoped<IChargingSessionRepository, ChargingSessionRepository>();
builder.Services.AddScoped<IPricingRepository, PricingRepository>();
builder.Services.AddScoped<IReceiptRepository, ReceiptRepository>();
builder.Services.AddScoped<IReportRepository, ReportRepository>();
builder.Services.AddScoped<IAssignmentRepository, AssignmentRepository>();
// Đăng ký Unit of Work
builder.Services.AddScoped<IUnitOfWork, UnitOfWork>();
// --- Đăng ký service (tầng logic)
builder.Services.AddScoped<ITokenService, TokenService>();
builder.Services.AddScoped<IReservationService, ReservationService>();
builder.Services.AddScoped<IWalletService, WalletService>();
builder.Services.AddScoped<IQRCodeService, QRCodeService>();
builder.Services.AddScoped<IChargingSessionService, ChargingSessionService>();
builder.Services.AddScoped<IChargingService, ChargingService>();
builder.Services.AddScoped<IPackageService, PackageService>();
builder.Services.AddScoped<IPricingService, PricingService>();
builder.Services.AddScoped<IReportService, ReportService>();
builder.Services.AddScoped<IAssignmentService, AssignmentService>();
builder.Services.AddScoped<IReceiptService, ReceiptService>();
builder.Services.AddScoped<IAuthService, AuthService>();
builder.Services.AddScoped<IAnalyticsService, AnalyticsService>();
// Cấu hình Email Settings
builder.Services.Configure<EmailSettings>(builder.Configuration.GetSection("EmailSettings"));
builder.Services.AddScoped<IEmailService, EmailService>();
builder.Services.AddScoped<IVnPayService, VnPayService>();
// đăng ký service check status gói của người dùng mỗi 24h
builder.Services.AddHostedService<PackageStatusChecker>();
builder.Services.AddHostedService<ReservationCleanupService>();
builder.Services.AddHostedService<IdleFeeService>();
builder.Services.AddHostedService<ReservationMonitorService>();
// Đăng ký SignalR
// builder.Services.AddSignalR();
builder.Services.AddSingleton<IChargingSimulationService, ChargingSimulationService>();
builder.Services.Configure<CloudinarySettings>(builder.Configuration.GetSection("CloudinarySettings"));
// Thêm dịch vụ HTTPClient (cần cho Bot Framework)
builder.Services.AddHttpClient();
// Tạo và đăng ký Bot Framework Authentication
builder.Services.AddSingleton<BotFrameworkAuthentication, ConfigurationBotFrameworkAuthentication>();
// Đăng ký Adapter xử lý lỗi
// builder.Services.AddSingleton<IBotFrameworkHttpAdapter, AdapterWithErrorHandler>();
// Đăng ký lớp logic Bot của bạn
// AddTransient nghĩa là một instance mới sẽ được tạo cho mỗi lượt hội thoại
// builder.Services.AddTransient<IBot, SimpleEvBot>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod()
.WithOrigins("https://localhost:4200", "http://localhost:4200").WithOrigins("https://localhost:4200", "http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()); //set connect
// Client (Angular) sẽ kết nối đến đường dẫn "/hubs/notification"
app.MapHub<NotificationHub>("/hubs/notification");
// // Bật tính năng này để có thể truy cập ảnh từ URL
// app.UseStaticFiles();
// app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
// Thêm endpoint cho hub
app.MapHub<ChargingHub>("/hubs/charging");
//DatNguyen-SignalR-End_Point
app.MapHub<ConnectCharging>("/hubs/connect-charging");
app.MapHub<ReservationHub>("hubs/reservation");
app.MapHub<BotHub>("/hubs/bot");
app.Run();