3 Commits

Author SHA1 Message Date
AleksDw
a81a57654c Merge branch 'EventRegistrationEndpoints' 2025-06-01 14:20:46 +02:00
AleksDw
48184cd8b6 Add remove endpoint 2025-05-31 02:24:54 +02:00
AleksDw
f2ccde2ea6 Join, leave, registrations endpoints
todo: remove smb from event endpoint
2025-05-31 02:19:01 +02:00
10 changed files with 189 additions and 160 deletions

View File

@@ -0,0 +1,11 @@
using System.ComponentModel.DataAnnotations;
using WebApp.Entities;
namespace WebApp.DTOs;
// Output values in JSON file
public record class EventRegistrationDto(
int EventId,
int UserId,
DateTime RegisteredAt
);

View File

@@ -1,4 +1,4 @@
using System.Security.Cryptography;
using System.Security.Cryptography;
using System.Text;
using Microsoft.EntityFrameworkCore;
using WebApp.Data;
@@ -18,7 +18,6 @@ namespace WebApp.Endpoints
var group = app.MapGroup("api/auth")
.WithParameterValidation();
// POST /api/auth/login
group.MapPost("/login", async (LoginDto dto, ApplicationDbContext context, GeneralUseHelpers guh) =>
{
var user = await context.WebUsers.FirstOrDefaultAsync(u => u.Email == dto.Email);
@@ -39,7 +38,6 @@ namespace WebApp.Endpoints
});
});
// POST /api/auth/logout
group.MapPost("/logout", async (HttpContext httpContext, GeneralUseHelpers guh) =>
{
var token = await guh.GetTokenFromHTTPContext(httpContext);
@@ -56,7 +54,6 @@ namespace WebApp.Endpoints
return Results.Ok(new { success = true });
});
// GET /api/auth/my_account
group.MapGet("/my_account", async (HttpContext httpContext, GeneralUseHelpers guh) =>
{
var token = await guh.GetTokenFromHTTPContext(httpContext);
@@ -80,7 +77,6 @@ namespace WebApp.Endpoints
})
.WithName(GetUserEndpointName);
// GET /api/auth/my_events
group.MapGet("/my_events", async (HttpContext httpContext, GeneralUseHelpers guh, ApplicationDbContext context) =>
{
var token = await guh.GetTokenFromHTTPContext(httpContext);
@@ -126,14 +122,13 @@ namespace WebApp.Endpoints
});
// POST /api/auth/add_skill
group.MapPost("/add_skill", async (SingleSkillDto dto, HttpContext httpContext, ApplicationDbContext context, GeneralUseHelpers guh) =>
{
// Uzyskaj użytkownika z tokenu
Token? token = await guh.GetTokenFromHTTPContext(httpContext);
User? user = await guh.GetUserFromToken(token);
// Tylko wolontariusze powinni móc dodawać swoje skille
// Tylko wolontariusze powinno móc dodawać swoje skille
if (user == null || user.IsOrganisation) {
return Results.Json(new { message = "Unauthorized" }, statusCode: 401);
}
@@ -163,14 +158,14 @@ namespace WebApp.Endpoints
return Results.Json(new { message = "Skill added successfully!" }, statusCode: 201);
});
// POST /api/auth/remove_skill
group.MapPost("/remove_skill", async (SingleSkillDto dto, HttpContext httpContext, ApplicationDbContext context, GeneralUseHelpers guh) =>
{
// Uzyskaj użytkownika z tokenu
Token? token = await guh.GetTokenFromHTTPContext(httpContext);
User? user = await guh.GetUserFromToken(token);
// Tylko wolontariusze powinni móc usuwać swoje skille
// Tylko wolontariusze powinien móc usuwac swoje skille
if (user == null || user.IsOrganisation)
{
return Results.Json(new { message = "Unauthorized" }, statusCode: 401);
@@ -183,28 +178,28 @@ namespace WebApp.Endpoints
return Results.Json(new { message = "Skill not found" }, statusCode: 404);
}
// Sprawdzamy, czy ten użytkownik ma już taki skill. Jeżeli nie ma, to nie ma sensu usuwać czegoś, czego nie ma.
// Sprawdzamy, czy ten użytkownik ma już taki skill. Jeżeli nie ma, nie ma sensu usuwac go kilkukrotnie.
VolunteerSkill? vs = await context.VolunteerSkills.FirstOrDefaultAsync(v => v.UserId == user.UserId && v.SkillId == dto.Skill);
if (vs is not null)
{
// Ma - zatem musimy usunąć otrzymany VolunteerSkill z bazy
// Nie ma - zatem musimy dodać nowy VolunteerSkill do bazy
VolunteerSkill newVs = dto.ToVolunteerSkillEntity(user.UserId);
await context.VolunteerSkills.Where(v => v.SkillId == dto.Skill)
.ExecuteDeleteAsync();
}
else
{
// Nie ma - (ta para UserId <-> SkillId nie istnieje w bazie). Zwracamy błąd.
// Ma - (ta para UserId <-> SkillId już istnieje w bazie) użytkownik już ma ten skill
return Results.Json(new { message = "You don't have this skill" }, statusCode: 400);
}
return Results.Json(new { message = "Skill deleted successfully!" }, statusCode: 201);
});
// GET /api/auth/skills
group.MapGet("/skills", async (HttpContext httpContext, ApplicationDbContext context, GeneralUseHelpers guh) =>
group.MapGet("/get_skills", async (HttpContext httpContext, ApplicationDbContext context, GeneralUseHelpers guh) =>
{
// Uzyskaj użytkownika z tokenu
Token? token = await guh.GetTokenFromHTTPContext(httpContext);

View File

@@ -0,0 +1,135 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.EntityFrameworkCore;
using System.Security.Cryptography;
using WebApp.Data;
using WebApp.DTOs;
using WebApp.Entities;
using WebApp.Mapping;
namespace WebApp.Endpoints
{
public static class EventsRegistrationEndpoints
{
const string GetEventEndpointRegistrationName = "GetEventRegistration";
public static RouteGroupBuilder MapEventsRegistrationEndpoints(this WebApplication app)
{
var group = app.MapGroup("api/events")
.WithParameterValidation();
// POST /api/events/join/{id}
group.MapPost("/join/{id}",
async (int id, ApplicationDbContext dbContext, HttpContext httpContext, GeneralUseHelpers guhf) =>
{
Event? Eve = await dbContext.Events.FindAsync(id);
if (Eve is null)
return Results.Json(new { success = false, error_msg = "Event not found." });
Token? token = await guhf.GetTokenFromHTTPContext(httpContext);
User? user = await guhf.GetUserFromToken(token);
if (user is null || user.IsOrganisation)
return Results.Json(new { success = false, error_msg = "Unauthorized or organisations cannot register for events." });
if (await dbContext.EventRegistrations.AnyAsync(er => er.UserId == user.UserId && er.EventId == id))
return Results.Json(new { success = false, error_msg = "You are already registered for this event." });
if (Eve.EventDate < DateTime.UtcNow)
return Results.Json(new { success = false, error_msg = "This event has already ended." });
EventRegistration registration = new EventRegistration
{
UserId = user.UserId,
EventId = id,
RegisteredAt = DateTime.UtcNow
};
dbContext.EventRegistrations.Add(registration);
await dbContext.SaveChangesAsync();
return Results.Json(new { success = true });
});
// POST /api/events/leave/{id}
group.MapPost("/leave/{id}",
async (int id, ApplicationDbContext dbContext, HttpContext httpContext, GeneralUseHelpers guhf) =>
{
Event? Eve = await dbContext.Events.FindAsync(id);
if (Eve is null)
return Results.Json(new { success = false, error_msg = "Event not found." });
Token? token = await guhf.GetTokenFromHTTPContext(httpContext);
User? user = await guhf.GetUserFromToken(token);
if (user is null)
return Results.Json(new { success = false, error_msg = "Unauthorized." });
if (!await dbContext.EventRegistrations.AnyAsync(er => er.UserId == user.UserId && er.EventId == id))
return Results.Json(new { success = false, error_msg = "You are not registered for this event." });
if (Eve.EventDate < DateTime.UtcNow)
return Results.Json(new { success = false, error_msg = "This event has already ended." });
EventRegistration? registration = await dbContext.EventRegistrations
.FirstOrDefaultAsync(er => er.UserId == user.UserId && er.EventId == id);
dbContext.EventRegistrations.Remove(registration);
await dbContext.SaveChangesAsync();
return Results.Json(new { success = true });
});
// GET /api/events/registrations/{id}
group.MapGet("/registrations/{id}",
async (int id, ApplicationDbContext dbContext, HttpContext httpContext, GeneralUseHelpers guhf) =>
{
Event? Eve = await dbContext.Events.FindAsync(id);
if (Eve is null)
return Results.Json(new { success = false, error_msg = "Event not found." });
Token? token = await guhf.GetTokenFromHTTPContext(httpContext);
Organisation? org = await guhf.GetOrganisationFromToken(token);
if (org is null || org.OrganisationId != Eve.OrganisationId)
return Results.Json(new { success = false, error_msg = "Unauthorized." });
var registrations = await dbContext.EventRegistrations
.Where(er => er.EventId == id)
.Select(er => er.ToEventRegistrationDto())
.ToListAsync();
return Results.Json(new
{
success = true,
registrations
});
});
// POST /api/events/remove/{id}/{userId}
group.MapPost("/remove/{id}/{userId}",
async (int id, int userId, ApplicationDbContext dbContext, HttpContext httpContext, GeneralUseHelpers guhf) =>
{
Event? Eve = await dbContext.Events.FindAsync(id);
if (Eve is null)
return Results.Json(new { success = false, error_msg = "Event not found." });
Token? token = await guhf.GetTokenFromHTTPContext(httpContext);
Organisation? org = await guhf.GetOrganisationFromToken(token);
if (org is null || org.OrganisationId != Eve.OrganisationId)
return Results.Json(new { success = false, error_msg = "Unauthorized." });
EventRegistration? registration = await dbContext.EventRegistrations
.FirstOrDefaultAsync(er => er.UserId == userId && er.EventId == id);
if (registration is null)
return Results.Json(new { success = false, error_msg = "Registration not found." });
dbContext.EventRegistrations.Remove(registration);
await dbContext.SaveChangesAsync();
return Results.Json(new { success = true });
});
return group;
}
}
}

View File

@@ -1,4 +1,4 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using WebApp.Data;
using WebApp.DTOs;
@@ -134,7 +134,7 @@ namespace WebApp.Endpoints
// Uzyskaj organizację z tokenu
Token? token = await guhf.GetTokenFromHTTPContext(httpContext);
Organisation? org = await guhf.GetOrganisationFromToken(token);
if (org is null) return Results.Unauthorized();
if (org is null) return Results.StatusCode(403);
// Sprawdź, czy organizacja ma prawo
// do usunięcia tego (EventId = id) eventu.
@@ -161,6 +161,7 @@ namespace WebApp.Endpoints
List<EventSummaryDto> SearchResults = [];
List<Event> AllEvents = await dbContext.Events.ToListAsync();
if (sort is null || sort.ToUpper() != "ASC")
{
@@ -222,91 +223,6 @@ namespace WebApp.Endpoints
return Results.Ok(SearchResults);
});
// POST /events/1/add_skill
group.MapPost("/{id}/add_skill/",
async (int id, SingleSkillDto dto, ApplicationDbContext dbContext, HttpContext httpContext, GeneralUseHelpers guhf) =>
{
Event? Eve = await dbContext.Events.FindAsync(id);
if (Eve is null) return Results.Json(new { message = "Event not found" }, statusCode: 404);
// Sprawdź, czy token należy do organizacji, a jeżeli tak, to do której.
Token? token = await guhf.GetTokenFromHTTPContext(httpContext);
Organisation? org = await guhf.GetOrganisationFromToken(token);
// Jeśli token należy do organizacji, która utworzyła to wydarzenie,
// to zwróć także EventRegistrations. W przeciwnym razie usuń to pole
// przed jego wysłaniem!
if (org is null || org.OrganisationId != Eve.OrganisationId) return Results.Unauthorized();
// Szukamy skilla w bazie o ID takim, jak w otrzymanym DTO
Skill? skill = await dbContext.Skills.FindAsync(dto.Skill);
if (skill is null)
{
return Results.Json(new { message = "Skill not found" }, statusCode: 404);
}
// Sprawdzamy, czy to wydarzenie nie ma już takiego skilla. Jeżeli ma, nie ma sensu dodawać go kilkukrotnie.
EventSkill? es = await dbContext.EventSkills.FirstOrDefaultAsync(e => e.EventId == id && e.SkillId == dto.Skill);
if (es is null)
{
// Nie ma - zatem musimy dodać nowy EventSkill do bazy
EventSkill newEs = dto.ToEventSkillEntity(Eve.EventId);
dbContext.EventSkills.Add(newEs);
await dbContext.SaveChangesAsync();
}
else
{
// Ma - (ta para EventId <-> SkillId już istnieje w bazie); ten Event posiada już ten skill
return Results.Json(new { message = "Skill already assinged to this event!" }, statusCode: 400);
}
return Results.Json(new { message = "Skill added to event successfully!" }, statusCode: 201);
});
// POST /events/1/renive_skill
group.MapPost("/{id}/remove_skill/",
async (int id, SingleSkillDto dto, ApplicationDbContext dbContext, HttpContext httpContext, GeneralUseHelpers guhf) =>
{
Event? Eve = await dbContext.Events.FindAsync(id);
if (Eve is null) return Results.Json(new { message = "Event not found" }, statusCode: 404);
// Sprawdź, czy token należy do organizacji, a jeżeli tak, to do której.
Token? token = await guhf.GetTokenFromHTTPContext(httpContext);
Organisation? org = await guhf.GetOrganisationFromToken(token);
// Jeśli token należy do organizacji, która utworzyła to wydarzenie,
// to zwróć także EventRegistrations. W przeciwnym razie usuń to pole
// przed jego wysłaniem!
if (org is null || org.OrganisationId != Eve.OrganisationId) return Results.Unauthorized();
// Szukamy skilla w bazie o ID takim, jak w otrzymanym DTO
Skill? skill = await dbContext.Skills.FindAsync(dto.Skill);
if (skill is null)
{
return Results.Json(new { message = "Skill not found" }, statusCode: 404);
}
// Sprawdzamy, czy to wydarzenie nie ma już takiego skilla. Jeżeli nie ma, to nie ma sensu kasować czegoś, czego nie ma.
EventSkill? es = await dbContext.EventSkills.FirstOrDefaultAsync(e => e.EventId == id && e.SkillId == dto.Skill);
if (es is not null)
{
// Ma - zatem musimy usunąć ten EventSkill z bazy
await dbContext.EventSkills.Where(e => e.SkillId == dto.Skill)
.ExecuteDeleteAsync();
}
else
{
// Nie ma - (ta para EventId <-> SkillId nie istnieje w bazie); ten Event nie posiada tego skill'a
return Results.Json(new { message = "This skill isn't assinged to this event!" }, statusCode: 400);
}
return Results.Json(new { message = "Skill removed from event successfully!" }, statusCode: 201);
});
return group;
}
}

