-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
236 lines (180 loc) · 7.07 KB
/
Program.cs
File metadata and controls
236 lines (180 loc) · 7.07 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
using AuthApiMinimal.Data;
using AuthApiMinimal.Models;
using AuthApiMinimal.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using System.Security.Claims;
using Microsoft.AspNetCore.Mvc;
// DotNetEnv lataa .env-tiedoston (jos käytät)
DotNetEnv.Env.Load();
var builder = WebApplication.CreateBuilder(args);
// Ympäristömuuttujat
var connString = Environment.GetEnvironmentVariable("DEFAULT_CONNSTRING")
?? "Server=(localdb)\\MSSQLLocalDB;Database=AuthApiDb;Trusted_Connection=True;";
var jwtKey = Environment.GetEnvironmentVariable("JWT_KEY") ?? "SUPER_SECRET_KEY_123_FOR_MY_AND_EVERYONE_ELSES_EYES_ONLY";
var jwtIssuer = Environment.GetEnvironmentVariable("JWT_ISSUER") ?? "AuthApi";
var jwtAudience = Environment.GetEnvironmentVariable("JWT_AUDIENCE") ?? "AuthApi";
// Palvelut
builder.Services.AddDbContext<AppDbContext>(opts =>
opts.UseSqlServer(connString));
builder.Services.AddScoped<JwtService>();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateIssuerSigningKey = true,
ValidIssuer = jwtIssuer,
ValidAudience = jwtAudience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey))
};
});
builder.Services.AddAuthorization();
var myAllowSpecificOrigins = "_myAllowSpecificOrigins";
builder.Services.AddCors(options =>
{
options.AddPolicy(myAllowSpecificOrigins, policy =>
{
policy
.WithOrigins("http://localhost:3000")
.AllowAnyMethod()
.AllowAnyHeader();
});
});
var app = builder.Build();
app.UseCors(myAllowSpecificOrigins);
app.UseAuthentication();
app.UseAuthorization();
// Routes
app.MapPost("/api/users/register", async (AppDbContext db, JwtService jwt, RegisterRequest req) =>
{
if (db.Users.Any(u => u.Email == req.Email))
return Results.BadRequest("Email already registered");
var user = new AppUser
{
Email = req.Email,
PasswordHash = BCrypt.Net.BCrypt.HashPassword(req.Password)
};
db.Users.Add(user);
await db.SaveChangesAsync();
var token = jwt.GenerateToken(user);
return Results.Ok(new { token });
});
app.MapPost("/api/users/login", async (AppDbContext db, JwtService jwt, LoginRequest req) =>
{
var user = db.Users.SingleOrDefault(u => u.Email == req.Email);
if (user == null) return Results.BadRequest("Invalid credentials");
if (!BCrypt.Net.BCrypt.Verify(req.Password, user.PasswordHash))
return Results.BadRequest("Invalid credentials");
var token = jwt.GenerateToken(user);
return Results.Ok(new { token });
});
app.MapDelete("/api/users/delete", [Authorize] async (AppDbContext db, HttpContext context) =>
{
var userEmail = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (string.IsNullOrEmpty(userEmail))
return Results.Unauthorized();
var user = await db.Users.FirstOrDefaultAsync(u => u.Email == userEmail);
if (user == null)
return Results.NotFound("User not found");
db.Users.Remove(user);
await db.SaveChangesAsync();
return Results.Ok("Account deleted successfully.");
});
app.MapGet("/api/search", [Authorize] async (AppDbContext db, HttpContext context, string keyword, int page, int pageSize) =>
{
var userEmail = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
var user = await db.Users.FirstOrDefaultAsync(u => u.Email == userEmail);
if (user == null)
return Results.NotFound("User not found");
var totalCount = await db.Infos
.Where(i => i.UserId == user.Id && i.Note.Contains(keyword))
.CountAsync();
var results = await db.Infos
.Where(i => i.UserId == user.Id && i.Note.Contains(keyword))
.OrderByDescending(i => i.Id)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToListAsync();
return Results.Ok(new {
TotalCount = totalCount,
Items = results});
});
app.MapPost("/api/info", [Authorize] async (AppDbContext db, HttpContext context, InfoDto dto) =>
{
var userEmail = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (userEmail == null)
return Results.Unauthorized();
var user = await db.Users.FirstOrDefaultAsync(u => u.Email == userEmail);
if (user == null)
return Results.NotFound("User not found");
var info = new Info
{
Note = dto.Note,
UserId = user.Id
};
db.Infos.Add(info);
await db.SaveChangesAsync();
return Results.Ok(info);
});
app.MapGet("/api/info", [Authorize] async (AppDbContext db, HttpContext context, int page = 1, int pageSize = 4) =>
{
if (page < 1) page = 1;
if (pageSize < 1) pageSize = 4;
var userEmail = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
var user = await db.Users.FirstOrDefaultAsync(u => u.Email == userEmail);
if (user == null)
return Results.NotFound("User not found");
var totalCount = await db.Infos
.Where(i => i.UserId == user.Id)
.CountAsync();
var items = await db.Infos
.Where(i => i.UserId == user.Id)
.OrderByDescending(i => i.Id) // vaihtoehtoisesti voisi käyttää jonkinlaista createdAt-arvoa...
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToListAsync();
return Results.Ok(new
{
TotalCount = totalCount,
Page = page,
PageSize = pageSize,
Items = items
});
});
app.MapPut("/api/info/{id}", [Authorize] async (int id, AppDbContext db, HttpContext context, InfoDto dto) =>
{
var userEmail = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
var user = await db.Users.FirstOrDefaultAsync(u => u.Email == userEmail);
if (user == null)
return Results.NotFound("User not found");
var info = await db.Infos.FirstOrDefaultAsync(i => i.Id == id && i.UserId == user.Id);
if (info == null)
return Results.NotFound("Note not found or does not belong to user");
info.Note = dto.Note;
await db.SaveChangesAsync();
return Results.Ok(info);
});
// delete note
app.MapDelete("/api/info/{id}", [Authorize] async (int id, AppDbContext db, HttpContext context) =>
{
var userEmail = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
var user = await db.Users.FirstOrDefaultAsync(u => u.Email == userEmail);
if (user == null)
return Results.NotFound("User not found");
var info = await db.Infos.FirstOrDefaultAsync(i => i.Id == id && i.UserId == user.Id);
if (info == null)
return Results.NotFound("Note not found or does not belong to user");
db.Remove(info);
await db.SaveChangesAsync();
return Results.Ok();
});
app.Run();
public record RegisterRequest(string Email, string Password);
public record LoginRequest(string Email, string Password);
public record InfoDto(string Note);