-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
209 lines (176 loc) · 6.42 KB
/
Program.cs
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
using System.Text.Json;
using System.Text.Json.Serialization;
using ai_poker_coach.Models.DataTransferObjects;
using ai_poker_coach.Models.DataTransferObjects.Authentication;
using ai_poker_coach.Models.Domain;
using DotNet8Authentication.Data;
using DotNetEnv;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Filters;
var builder = WebApplication.CreateBuilder(args);
if (builder.Environment.IsDevelopment())
{
Env.Load();
}
else if (builder.Environment.IsProduction())
{
Env.Load("/home/will/ai-poker-coach/.env");
}
builder.Services.Configure<IdentityOptions>(options =>
{
options.User.RequireUniqueEmail = true;
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
options.AddSecurityDefinition(
"oauth2",
new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Name = "Authorization",
Type = SecuritySchemeType.ApiKey
}
);
options.OperationFilter<SecurityRequirementsOperationFilter>();
});
builder.Services.AddDbContext<IdentityDataContext>(options =>
{
options.UseNpgsql(Environment.GetEnvironmentVariable("POSTGRES_CONNECTION"));
});
builder.Services.AddAuthorization();
builder.Services.AddIdentityApiEndpoints<ApplicationUser>().AddEntityFrameworkStores<IdentityDataContext>();
builder
.Services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
});
builder.Services.AddHttpClient();
builder.Services.AddCors(options =>
{
options.AddPolicy(
"ProdCorsPolicy",
policy =>
{
policy
.WithOrigins("https://ai-poker-coach.netlify.app", "https://aipokercoach.willbraun.dev")
.AllowAnyHeader()
.AllowAnyMethod();
}
);
options.AddPolicy(
"DevCorsPolicy",
policy =>
{
policy.WithOrigins("http://localhost:3000").AllowAnyHeader().AllowAnyMethod();
}
);
});
var app = builder.Build();
int port;
if (app.Environment.IsDevelopment())
{
port = 5159;
app.UseSwagger();
app.UseSwaggerUI();
app.UseCors("DevCorsPolicy");
}
else
{
port = 5000;
app.UseCors("ProdCorsPolicy");
}
app.MapIdentityApi<ApplicationUser>();
app.MapPost(
"/customLogin",
async Task<IResult> (AuthRequestDto requestBody, UserManager<ApplicationUser> userManager) =>
{
var user = await userManager.FindByEmailAsync(requestBody.Email);
if (user == null)
{
return TypedResults.Unauthorized();
}
using var httpClient = new HttpClient();
try
{
var response = await httpClient.PostAsJsonAsync($"http://localhost:{port}/login", requestBody);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
var responseObject = JsonSerializer.Deserialize<LoginInnerResponseDto>(responseBody);
if (responseObject == null)
{
return TypedResults.UnprocessableEntity("Login error: response object is null");
}
return TypedResults.Ok(new LoginResponseDto(user, responseObject));
}
catch (HttpRequestException ex)
{
if (ex.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
return TypedResults.Unauthorized();
}
else
{
return TypedResults.UnprocessableEntity($"Login error: {ex.StatusCode} - {ex.Message}");
}
}
}
)
.AllowAnonymous();
app.MapPost(
"/customRegister",
async Task<IResult> (AuthRequestDto requestBody, UserManager<ApplicationUser> userManager) =>
{
var user = await userManager.FindByEmailAsync(requestBody.Email);
if (user != null)
{
return TypedResults.Conflict("Email already exists");
}
using var httpClient = new HttpClient();
try
{
var response = await httpClient.PostAsJsonAsync($"http://localhost:{port}/register", requestBody);
if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
{
string responseBody = await response.Content.ReadAsStringAsync();
var responseObject = JsonSerializer.Deserialize<RegisterInnerResponseDto>(responseBody);
return TypedResults.BadRequest(responseObject);
}
}
catch (HttpRequestException ex)
{
return TypedResults.BadRequest(ex.Message);
}
try
{
var newUser = await userManager.FindByEmailAsync(requestBody.Email);
if (newUser == null)
{
return TypedResults.UnprocessableEntity("User not found after registration");
}
var loginResponse = await httpClient.PostAsJsonAsync($"http://localhost:{port}/login", requestBody);
loginResponse.EnsureSuccessStatusCode();
string loginResponseBody = await loginResponse.Content.ReadAsStringAsync();
var loginResponseObject = JsonSerializer.Deserialize<LoginInnerResponseDto>(loginResponseBody);
if (loginResponseObject == null)
{
return TypedResults.UnprocessableEntity("Login error: response object is null");
}
return TypedResults.Ok(new LoginResponseDto(newUser, loginResponseObject));
}
catch (HttpRequestException ex)
{
return TypedResults.UnprocessableEntity(
$"Account successfully created, but there was a problem logging in: {ex.StatusCode} - {ex.Message}"
);
}
}
)
.AllowAnonymous();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();