-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
254 lines (213 loc) · 10 KB
/
Program.cs
File metadata and controls
254 lines (213 loc) · 10 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
using NLog.Web;
using NLog;
using CyberPayAuthenticationApi.Data;
using CyberPayAuthenticationApi.Interfaces;
using CyberPayAuthenticationApi.Models;
using CyberPayAuthenticationApi.Repository;
using CyberPayAuthenticationApi.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Text;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Logging;
using Hangfire;
using HangfireBasicAuthenticationFilter;
namespace CyberPayAuthenticationApi
{
public class Program
{
//change it from:: public static void Main(string[] args) to:: public static async Task Main(string[] args)
public static async Task Main(string[] args)
{
//for logging
var logger = LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
logger.Debug("init main");
//try catch for logger
try
{
var builder = WebApplication.CreateBuilder(args);
//for logging
//NLog: Setup NLog for Dependency injection
builder.Logging.ClearProviders();
builder.Host.UseNLog();
//for hangfire
builder.Services.AddHangfire((sp, config) =>{
var connectionString = sp.GetRequiredService<IConfiguration>().GetConnectionString("DefaultConnection");
config.UseSqlServerStorage(connectionString);
});
builder.Services.AddHangfireServer();
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddTransient<Seed>();
//Add this so that you won't get stuck in a loop when you run your program
builder.Services.AddControllers().AddJsonOptions(x => x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles);
builder.Services.AddScoped<IBusinessTypeRepository, BusinessTypeRepository>();
builder.Services.AddScoped<ICountryRepository, CountryRepository>();
builder.Services.AddScoped<ICreateAccountRepository, CreateAccountRepository>();
builder.Services.AddScoped<IUpdateProfileRepository, UpdateProfileRepository>();
builder.Services.AddScoped<CyberPayAPIService>();
//for email sending
//we use AddTransiet to initialize an object whenever we need or with each request
builder.Services.AddTransient<IMailService, MailService>();
//for identity framework
//adding configuration for identity
builder.Services.AddIdentityCore<User>(opt =>
{
//reducing the complexity of a password
opt.Password.RequireNonAlphanumeric = false;
//this prevents us from having duplicate emails in our database
opt.User.RequireUniqueEmail = true;
})
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<DataContext>()
.AddDefaultTokenProviders();//this is for two factor authentication
// leave it as builder.Services.AddAuthentication(); if you dont have a jwt
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(opt =>
{
opt.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.
GetBytes(builder.Configuration["JWTSettings:TokenKey"])),
};
});
//very important for identity framework
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("AdminPolicy", policy => policy.RequireRole("Admin"));
options.AddPolicy("MemberPolicy", policy => policy.RequireRole("Member"));
});
//to allow calls from frontend
builder.Services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", builder =>
{
builder.AllowAnyOrigin();
builder.AllowAnyMethod();
builder.AllowAnyHeader();
});
});
//for JwtToken
builder.Services.AddScoped<TokenService>();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
//for JwtToken
builder.Services.AddSwaggerGen(c =>
{
var jwtSecurityScheme = new OpenApiSecurityScheme
{
BearerFormat = "JWT",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = JwtBearerDefaults.AuthenticationScheme,
Description = "Put Bearer + your token in the box below",
Reference = new OpenApiReference
{
Id = JwtBearerDefaults.AuthenticationScheme,
Type = ReferenceType.SecurityScheme
}
};
c.AddSecurityDefinition(jwtSecurityScheme.Reference.Id, jwtSecurityScheme);
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
jwtSecurityScheme, Array.Empty<string>()
}
});
});
builder.Services.AddDbContext<DataContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
var app = builder.Build();
using (var scoped = app.Services.CreateScope())
{
var dbContext = scoped.ServiceProvider.GetRequiredService<DataContext>();
dbContext.Database.Migrate();
}
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
//for JwtToken
app.UseSwaggerUI(c =>
{
c.ConfigObject.AdditionalItems.Add("persistAuthorization", "true");
});
}
else
{
app.UseSwagger();
//for JwtToken
app.UseSwaggerUI(c =>
{
c.ConfigObject.AdditionalItems.Add("persistAuthorization", "true");
});
}
app.UseHttpsRedirection();
//to allow calls from frontend
app.UseCors(x =>
{
x.AllowAnyOrigin();
x.WithOrigins("http://localhost:3000");
x.AllowAnyMethod();
x.AllowAnyHeader();
});
app.UseAuthorization();
// Seeding identity
app.MapControllers();
var scope = app.Services.CreateScope();
var serviceProvider = scope.ServiceProvider;
var context = serviceProvider.GetRequiredService<DataContext>();
var userManager = serviceProvider.GetRequiredService<UserManager<User>>();
var logging = serviceProvider.GetRequiredService<ILogger<Program>>();
try
{
await context.Database.MigrateAsync();
var seed = new Seed(context, userManager);
await seed.SeedUsersAsync(app);
}
catch (Exception ex)
{
logging.LogError(ex, "A problem occurred during migration or seeding");
}
//for hangfire
//enabling hangfire dashboard to view the details of our jobs
//to use the dashboard ass hangfire to the application URL for example localhost:7105/hangfire
//"WelcomeToCyberPay/job-dashboard" is a custom path for example instead of localhost:7105/hangfire you can now do localhost:7105/WelcomeToCyberPay/job-dashboard
//or you can just do app.UseHangfireDashboard(); to not configure any authorization
//to customize the hangfire dashboard install the nuget package of name "Hangfire.Dashboard.Basic.Authentication"
app.UseHangfireDashboard("/job-dashboard", new DashboardOptions
{
DashboardTitle = "Welcome message to Registered Businesses",
DisplayStorageConnectionString = false,
Authorization = new[]
{
new HangfireCustomBasicAuthenticationFilter
{
User = "admin",
Pass = "Pa$$w0rd"
}
}
});
app.Run();
}
catch(Exception ex)
{
logger.Error(ex);
}
finally
{
LogManager.Shutdown();
}
}
}
}