View File

@@ -1,26 +0,0 @@
using Microsoft.EntityFrameworkCore;
using WebApp.Data;
using WebApp.Mapping;
namespace WebApp.Endpoints;
public static class SkillsEndpoints
{
const string GetSkillEndpointName = "GetSkill";
public static RouteGroupBuilder MapSkillsEndpoints(this WebApplication app)
{
var group = app.MapGroup("api/skills").WithParameterValidation();
// GET /skills
group.MapGet("/",
async (ApplicationDbContext dbContext) =>
await dbContext.Skills
.OrderBy(Sk => Sk.SkillId)
.Select(Sk => Sk.ToSkillSummaryDto()) // SkillSummaryDto
.AsNoTracking()
.ToListAsync());
return group;
}
}

View File

@@ -0,0 +1,17 @@
using WebApp.DTOs;
using WebApp.Entities;
namespace WebApp.Mapping
{
public static class EventRegistrationMapping
{
public static EventRegistrationDto ToEventRegistrationDto(this EventRegistration er)
{
return new EventRegistrationDto(
er.EventId,
er.UserId,
er.RegisteredAt
);
}
}
}

View File

@@ -1,16 +0,0 @@
using WebApp.DTOs;
using WebApp.Entities;
namespace WebApp.Mapping;
public static class EventSkillMapping
{
public static EventSkill ToEventSkillEntity(this SingleSkillDto SSDto, int eid)
{
return new EventSkill()
{
EventId = eid,
SkillId = SSDto.Skill,
};
}
}

