/
EventsController.cs
195 lines (167 loc) · 7.19 KB
/
EventsController.cs
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
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Altinn.Platform.Events.Configuration;
using Altinn.Platform.Events.Extensions;
using Altinn.Platform.Events.Services.Interfaces;
using CloudNative.CloudEvents;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
namespace Altinn.Platform.Events.Controllers
{
/// <summary>
/// Controller for all events related operations
/// </summary>
[Authorize]
[Route("events/api/v1/events")]
[ApiController]
public class EventsController : ControllerBase
{
private readonly IEventsService _eventsService;
private readonly GeneralSettings _settings;
private readonly string _eventsBaseUri;
private readonly IAuthorization _authorizationService;
/// <summary>
/// Initializes a new instance of the <see cref="EventsController"/> class.
/// </summary>
public EventsController(
IEventsService events,
IAuthorization authorizationService,
IOptions<GeneralSettings> settings)
{
_eventsService = events;
_authorizationService = authorizationService;
_settings = settings.Value;
_eventsBaseUri = settings.Value.BaseUri;
}
/// <summary>
/// Endpoint for posting a new cloud event
/// </summary>
/// <param name="cloudEvent">The incoming cloud event</param>
/// <returns>The cloud event subject and id</returns>
[HttpPost]
[Authorize(Policy = AuthorizationConstants.POLICY_PUBLISH_SCOPE_OR_PLATFORM_ACCESS)]
[Consumes("application/cloudevents+json")]
public async Task<ActionResult<string>> Post([FromBody] CloudEvent cloudEvent)
{
if (!_settings.EnableExternalEvents)
{
return NotFound();
}
(bool isValid, string errorMessage) = ValidateCloudEvent(cloudEvent);
if (!isValid)
{
return Problem(errorMessage, null, 400);
}
bool isAuthorizedToPublish = await _authorizationService.AuthorizePublishEvent(cloudEvent);
if (!isAuthorizedToPublish)
{
return Forbid();
}
try
{
await _eventsService.RegisterNew(cloudEvent);
return Ok();
}
catch
{
return StatusCode(500, $"Unable to register cloud event.");
}
}
/// <summary>
/// Retrieves a set of events related based on query parameters.
/// </summary>
/// <param name="resource" example="urn:altinn:resource:app_ttd_apps-test">
/// Required resource attribute</param>
/// <param name="after" example="3fa85f64-5717-4562-b3fc-2c963f66afa6">Retrieve events that were registered after this event Id</param>
/// <param name="subject">Optional filter by subject. Only exact matches will be returned.</param>
/// <param name="alternativeSubject" example="/person/16035001577">Optional filter by extension attribute alternative subject. Only exact matches will be returned.</param>
/// <param name="type" example="["instance.created", "instance.process.completed"]">
/// Optional filter by event type. </param>
/// <param name="size">The maximum number of events to include in the response.</param>
[HttpGet]
[Authorize(Policy = AuthorizationConstants.POLICY_SCOPE_EVENTS_SUBSCRIBE)]
[Consumes("application/json")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[Produces("application/cloudevents+json")]
public async Task<ActionResult<List<CloudEvent>>> Get(
[FromQuery, Required] string resource,
[FromQuery] string after,
[FromQuery] string subject,
[FromHeader(Name = "Altinn-AlternativeSubject")] string alternativeSubject,
[FromQuery] List<string> type,
[FromQuery] int size = 50)
{
if (!_settings.EnableExternalEvents)
{
return NotFound();
}
// Maximum allowed result set size is adjusted silently.
size = size > 1000 ? 1000 : size;
(bool isValid, string errorMessage) = ValidateQueryParams(resource, after, size);
if (!isValid)
{
return Problem(errorMessage, null, 400);
}
List<CloudEvent> events = await _eventsService.GetEvents(resource, after, subject, alternativeSubject, type, size);
bool includeSubject = !string.IsNullOrEmpty(alternativeSubject) && string.IsNullOrEmpty(subject);
SetNextLink(events, includeSubject);
return events;
}
private static (bool IsValid, string ErrorMessage) ValidateQueryParams(string resource, string after, int size)
{
if (!resource.StartsWith("urn:altinn:resource:"))
{
return (false, "The 'resource' parameter must begin with `urn:altinn:resource:`");
}
if (string.IsNullOrEmpty(after))
{
return (false, "The 'after' parameter must be defined.");
}
if (size < 1)
{
return (false, "The 'size' parameter must be a number larger that 0.");
}
return (true, null);
}
private static (bool IsValid, string ErrorMessage) ValidateCloudEvent(CloudEvent cloudEvent)
{
string eventResource = cloudEvent["resource"]?.ToString();
if (string.IsNullOrEmpty(eventResource))
{
return (false, "A 'resource' property must be defined.");
}
if (!UriExtensions.IsValidUrn(eventResource))
{
return (false, "'Resource' must be a valid urn.");
}
return (true, null);
}
private void SetNextLink(List<CloudEvent> events, bool includeSubject = false)
{
if (events.Count > 0)
{
List<KeyValuePair<string, string>> queryCollection = HttpContext.Request.Query
.SelectMany(q => q.Value, (col, value) => new KeyValuePair<string, string>(col.Key, value))
.Where(q => q.Key != "after")
.ToList();
StringBuilder nextUriBuilder = new($"{_eventsBaseUri}{HttpContext.Request.Path}?after={events.Last().Id}");
foreach (KeyValuePair<string, string> queryParam in queryCollection)
{
nextUriBuilder.Append($"&{queryParam.Key}={queryParam.Value}");
}
if (includeSubject)
{
var subject = events.First().Subject;
nextUriBuilder.Append($"&subject={subject}");
}
Response.Headers["next"] = nextUriBuilder.ToString();
}
}
}
}