forked from nobodies-collective/Humans
-
Notifications
You must be signed in to change notification settings - Fork 2
Add notifications API endpoint for external consumers #211
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
peterdrier
wants to merge
2
commits into
main
Choose a base branch
from
sprint/2026-04-10/batch-4
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
139 changes: 139 additions & 0 deletions
139
src/Humans.Web/Controllers/NotificationApiController.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,139 @@ | ||
| using System.Security.Claims; | ||
| using Humans.Application.Interfaces; | ||
| using Humans.Infrastructure.Data; | ||
| using Humans.Web.Filters; | ||
| using Microsoft.AspNetCore.Authorization; | ||
| using Microsoft.AspNetCore.Mvc; | ||
| using Microsoft.EntityFrameworkCore; | ||
| using Microsoft.Extensions.Options; | ||
| using NodaTime; | ||
| using NodaTime.Text; | ||
|
|
||
| namespace Humans.Web.Controllers; | ||
|
|
||
| [ApiController] | ||
| [Route("api/notifications")] | ||
| [AllowAnonymous] | ||
| [ServiceFilter(typeof(NotificationApiKeyAuthFilter))] | ||
| public class NotificationApiController : ControllerBase | ||
| { | ||
| private readonly INotificationInboxService _inboxService; | ||
| private readonly INotificationMeterProvider _meterProvider; | ||
| private readonly HumansDbContext _dbContext; | ||
| private readonly IClock _clock; | ||
| private readonly NotificationApiSettings _settings; | ||
| private readonly ILogger<NotificationApiController> _logger; | ||
|
|
||
| public NotificationApiController( | ||
| INotificationInboxService inboxService, | ||
| INotificationMeterProvider meterProvider, | ||
| HumansDbContext dbContext, | ||
| IClock clock, | ||
| IOptions<NotificationApiSettings> settings, | ||
| ILogger<NotificationApiController> logger) | ||
| { | ||
| _inboxService = inboxService; | ||
| _meterProvider = meterProvider; | ||
| _dbContext = dbContext; | ||
| _clock = clock; | ||
| _settings = settings.Value; | ||
| _logger = logger; | ||
| } | ||
|
|
||
| [HttpGet] | ||
| public async Task<IActionResult> Get( | ||
| [FromQuery] string? since = null, | ||
| CancellationToken ct = default) | ||
| { | ||
| if (!Guid.TryParse(_settings.UserId, out var userId)) | ||
| { | ||
| _logger.LogError("NotificationApi:UserId is not configured or invalid"); | ||
| return StatusCode(503, new { error = "UserId not configured" }); | ||
| } | ||
|
|
||
| try | ||
| { | ||
| // Build inbox query — unread tab, no filter, no search | ||
| var inbox = await _inboxService.GetInboxAsync(userId, search: null, filter: "", tab: "unread", ct); | ||
|
|
||
| var notifications = inbox.NeedsAttention | ||
| .Concat(inbox.Informational) | ||
| .AsEnumerable(); | ||
|
|
||
| // Apply since filter if provided | ||
| if (since is not null) | ||
| { | ||
| var parseResult = LocalDatePattern.Iso.Parse(since); | ||
| if (!parseResult.Success) | ||
| { | ||
| return BadRequest(new { error = "Invalid 'since' format. Use yyyy-MM-dd." }); | ||
| } | ||
|
|
||
| var sinceInstant = parseResult.Value.AtStartOfDayInZone(DateTimeZone.Utc).ToInstant(); | ||
| var sinceUtc = sinceInstant.ToDateTimeUtc(); | ||
| notifications = notifications.Where(n => n.CreatedAt >= sinceUtc); | ||
| } | ||
|
|
||
| var notificationList = notifications.Select(n => new | ||
| { | ||
| Date = n.CreatedAt, | ||
| Source = n.Source.ToString(), | ||
| Subject = n.Title, | ||
| Link = n.ActionUrl, | ||
| Priority = n.Priority.ToString().ToLowerInvariant(), | ||
| Class = n.Class.ToString().ToLowerInvariant(), | ||
| Unread = !n.IsRead, | ||
| }).ToList(); | ||
|
|
||
| // Build meters using a ClaimsPrincipal for the configured user | ||
| var principal = await BuildClaimsPrincipalAsync(userId, ct); | ||
| var meters = await _meterProvider.GetMetersForUserAsync(principal, ct); | ||
|
|
||
| var meterList = meters.Select(m => new | ||
| { | ||
| Label = m.Title, | ||
| m.Count, | ||
| Link = m.ActionUrl, | ||
| }).ToList(); | ||
|
|
||
| return Ok(new | ||
| { | ||
| Notifications = notificationList, | ||
| Meters = meterList, | ||
| }); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| _logger.LogError(ex, "Failed to retrieve notifications for API"); | ||
| return StatusCode(500, new { error = "Failed to retrieve notifications" }); | ||
| } | ||
| } | ||
|
|
||
| private async Task<ClaimsPrincipal> BuildClaimsPrincipalAsync(Guid userId, CancellationToken ct) | ||
| { | ||
| var now = _clock.GetCurrentInstant(); | ||
|
|
||
| var roles = await _dbContext.RoleAssignments | ||
| .AsNoTracking() | ||
| .Where(ra => | ||
| ra.UserId == userId && | ||
| ra.ValidFrom <= now && | ||
| (ra.ValidTo == null || ra.ValidTo > now)) | ||
| .Select(ra => ra.RoleName) | ||
| .Distinct() | ||
| .ToListAsync(ct); | ||
|
|
||
| var claims = new List<Claim> | ||
| { | ||
| new(ClaimTypes.NameIdentifier, userId.ToString()), | ||
| }; | ||
|
|
||
| foreach (var role in roles) | ||
| { | ||
| claims.Add(new Claim(ClaimTypes.Role, role)); | ||
| } | ||
|
|
||
| var identity = new ClaimsIdentity(claims, "ApiKey"); | ||
| return new ClaimsPrincipal(identity); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This controller is missing
[AllowAnonymous], so requests with a validX-Api-Keycan still be redirected by the globalMembershipRequiredFilterwhen the caller also has an authenticated but non-active-member cookie. InProgram.cs, that filter is applied globally, and inMembershipRequiredFilterauthenticated users are redirected unless the action/controller is anonymous; as written,/api/notificationscan return a 302 HTML redirect instead of the JSON API response depending on caller session state.Useful? React with 👍 / 👎.