View File

@@ -1,16 +1,17 @@
using WebApp.DTOs;
using WebApp.DTOs;
using WebApp.Entities;
namespace WebApp.Mapping;
public static class VolunteerSkillMapping
namespace WebApp.Mapping
{
public static VolunteerSkill ToVolunteerSkillEntity(this SingleSkillDto SSDto, int uid)
public static class VolunteerSkillMapping
{
return new VolunteerSkill()
public static VolunteerSkill ToVolunteerSkillEntity(this SingleSkillDto SSDto, int uid)
{
UserId = uid,
SkillId = SSDto.Skill,
};
return new VolunteerSkill()
{
UserId = uid,
SkillId = SSDto.Skill,
};
}
}
}

View File

@@ -53,6 +53,6 @@ app.UseRouting(); // Enables routing to match incoming request to endpoints
app.MapEventsEndpoints();
app.MapOrganizationsEndpoints();
app.MapAuthEndpoints();
app.MapSkillsEndpoints();
app.MapEventsRegistrationEndpoints();
app.Run();

View File

@@ -1,4 +1,4 @@
<!DOCTYPE html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
@@ -68,16 +68,12 @@
<input type="password" id="password" class="form-control input-field" required />
</div>
<br />
<br/>
<button id="logInBtn" class="button" type="submit">
<span>Log in</span>
<span>&#11166;</span>
</button>
<button id="signUpBtn" class="button" type="button" onclick="alert('Coming soon!')">
<span>Sign up</span>
<span>&#11166;</span>
</button>
<p id="message" style="color: red;"></p>
</form>