forked from gongxuegit/tiku-backend.net
feat: add current user and tenant endpoints
This commit is contained in:
61
Tiku.Api/Controllers/TenantsController.cs
Normal file
61
Tiku.Api/Controllers/TenantsController.cs
Normal file
@@ -0,0 +1,61 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Text.Json;
|
||||
using Tiku.Application.Auth;
|
||||
using Tiku.Application.Security;
|
||||
using Tiku.Domain.Tenancy;
|
||||
using Tiku.Infrastructure.Persistence;
|
||||
|
||||
namespace Tiku.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Authorize(Policy = TikuPolicies.CurrentTenantMember)]
|
||||
[Route("api/tenants")]
|
||||
public sealed class TenantsController(
|
||||
ICurrentUser currentUser,
|
||||
ICurrentTenant currentTenant,
|
||||
TikuDbContext dbContext) : ControllerBase
|
||||
{
|
||||
[HttpGet("current")]
|
||||
public async Task<ActionResult<CurrentTenantResponse>> GetCurrent(CancellationToken cancellationToken)
|
||||
{
|
||||
if (currentUser.UserId is null || currentTenant.TenantId is null)
|
||||
{
|
||||
throw new TenantAccessDeniedException();
|
||||
}
|
||||
|
||||
var result = await dbContext.TenantMemberships
|
||||
.Where(membership =>
|
||||
membership.UserId == currentUser.UserId.Value &&
|
||||
membership.TenantId == currentTenant.TenantId.Value &&
|
||||
membership.Status == MembershipStatus.Active)
|
||||
.Join(
|
||||
dbContext.Tenants,
|
||||
membership => membership.TenantId,
|
||||
tenant => tenant.Id,
|
||||
(membership, tenant) => new CurrentTenantResponse(
|
||||
tenant.Id,
|
||||
tenant.Name,
|
||||
tenant.Slug,
|
||||
tenant.Status,
|
||||
membership.Role,
|
||||
membership.Permissions))
|
||||
.SingleOrDefaultAsync(cancellationToken);
|
||||
|
||||
if (result is null)
|
||||
{
|
||||
throw new TenantAccessDeniedException();
|
||||
}
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record CurrentTenantResponse(
|
||||
Guid TenantId,
|
||||
string TenantName,
|
||||
string TenantSlug,
|
||||
TenantStatus Status,
|
||||
TenantRole Role,
|
||||
JsonElement Permissions);
|
||||
Reference in New Issue
Block a user