-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
238 lines (213 loc) · 10.6 KB
/
Copy pathProgram.cs
File metadata and controls
238 lines (213 loc) · 10.6 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
using Microsoft.EntityFrameworkCore;
using AKhderApi.Context;
using AKhderApi.Repositories;
using AKhderApi.Helpers;
using Microsoft.AspNetCore.Identity;
using AKhderApi.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using AKhderApi.Services;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.Google;
using FluentValidation;
using AKhderApi.Validators;
using Microsoft.OpenApi.Models;
using Stripe;
using SmartCartCarbonFootprintApi.Services;
using InvoiceService = SmartCartCarbonFootprintApi.Services.InvoiceService;
using SmartCartCarbonFootprintApi.Helpers;
using AKhderApi.Hubs;
namespace AKhderApi
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll",
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
// Add services to the container.
builder.Services.Configure<JWT>(builder.Configuration.GetSection("JWT"));
builder.Services.PostConfigure<JWT>(options =>
{
options.Key = Environment.GetEnvironmentVariable("JWT_KEY") ?? options.Key;
});
builder.Services.AddIdentity<User, IdentityRole>()
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders();
builder.Services.AddScoped<IAuthService, AuthService>();
builder.Services.AddScoped<AuthService>();
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<IEmailService, EmailService>();
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseLazyLoadingProxies().UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
o.RequireHttpsMetadata = false;
o.SaveToken = false;
o.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidIssuer = builder.Configuration["JWT:Issuer"],
ValidAudience = builder.Configuration["JWT:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("JWT_KEY") ?? builder.Configuration["JWT:Key"]!)),
NameClaimType = "uid",
ClockSkew = TimeSpan.Zero
};
})
// Add Cookie authentication for external login (Google)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.LoginPath = "/api/Auth/LoginGoogle"; // Set the login path for initiating Google login
options.Events.OnRedirectToLogin = context =>
{
// Return 401 instead of redirecting to the login page
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return Task.CompletedTask;
};
options.Events.OnRedirectToAccessDenied = context =>
{
// Return 403 instead of redirecting
context.Response.StatusCode = StatusCodes.Status403Forbidden;
return Task.CompletedTask;
};
})
.AddGoogle(GoogleDefaults.AuthenticationScheme, options =>
{
options.ClientId = Environment.GetEnvironmentVariable("GOOGLE_CLIENTID") ?? builder.Configuration["Authentication:Google:ClientId"]!;
options.ClientSecret = Environment.GetEnvironmentVariable("GOOGLE_CLIENTSECRET") ?? builder.Configuration["Authentication:Google:ClientSecret"]!;
options.Scope.Add("profile");
options.SaveTokens = true;
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; // Use cookies for sign-in
})
.AddFacebook(facebookOptions =>
{
facebookOptions.AppId = Environment.GetEnvironmentVariable("FACE_APPID") ?? builder.Configuration["Authentication:Facebook:AppId"]!;
facebookOptions.AppSecret = Environment.GetEnvironmentVariable("FACE_APPSECRET") ?? builder.Configuration["Authentication:Facebook:AppSecret"]!;
facebookOptions.SaveTokens = true;
facebookOptions.Scope.Add("public_profile");
facebookOptions.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});
builder.Services.AddControllers();
builder.Services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
builder.Services.AddValidatorsFromAssemblyContaining<UserValidator>();
builder.Services.AddScoped<IUnitOfWork, UnitOfWork>();
builder.Services.AddAutoMapper(typeof(Program).Assembly);
builder.Services.AddAutoMapper(typeof(MappingProfile).Assembly);
builder.Services.AddMemoryCache();
var emailSettings = new EmailSettings
{
SmtpServer = builder.Configuration["Email:SmtpServer"],
Port = builder.Configuration.GetValue<int>("Email:Port"),
Username = Environment.GetEnvironmentVariable("EMAIL_USERNAME") ?? builder.Configuration["Email:Username"],
Password = Environment.GetEnvironmentVariable("EMAIL_PASSWORD") ?? builder.Configuration["Email:Password"],
FromAddress = builder.Configuration["Email:FromAddress"]
};
if (string.IsNullOrEmpty(emailSettings.SmtpServer))
{
throw new Exception("Email configuration is missing or invalid.");
}
#region stripe
var stripeSettings = new StripeSettings
{
Publishablekey = Environment.GetEnvironmentVariable("STRIPE_PUBLISHKEY") ?? builder.Configuration["Stripe:Publishablekey"],
Secretkey = Environment.GetEnvironmentVariable("STRIPE_SECRETKEY") ?? builder.Configuration["Stripe:Secretkey"],
WebhookSecret = builder.Configuration["Stripe:WebhookSecret"],
SuccessUrl = builder.Configuration["Stripe:SuccessUrl"],
CancelUrl = builder.Configuration["Stripe:CancelUrl"]
};
if (string.IsNullOrEmpty(stripeSettings.Secretkey))
{
throw new Exception("Stripe configuration is missing or invalid.");
}
builder.Services.AddScoped<TokenService>();
builder.Services.AddScoped<CustomerService>();
builder.Services.AddScoped<ChargeService>();
builder.Services.AddScoped<ProductService>();
builder.Services.AddScoped<PaymentService>();
builder.Services.AddScoped<InvoiceService>();
builder.Services.AddScoped<StripeService>();
builder.Services.AddScoped<OrderService>();
#endregion
builder.Services.AddScoped<QRCodeService>();
builder.Services.AddScoped<ICartService, CartService>();
builder.Services.AddAutoMapper(typeof(Program));
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSwaggerGen(swagger =>
{
// This is to generate the default UI of Swagger Documentation
swagger.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "AKhder API",
Description = "API for e-commerce platform."
});
// To Enable authorization using Swagger (JWT)
swagger.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
Name = "Authorization",
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Description = "Enter 'Bearer' [space] and then your valid token in the text input below.\r\n\r\nExample: \"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9\"",
});
swagger.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] {}
}
});
});
builder.Services.AddSignalR();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsProduction() || app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(opt =>
{
opt.SwaggerEndpoint("/swagger/v1/swagger.json", "AKhder API v1");
});
}
app.UseHttpsRedirection();
// Enable CORS
app.UseCors("AllowAll");
StripeConfiguration.ApiKey = Environment.GetEnvironmentVariable("STRIPE_SECRETKEY") ?? builder.Configuration.GetSection("Stripe:Secretkey").Get<string>();
app.UseAuthentication();
app.UseAuthorization();
app.UseStaticFiles();
app.MapControllers();
app.MapHub<NotificationHub>("/notificationHub");
app.Run();
}
}
}