Adds messages api
This commit is contained in:
@@ -10,6 +10,7 @@
|
|||||||
<PackageVersion Include="Azure.Identity" Version="1.11.0" />
|
<PackageVersion Include="Azure.Identity" Version="1.11.0" />
|
||||||
<PackageVersion Include="Azure.Storage.Blobs" Version="12.20.0" />
|
<PackageVersion Include="Azure.Storage.Blobs" Version="12.20.0" />
|
||||||
<PackageVersion Include="coverlet.collector" Version="6.0.0" />
|
<PackageVersion Include="coverlet.collector" Version="6.0.0" />
|
||||||
|
<PackageVersion Include="FastEndpoints" Version="5.26.0" />
|
||||||
<PackageVersion Include="FluentAssertions" Version="6.12.0" />
|
<PackageVersion Include="FluentAssertions" Version="6.12.0" />
|
||||||
<PackageVersion Include="FluentValidation.AspNetCore" Version="11.3.0" />
|
<PackageVersion Include="FluentValidation.AspNetCore" Version="11.3.0" />
|
||||||
<PackageVersion Include="FluentValidation.DependencyInjectionExtensions" Version="11.8.1" />
|
<PackageVersion Include="FluentValidation.DependencyInjectionExtensions" Version="11.8.1" />
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
namespace Hutopy.Application.Common.Models;
|
namespace Hutopy.Application.Common.Models;
|
||||||
|
|
||||||
|
// TODO: Review nullable affectation here
|
||||||
public class UserModel
|
public class UserModel
|
||||||
{
|
{
|
||||||
public string? Id { get; set; }
|
public string? Id { get; set; }
|
||||||
@@ -7,4 +8,5 @@ public class UserModel
|
|||||||
public string? FirstName { get; set; }
|
public string? FirstName { get; set; }
|
||||||
public string? LastName { get; set; }
|
public string? LastName { get; set; }
|
||||||
public string? Email { get; set; }
|
public string? Email { get; set; }
|
||||||
|
public string? PortraitUrl { get; set; }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using System.Diagnostics;
|
||||||
using Google.Apis.Oauth2.v2.Data;
|
using Google.Apis.Oauth2.v2.Data;
|
||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
using Hutopy.Application.Common.Interfaces;
|
using Hutopy.Application.Common.Interfaces;
|
||||||
@@ -221,13 +222,19 @@ public class IdentityService(
|
|||||||
|
|
||||||
var user = await GetUserByUserNameAsync(userName);
|
var user = await GetUserByUserNameAsync(userName);
|
||||||
|
|
||||||
|
if (user is null) throw new InvalidOperationException();
|
||||||
|
|
||||||
var jwtSection = configuration.GetRequiredSection("Authentication:Jwt");
|
var jwtSection = configuration.GetRequiredSection("Authentication:Jwt");
|
||||||
|
|
||||||
var token = JwtTokenHelper.GenerateJwtToken(
|
var token = JwtTokenHelper.GenerateJwtToken(
|
||||||
issuer: jwtSection["Issuer"] ?? "",
|
issuer: jwtSection["Issuer"] ?? "",
|
||||||
audience: jwtSection["Audience"] ?? "",
|
audience: jwtSection["Audience"] ?? "",
|
||||||
key: jwtSection["Key"] ?? "",
|
key: jwtSection["Key"] ?? "",
|
||||||
userId: user?.Id ?? "");
|
userId: user.Id,
|
||||||
|
email: user.Email,
|
||||||
|
firstname: user.FirstName,
|
||||||
|
lastname: user.LastName,
|
||||||
|
portraitUrl: user.PortraitUrl);
|
||||||
|
|
||||||
return token;
|
return token;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,20 +7,31 @@ namespace Hutopy.Infrastructure.Utils;
|
|||||||
|
|
||||||
public static class JwtTokenHelper
|
public static class JwtTokenHelper
|
||||||
{
|
{
|
||||||
public static string GenerateJwtToken(string issuer, string audience, string key, string userId)
|
public static string GenerateJwtToken(string issuer, string audience, string key, string? userId, string? email,
|
||||||
|
string? firstname, string? lastname, string? portraitUrl)
|
||||||
{
|
{
|
||||||
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
|
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
|
||||||
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
|
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
|
||||||
|
|
||||||
var token = new JwtSecurityToken(
|
var claims = new List<Claim>(new[]
|
||||||
issuer: issuer,
|
|
||||||
audience: audience,
|
|
||||||
claims: new[]
|
|
||||||
{
|
{
|
||||||
new Claim(JwtRegisteredClaimNames.Sub, userId),
|
new Claim(JwtRegisteredClaimNames.Sub, userId),
|
||||||
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
|
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
|
||||||
new Claim(ClaimTypes.NameIdentifier, userId)
|
new Claim(ClaimTypes.NameIdentifier, userId),
|
||||||
},
|
new Claim(ClaimTypes.Email, email),
|
||||||
|
new Claim(ClaimTypes.GivenName, firstname),
|
||||||
|
new Claim(ClaimTypes.Surname, lastname),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (portraitUrl is not null)
|
||||||
|
{
|
||||||
|
claims.Add(new Claim("portrait-url", portraitUrl));
|
||||||
|
}
|
||||||
|
|
||||||
|
var token = new JwtSecurityToken(
|
||||||
|
issuer: issuer,
|
||||||
|
audience: audience,
|
||||||
|
claims: claims,
|
||||||
expires: DateTime.Now.AddMinutes(30),
|
expires: DateTime.Now.AddMinutes(30),
|
||||||
signingCredentials: credentials);
|
signingCredentials: credentials);
|
||||||
|
|
||||||
|
|||||||
@@ -64,10 +64,14 @@ public class GoogleController(IIdentityService identityService, IHttpClientFacto
|
|||||||
var jwtSection = configuration.GetRequiredSection("Authentication:Jwt");
|
var jwtSection = configuration.GetRequiredSection("Authentication:Jwt");
|
||||||
|
|
||||||
var token = JwtTokenHelper.GenerateJwtToken(
|
var token = JwtTokenHelper.GenerateJwtToken(
|
||||||
issuer: jwtSection["Issuer"] ?? throw new ArgumentNullException("The Jwt issuer is missing."),
|
jwtSection["Issuer"] ?? throw new ArgumentNullException("The Jwt issuer is missing."),
|
||||||
audience: jwtSection["Audience"] ?? throw new ArgumentNullException("The Jwt audience is missing."),
|
jwtSection["Audience"] ?? throw new ArgumentNullException("The Jwt audience is missing."),
|
||||||
key: jwtSection["Key"] ?? throw new ArgumentNullException("The Jwt key is missing."),
|
jwtSection["Key"] ?? throw new ArgumentNullException("The Jwt key is missing."),
|
||||||
userId: user.Id);
|
user.Id,
|
||||||
|
user.Email,
|
||||||
|
user.FirstName,
|
||||||
|
user.LastName,
|
||||||
|
user.PortraitUrl);
|
||||||
|
|
||||||
return Ok(new { accessToken = token, email });
|
return Ok(new { accessToken = token, email });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,10 +31,8 @@ public class Users : EndpointGroupBase
|
|||||||
|
|
||||||
private static async Task<string> UploadProfilePicture(ISender sender, Stream stream)
|
private static async Task<string> UploadProfilePicture(ISender sender, Stream stream)
|
||||||
{
|
{
|
||||||
var command = new UploadProfilePictureCommand
|
var command = new UploadProfilePictureCommand { ProfilePicture = stream };
|
||||||
{
|
|
||||||
ProfilePicture = stream
|
|
||||||
};
|
|
||||||
return await sender.Send(command);
|
return await sender.Send(command);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
13
src/Web/Messages/Data/Message.cs
Normal file
13
src/Web/Messages/Data/Message.cs
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
namespace Hutopy.Web.Messages.Data;
|
||||||
|
|
||||||
|
public class Message
|
||||||
|
{
|
||||||
|
public Guid Id { get; init; }
|
||||||
|
public Guid ContentId { get; init; } // works for any - VideoId, ChatId, RoomId, xxxId, ForumId
|
||||||
|
public Guid CreatedBy { get; init; }
|
||||||
|
public DateTime CreatedAt { get; }
|
||||||
|
|
||||||
|
public Guid ParentId { get; init; }
|
||||||
|
|
||||||
|
public string Value { get; init; } = null!;
|
||||||
|
}
|
||||||
19
src/Web/Messages/Data/MessagingDbContext.cs
Normal file
19
src/Web/Messages/Data/MessagingDbContext.cs
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace Hutopy.Web.Messages.Data;
|
||||||
|
|
||||||
|
public class MessagingDbContext(
|
||||||
|
DbContextOptions<MessagingDbContext> options)
|
||||||
|
: DbContext(options)
|
||||||
|
{
|
||||||
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||||
|
{
|
||||||
|
modelBuilder
|
||||||
|
.Entity<Message>()
|
||||||
|
.Property(c => c.CreatedAt)
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasDefaultValueSql("CURRENT_TIMESTAMP");
|
||||||
|
}
|
||||||
|
|
||||||
|
public DbSet<Message> Messages { get; set; }
|
||||||
|
}
|
||||||
30
src/Web/Messages/Handlers/GetMessages.cs
Normal file
30
src/Web/Messages/Handlers/GetMessages.cs
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
using FastEndpoints;
|
||||||
|
using Hutopy.Web.Messages.Data;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace Hutopy.Web.Messages.Handlers;
|
||||||
|
|
||||||
|
public class GetMessages(
|
||||||
|
MessagingDbContext context)
|
||||||
|
: EndpointWithoutRequest<List<Message>>
|
||||||
|
{
|
||||||
|
public override void Configure()
|
||||||
|
{
|
||||||
|
Tags("Messages");
|
||||||
|
Get("/api/messages/{ContentId:guid}");
|
||||||
|
AllowAnonymous();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override async Task HandleAsync(
|
||||||
|
CancellationToken ct)
|
||||||
|
{
|
||||||
|
var contentId = Route<Guid>("ContentId");
|
||||||
|
|
||||||
|
var comments = await context
|
||||||
|
.Messages
|
||||||
|
.Where(c => c.ContentId == contentId)
|
||||||
|
.ToListAsync(cancellationToken: ct);
|
||||||
|
|
||||||
|
await SendAsync(comments, cancellation: ct);
|
||||||
|
}
|
||||||
|
}
|
||||||
33
src/Web/Messages/Handlers/GetMessagesByUser.cs
Normal file
33
src/Web/Messages/Handlers/GetMessagesByUser.cs
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
using FastEndpoints;
|
||||||
|
using Hutopy.Web.Messages.Data;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace Hutopy.Web.Messages.Handlers;
|
||||||
|
|
||||||
|
public record GetMessagesByUserRequest(
|
||||||
|
[FromRoute] Guid UserId);
|
||||||
|
|
||||||
|
public class GetMessagesByUser(
|
||||||
|
MessagingDbContext context)
|
||||||
|
: EndpointWithoutRequest<List<Message>>
|
||||||
|
{
|
||||||
|
public override void Configure()
|
||||||
|
{
|
||||||
|
Tags("Messages");
|
||||||
|
Get("/api/messages/by-user/{UserId:guid}");
|
||||||
|
}
|
||||||
|
|
||||||
|
public override async Task HandleAsync(
|
||||||
|
CancellationToken ct)
|
||||||
|
{
|
||||||
|
var userId = Route<Guid>("UserId");
|
||||||
|
|
||||||
|
var posts = await context
|
||||||
|
.Messages
|
||||||
|
.Where(c => c.CreatedBy == userId)
|
||||||
|
.ToListAsync(cancellationToken: ct);
|
||||||
|
|
||||||
|
await SendAsync(posts, cancellation: ct);
|
||||||
|
}
|
||||||
|
}
|
||||||
34
src/Web/Messages/Handlers/PostMessage.cs
Normal file
34
src/Web/Messages/Handlers/PostMessage.cs
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
using FastEndpoints;
|
||||||
|
using Hutopy.Web.Messages.Data;
|
||||||
|
|
||||||
|
namespace Hutopy.Web.Messages.Handlers;
|
||||||
|
|
||||||
|
public record PostMessageRequest(
|
||||||
|
Guid ContentId,
|
||||||
|
string Message);
|
||||||
|
|
||||||
|
public class PostMessage(
|
||||||
|
MessagingDbContext context)
|
||||||
|
: Endpoint<PostMessageRequest>
|
||||||
|
{
|
||||||
|
public override void Configure()
|
||||||
|
{
|
||||||
|
// TODO: Find how to specify the name we see in Swagger
|
||||||
|
Tags("Messages");
|
||||||
|
Post("/api/messages");
|
||||||
|
}
|
||||||
|
|
||||||
|
public override async Task HandleAsync(
|
||||||
|
PostMessageRequest req,
|
||||||
|
CancellationToken ct)
|
||||||
|
{
|
||||||
|
await context.Messages.AddAsync(
|
||||||
|
new Message {
|
||||||
|
ContentId = req.ContentId,
|
||||||
|
CreatedBy = User.GetUserId(),
|
||||||
|
Value = req.Message },
|
||||||
|
ct);
|
||||||
|
|
||||||
|
await context.SaveChangesAsync(ct);
|
||||||
|
}
|
||||||
|
}
|
||||||
37
src/Web/Messages/Handlers/PostReplyMessage.cs
Normal file
37
src/Web/Messages/Handlers/PostReplyMessage.cs
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
using FastEndpoints;
|
||||||
|
using Hutopy.Web.Messages.Data;
|
||||||
|
|
||||||
|
namespace Hutopy.Web.Messages.Handlers;
|
||||||
|
|
||||||
|
public record PostReplyMessageRequest(
|
||||||
|
Guid ContentId,
|
||||||
|
Guid ParentId,
|
||||||
|
string Message);
|
||||||
|
|
||||||
|
public sealed class PostReplyMessage(
|
||||||
|
MessagingDbContext context)
|
||||||
|
: Endpoint<PostReplyMessageRequest>
|
||||||
|
{
|
||||||
|
public override void Configure()
|
||||||
|
{
|
||||||
|
Tags("Messages");
|
||||||
|
Post("/api/messages/reply");
|
||||||
|
}
|
||||||
|
|
||||||
|
public override async Task HandleAsync(
|
||||||
|
PostReplyMessageRequest req,
|
||||||
|
CancellationToken ct)
|
||||||
|
{
|
||||||
|
await context.Messages.AddAsync(
|
||||||
|
new Message
|
||||||
|
{
|
||||||
|
ContentId = req.ContentId,
|
||||||
|
ParentId = req.ParentId,
|
||||||
|
CreatedBy = User.GetUserId(),
|
||||||
|
Value = req.Message
|
||||||
|
},
|
||||||
|
ct);
|
||||||
|
|
||||||
|
await context.SaveChangesAsync(ct);
|
||||||
|
}
|
||||||
|
}
|
||||||
59
src/Web/Messages/Migrations/20240627081653_Initial.Designer.cs
generated
Normal file
59
src/Web/Messages/Migrations/20240627081653_Initial.Designer.cs
generated
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
// <auto-generated />
|
||||||
|
using System;
|
||||||
|
using Hutopy.Web.Messages.Data;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||||
|
using Microsoft.EntityFrameworkCore.Metadata;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Hutopy.Web.Messages.Migrations
|
||||||
|
{
|
||||||
|
[DbContext(typeof(MessagingDbContext))]
|
||||||
|
[Migration("20240627081653_Initial")]
|
||||||
|
partial class Initial
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||||
|
{
|
||||||
|
#pragma warning disable 612, 618
|
||||||
|
modelBuilder
|
||||||
|
.HasAnnotation("ProductVersion", "8.0.3")
|
||||||
|
.HasAnnotation("Relational:MaxIdentifierLength", 128);
|
||||||
|
|
||||||
|
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
|
||||||
|
|
||||||
|
modelBuilder.Entity("Hutopy.Web.Messages.Data.Message", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("uniqueidentifier");
|
||||||
|
|
||||||
|
b.Property<Guid>("ContentId")
|
||||||
|
.HasColumnType("uniqueidentifier");
|
||||||
|
|
||||||
|
b.Property<DateTime>("CreatedAt")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("datetime2")
|
||||||
|
.HasDefaultValueSql("CURRENT_TIMESTAMP");
|
||||||
|
|
||||||
|
b.Property<Guid>("CreatedBy")
|
||||||
|
.HasColumnType("uniqueidentifier");
|
||||||
|
|
||||||
|
b.Property<Guid>("ParentId")
|
||||||
|
.HasColumnType("uniqueidentifier");
|
||||||
|
|
||||||
|
b.Property<string>("Value")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("nvarchar(max)");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.ToTable("Messages");
|
||||||
|
});
|
||||||
|
#pragma warning restore 612, 618
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
38
src/Web/Messages/Migrations/20240627081653_Initial.cs
Normal file
38
src/Web/Messages/Migrations/20240627081653_Initial.cs
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
using System;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Hutopy.Web.Messages.Migrations
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class Initial : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "Messages",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
|
||||||
|
ContentId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
|
||||||
|
CreatedBy = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
|
||||||
|
CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP"),
|
||||||
|
ParentId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
|
||||||
|
Value = table.Column<string>(type: "nvarchar(max)", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_Messages", x => x.Id);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "Messages");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
// <auto-generated />
|
||||||
|
using System;
|
||||||
|
using Hutopy.Web.Messages.Data;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||||
|
using Microsoft.EntityFrameworkCore.Metadata;
|
||||||
|
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Hutopy.Web.Messages.Migrations
|
||||||
|
{
|
||||||
|
[DbContext(typeof(MessagingDbContext))]
|
||||||
|
partial class MessagingDbContextModelSnapshot : ModelSnapshot
|
||||||
|
{
|
||||||
|
protected override void BuildModel(ModelBuilder modelBuilder)
|
||||||
|
{
|
||||||
|
#pragma warning disable 612, 618
|
||||||
|
modelBuilder
|
||||||
|
.HasAnnotation("ProductVersion", "8.0.3")
|
||||||
|
.HasAnnotation("Relational:MaxIdentifierLength", 128);
|
||||||
|
|
||||||
|
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
|
||||||
|
|
||||||
|
modelBuilder.Entity("Hutopy.Web.Messages.Data.Message", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("uniqueidentifier");
|
||||||
|
|
||||||
|
b.Property<Guid>("ContentId")
|
||||||
|
.HasColumnType("uniqueidentifier");
|
||||||
|
|
||||||
|
b.Property<DateTime>("CreatedAt")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("datetime2")
|
||||||
|
.HasDefaultValueSql("CURRENT_TIMESTAMP");
|
||||||
|
|
||||||
|
b.Property<Guid>("CreatedBy")
|
||||||
|
.HasColumnType("uniqueidentifier");
|
||||||
|
|
||||||
|
b.Property<Guid>("ParentId")
|
||||||
|
.HasColumnType("uniqueidentifier");
|
||||||
|
|
||||||
|
b.Property<string>("Value")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("nvarchar(max)");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.ToTable("Messages");
|
||||||
|
});
|
||||||
|
#pragma warning restore 612, 618
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
42
src/Web/Messages/Shared.cs
Normal file
42
src/Web/Messages/Shared.cs
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
using System.Security.Claims;
|
||||||
|
|
||||||
|
namespace Hutopy.Web.Messages;
|
||||||
|
|
||||||
|
public class Shared(string claimName) : Exception;
|
||||||
|
|
||||||
|
public static class ClaimsPrincipalExtensions
|
||||||
|
{
|
||||||
|
public static Guid GetUserId(this ClaimsPrincipal claims)
|
||||||
|
{
|
||||||
|
return (Guid)claims.GetFirstValue<Guid>(ClaimTypes.NameIdentifier);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string GetFirstName(this ClaimsPrincipal claims)
|
||||||
|
{
|
||||||
|
return (string)claims.GetFirstValue<string>(ClaimTypes.GivenName);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string GetLastName(this ClaimsPrincipal claims)
|
||||||
|
{
|
||||||
|
return (string)claims.GetFirstValue<string>(ClaimTypes.Surname);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string GetEmail(this ClaimsPrincipal claims)
|
||||||
|
{
|
||||||
|
return (string)claims.GetFirstValue<string>(ClaimTypes.Email);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static object GetFirstValue<TValue>(this ClaimsPrincipal claims, string key)
|
||||||
|
{
|
||||||
|
var claim = claims.FindFirst(key);
|
||||||
|
|
||||||
|
if (claim is null) throw new Shared(key);
|
||||||
|
|
||||||
|
if (typeof(TValue) == typeof(Guid))
|
||||||
|
{
|
||||||
|
return Guid.Parse(claim.Value);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Convert.ChangeType(claim.Value, typeof(TValue));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,10 +1,14 @@
|
|||||||
|
using Azure.Identity;
|
||||||
|
using FastEndpoints;
|
||||||
using Hutopy.Application;
|
using Hutopy.Application;
|
||||||
using Hutopy.Infrastructure;
|
using Hutopy.Infrastructure;
|
||||||
using Hutopy.Infrastructure.Data;
|
using Hutopy.Infrastructure.Data;
|
||||||
using Hutopy.Web;
|
using Hutopy.Web;
|
||||||
using Azure.Identity;
|
using Hutopy.Web.Messages.Data;
|
||||||
using Microsoft.AspNetCore.HttpOverrides;
|
using Microsoft.AspNetCore.HttpOverrides;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
using NSwag;
|
using NSwag;
|
||||||
|
using NSwag.Generation.AspNetCore.Processors;
|
||||||
using NSwag.Generation.Processors.Security;
|
using NSwag.Generation.Processors.Security;
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
@@ -48,6 +52,8 @@ builder.Services.AddApplicationServices();
|
|||||||
builder.Services.AddInfrastructureServices(builder.Configuration);
|
builder.Services.AddInfrastructureServices(builder.Configuration);
|
||||||
builder.Services.AddWebServices();
|
builder.Services.AddWebServices();
|
||||||
builder.Services.AddAuthorizationAndAuthentication(builder.Configuration);
|
builder.Services.AddAuthorizationAndAuthentication(builder.Configuration);
|
||||||
|
|
||||||
|
// TODO: This old tech should be remove - need to move Facebook / Google controllers to FastEndpoints
|
||||||
builder.Services.AddControllers();
|
builder.Services.AddControllers();
|
||||||
|
|
||||||
builder.Services.AddOpenApiDocument((configure, sp) =>
|
builder.Services.AddOpenApiDocument((configure, sp) =>
|
||||||
@@ -63,12 +69,20 @@ builder.Services.AddOpenApiDocument((configure, sp) =>
|
|||||||
Type = OpenApiSecuritySchemeType.ApiKey,
|
Type = OpenApiSecuritySchemeType.ApiKey,
|
||||||
Name = "Authorization",
|
Name = "Authorization",
|
||||||
In = OpenApiSecurityApiKeyLocation.Header,
|
In = OpenApiSecurityApiKeyLocation.Header,
|
||||||
Description = "Type into the textbox: Bearer {your JWT token}."
|
Description = "Type into the textbox: Bearer {your JWT token}.",
|
||||||
});
|
});
|
||||||
|
|
||||||
|
configure.OperationProcessors.Add(new AspNetCoreOperationTagsProcessor());
|
||||||
configure.OperationProcessors.Add(new AspNetCoreOperationSecurityScopeProcessor("JWT"));
|
configure.OperationProcessors.Add(new AspNetCoreOperationSecurityScopeProcessor("JWT"));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
builder.Services.AddFastEndpoints();
|
||||||
|
|
||||||
|
builder.Services.AddDbContext<MessagingDbContext>((_, options) =>
|
||||||
|
{
|
||||||
|
options.UseSqlServer(builder.Configuration.GetConnectionString("CommentStore"));
|
||||||
|
});
|
||||||
|
|
||||||
var app = builder.Build();
|
var app = builder.Build();
|
||||||
|
|
||||||
app.UseForwardedHeaders(
|
app.UseForwardedHeaders(
|
||||||
@@ -110,6 +124,13 @@ app.MapControllerRoute(
|
|||||||
// app.UseExceptionHandler();
|
// app.UseExceptionHandler();
|
||||||
app.MapEndpoints();
|
app.MapEndpoints();
|
||||||
|
|
||||||
|
app.UseFastEndpoints();
|
||||||
|
|
||||||
app.Run();
|
app.Run();
|
||||||
|
|
||||||
public abstract partial class Program { }
|
namespace Hutopy.Web
|
||||||
|
{
|
||||||
|
public abstract partial class Program
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -14,6 +14,7 @@
|
|||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Azure.Extensions.AspNetCore.Configuration.Secrets" />
|
<PackageReference Include="Azure.Extensions.AspNetCore.Configuration.Secrets" />
|
||||||
<PackageReference Include="Azure.Identity" />
|
<PackageReference Include="Azure.Identity" />
|
||||||
|
<PackageReference Include="FastEndpoints" />
|
||||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.Facebook" />
|
<PackageReference Include="Microsoft.AspNetCore.Authentication.Facebook" />
|
||||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.Google" />
|
<PackageReference Include="Microsoft.AspNetCore.Authentication.Google" />
|
||||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
|
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
|
||||||
@@ -29,4 +30,8 @@
|
|||||||
<PackageReference Include="FluentValidation.AspNetCore" />
|
<PackageReference Include="FluentValidation.AspNetCore" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Folder Include="Messages\Migrations\" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ Content-Type: application/json
|
|||||||
"password": "{{Password}}"
|
"password": "{{Password}}"
|
||||||
}
|
}
|
||||||
|
|
||||||
> {% client.global.set("auth_token", response.body); %}
|
> {% client.global.set("auth_token", response.body.accessToken); %}
|
||||||
|
|
||||||
###
|
###
|
||||||
|
|
||||||
@@ -47,3 +47,15 @@ Authorization: Bearer {{auth_token}}
|
|||||||
# GET GetMyUser
|
# GET GetMyUser
|
||||||
GET {{base_url}}/api/GetMyUser
|
GET {{base_url}}/api/GetMyUser
|
||||||
Authorization: Bearer {{auth_token}}
|
Authorization: Bearer {{auth_token}}
|
||||||
|
|
||||||
|
###
|
||||||
|
|
||||||
|
# GET /api/posts
|
||||||
|
|
||||||
|
GET {{base_url}}/api/messages/00000001-0000-0000-0000-000000000001
|
||||||
|
|
||||||
|
###
|
||||||
|
|
||||||
|
# GET /api/posts/by-user
|
||||||
|
GET {{base_url}}/api/messages/by-user/325C69E8-DBC4-4CEE-B56E-C3C90AEE7963
|
||||||
|
Authorization: Bearer {{auth_token}}
|
||||||
@@ -8,7 +8,8 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"ConnectionStrings": {
|
"ConnectionStrings": {
|
||||||
"DefaultConnection": "Server=localhost,1433;Initial Catalog=Hutopy;User Id=sa;Password=P@ssword123!;MultipleActiveResultSets=true;TrustServerCertificate=True;MultiSubnetFailover=True"
|
"DefaultConnection": "Server=localhost,1433;Initial Catalog=Hutopy;User Id=sa;Password=P@ssword123!;MultipleActiveResultSets=true;TrustServerCertificate=True;MultiSubnetFailover=True",
|
||||||
|
"CommentStore": "Server=localhost,1433;Initial Catalog=Hutopy;User Id=sa;Password=P@ssword123!;MultipleActiveResultSets=true;TrustServerCertificate=True;MultiSubnetFailover=True"
|
||||||
},
|
},
|
||||||
"Authentication": {
|
"Authentication": {
|
||||||
"Jwt": {
|
"Jwt": {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
using System.Data.Common;
|
using System.Data.Common;
|
||||||
using Hutopy.Application.Common.Interfaces;
|
using Hutopy.Application.Common.Interfaces;
|
||||||
using Hutopy.Infrastructure.Data;
|
using Hutopy.Infrastructure.Data;
|
||||||
|
using Hutopy.Web;
|
||||||
using Microsoft.AspNetCore.Hosting;
|
using Microsoft.AspNetCore.Hosting;
|
||||||
using Microsoft.AspNetCore.Mvc.Testing;
|
using Microsoft.AspNetCore.Mvc.Testing;
|
||||||
using Microsoft.AspNetCore.TestHost;
|
using Microsoft.AspNetCore.TestHost;
|
||||||
|
|||||||
Reference in New Issue
Block a user