-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathAASXFileServerAPIApi.cs
299 lines (263 loc) · 14.9 KB
/
AASXFileServerAPIApi.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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
/*
* DotAAS Part 2 | HTTP/REST | AASX File Server Service Specification
*
* The File Server Service Specification as part of the [Specification of the Asset Administration Shell: Part 2](http://industrialdigitaltwin.org/en/content-hub). Publisher: Industrial Digital Twin Association (IDTA) 2023
*
* OpenAPI spec version: V3.0.1_SSP-001
* Contact: info@idtwin.org
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using AasSecurity.Exceptions;
using AasxServerStandardBib.Interfaces;
using AasxServerStandardBib.Logging;
using IO.Swagger.Attributes;
using IO.Swagger.Lib.V3.Interfaces;
using IO.Swagger.Lib.V3.Models;
using IO.Swagger.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations;
using System;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Net.Mime;
namespace IO.Swagger.Controllers;
using System.Threading.Tasks;
/// <summary>
///
/// </summary>
[Authorize(AuthenticationSchemes = "AasSecurityAuth")]
[ApiController]
public class AASXFileServerAPIApiController : ControllerBase
{
private readonly IAppLogger<AASXFileServerAPIApiController> _logger;
private readonly IBase64UrlDecoderService _decoderService;
private readonly IAasxFileServerInterfaceService _fileService;
private readonly IPaginationService _paginationService;
private readonly IAuthorizationService _authorizationService;
public AASXFileServerAPIApiController(IAppLogger<AASXFileServerAPIApiController> logger, IBase64UrlDecoderService decoderService,
IAasxFileServerInterfaceService fileService, IPaginationService paginationService, IAuthorizationService authorizationService)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_decoderService = decoderService ?? throw new ArgumentNullException(nameof(decoderService));
_fileService = fileService ?? throw new ArgumentNullException(nameof(fileService));
_paginationService = paginationService ?? throw new ArgumentNullException(nameof(paginationService));
_authorizationService = authorizationService ?? throw new ArgumentNullException(nameof(authorizationService));
}
/// <summary>
/// Deletes a specific AASX package from the server
/// </summary>
/// <param name="packageId">The package Id (UTF8-BASE64-URL-encoded)</param>
/// <response code="204">Deleted successfully</response>
/// <response code="400">Bad Request, e.g. the request parameters of the format of the request body is wrong.</response>
/// <response code="401">Unauthorized, e.g. the server refused the authorization attempt.</response>
/// <response code="403">Forbidden</response>
/// <response code="404">Not Found</response>
/// <response code="500">Internal Server Error</response>
/// <response code="0">Default error handling for unmentioned status codes</response>
[HttpDelete]
[Route("/packages/{packageId}")]
[ValidateModelState]
[SwaggerOperation("DeleteAASXByPackageId")]
[SwaggerResponse(statusCode: 400, type: typeof(Result), description: "Bad Request, e.g. the request parameters of the format of the request body is wrong.")]
[SwaggerResponse(statusCode: 401, type: typeof(Result), description: "Unauthorized, e.g. the server refused the authorization attempt.")]
[SwaggerResponse(statusCode: 403, type: typeof(Result), description: "Forbidden")]
[SwaggerResponse(statusCode: 404, type: typeof(Result), description: "Not Found")]
[SwaggerResponse(statusCode: 500, type: typeof(Result), description: "Internal Server Error")]
[SwaggerResponse(statusCode: 0, type: typeof(Result), description: "Default error handling for unmentioned status codes")]
public virtual IActionResult DeleteAASXByPackageId([FromRoute] [Required] string packageId)
{
var decodedPackageId = _decoderService.Decode("packageId", packageId);
_logger.LogInformation($"Received request to delete the AASX Package with package id {decodedPackageId}");
var aas = _fileService.GetAssetAdministrationShellByPackageId(decodedPackageId);
var authResult = _authorizationService.AuthorizeAsync(User, aas, "SecurityPolicy").Result;
if (!authResult.Succeeded)
{
var failedReasons = authResult.Failure.FailureReasons;
var authorizationFailureReasons = failedReasons.ToList();
if (authorizationFailureReasons.Count != 0)
{
throw new NotAllowed(authorizationFailureReasons.First().Message); // TODO (jtikekar, 2023-09-04): write AuthResultMiddlewareHandler
}
if (HttpContext.Response.StatusCode == 307)
{
var url = HttpContext.Response.Headers["redirectInfo"].First();
return new RedirectResult(url ?? string.Empty);
}
}
_fileService.DeleteAASXByPackageId(decodedPackageId);
return NoContent();
}
/// <summary>
/// Returns a specific AASX package from the server
/// </summary>
/// <param name="packageId">The package Id (UTF8-BASE64-URL-encoded)</param>
/// <response code="200">Requested AASX package</response>
/// <response code="400">Bad Request, e.g. the request parameters of the format of the request body is wrong.</response>
/// <response code="401">Unauthorized, e.g. the server refused the authorization attempt.</response>
/// <response code="403">Forbidden</response>
/// <response code="404">Not Found</response>
/// <response code="500">Internal Server Error</response>
/// <response code="0">Default error handling for unmentioned status codes</response>
[HttpGet]
[Route("/packages/{packageId}")]
[ValidateModelState]
[SwaggerOperation("GetAASXByPackageId")]
[SwaggerResponse(statusCode: 200, type: typeof(byte[]), description: "Requested AASX package")]
[SwaggerResponse(statusCode: 400, type: typeof(Result), description: "Bad Request, e.g. the request parameters of the format of the request body is wrong.")]
[SwaggerResponse(statusCode: 401, type: typeof(Result), description: "Unauthorized, e.g. the server refused the authorization attempt.")]
[SwaggerResponse(statusCode: 403, type: typeof(Result), description: "Forbidden")]
[SwaggerResponse(statusCode: 404, type: typeof(Result), description: "Not Found")]
[SwaggerResponse(statusCode: 500, type: typeof(Result), description: "Internal Server Error")]
[SwaggerResponse(statusCode: 0, type: typeof(Result), description: "Default error handling for unmentioned status codes")]
public virtual async Task<IActionResult> GetAASXByPackageId([FromRoute] [Required] string packageId)
{
var decodedPackageId = _decoderService.Decode("packageId", packageId);
_logger.LogInformation($"Received request to get the AASX Package with package id {decodedPackageId}");
if (decodedPackageId == null)
{
throw new NotAllowed($"Cannot proceed as {nameof(decodedPackageId)} is null");
}
var fileName = _fileService.GetAASXByPackageId(decodedPackageId, out var content, out var fileSize, out var aas);
var authResult = _authorizationService.AuthorizeAsync(User, aas, "SecurityPolicy").Result;
if (!authResult.Succeeded)
{
var failedReasons = authResult.Failure.FailureReasons;
var authorizationFailureReasons = failedReasons.ToList();
if (authorizationFailureReasons.Count != 0)
{
throw new NotAllowed(authorizationFailureReasons.First().Message); // TODO (jtikekar, 2023-09-04): write AuthResultMiddlewareHandler
}
if (HttpContext.Response.StatusCode == 307)
{
var url = HttpContext.Response.Headers["redirectInfo"].First();
return new RedirectResult(url ?? string.Empty);
}
}
//content-disposition so that the aasx file can be downloaded from the web browser.
ContentDisposition contentDisposition = new() {FileName = fileName};
HttpContext.Response.Headers.Append("Content-Disposition", contentDisposition.ToString());
HttpContext.Response.Headers.Append("X-FileName", fileName);
HttpContext.Response.ContentLength = fileSize;
await HttpContext.Response.Body.WriteAsync(content);
return new EmptyResult();
}
/// <summary>
/// Returns a list of available AASX packages at the server
/// </summary>
/// <param name="aasId">The Asset Administration Shell’s unique id (UTF8-BASE64-URL-encoded)</param>
/// <param name="limit">The maximum number of elements in the response array</param>
/// <param name="cursor">A server-generated identifier retrieved from pagingMetadata that specifies from which position the result listing should continue</param>
/// <response code="200">Requested package list</response>
/// <response code="400">Bad Request, e.g. the request parameters of the format of the request body is wrong.</response>
/// <response code="401">Unauthorized, e.g. the server refused the authorization attempt.</response>
/// <response code="403">Forbidden</response>
/// <response code="500">Internal Server Error</response>
/// <response code="0">Default error handling for unmentioned status codes</response>
[HttpGet]
[Route("/packages")]
[ValidateModelState]
[SwaggerOperation("GetAllAASXPackageIds")]
[SwaggerResponse(statusCode: 200, type: typeof(PackageDescriptionPagedResult), description: "Requested package list")]
[SwaggerResponse(statusCode: 400, type: typeof(Result), description: "Bad Request, e.g. the request parameters of the format of the request body is wrong.")]
[SwaggerResponse(statusCode: 401, type: typeof(Result), description: "Unauthorized, e.g. the server refused the authorization attempt.")]
[SwaggerResponse(statusCode: 403, type: typeof(Result), description: "Forbidden")]
[SwaggerResponse(statusCode: 500, type: typeof(Result), description: "Internal Server Error")]
[SwaggerResponse(statusCode: 0, type: typeof(Result), description: "Default error handling for unmentioned status codes")]
public virtual IActionResult GetAllAASXPackageIds([FromQuery] string? aasId, [FromQuery] int? limit, [FromQuery] string? cursor)
{
_logger.LogInformation($"Received request to get all the AASX packages.");
var decodedAasId = _decoderService.Decode("aasId", aasId);
var packages = _fileService.GetAllAASXPackageIds(decodedAasId);
var authResult = _authorizationService.AuthorizeAsync(User, packages, "SecurityPolicy").Result;
if (!authResult.Succeeded)
{
var failedReasons = authResult.Failure.FailureReasons;
var authorizationFailureReasons = failedReasons.ToList();
if (authorizationFailureReasons.Count != 0)
{
throw new NotAllowed(authorizationFailureReasons.First().Message); // TODO (jtikekar, 2023-09-04): write AuthResultMiddlewareHandler
}
}
var paginatedPackages = _paginationService.GetPaginatedPackageDescriptionList(packages, new PaginationParameters(cursor, limit));
return new ObjectResult(paginatedPackages);
}
/// <summary>
/// Creates an AASX package at the server
/// </summary>
/// <param name="aasIds">Included AAS Ids</param>
/// <param name="file">AASX Package</param>
/// <returns></returns>
[HttpPost]
[Route("/packages")]
[ValidateModelState]
[SwaggerOperation("PostAASXPackage")]
public virtual IActionResult PostAASXPackage([FromQuery] string? aasIds, IFormFile? file)
{
_logger.LogInformation($"Received request to create a new AASX Package.");
var authResult = _authorizationService.AuthorizeAsync(User, "", "SecurityPolicy").Result;
if (!authResult.Succeeded)
{
var failedReasons = authResult.Failure.FailureReasons;
var authorizationFailureReasons = failedReasons.ToList();
if (authorizationFailureReasons.Count != 0)
{
throw new NotAllowed(authorizationFailureReasons.First().Message); // TODO (jtikekar, 2023-09-04): write AuthResultMiddlewareHandler
}
if (HttpContext.Response.StatusCode == 307)
{
var url = HttpContext.Response.Headers["redirectInfo"].First();
return new RedirectResult(url ?? string.Empty);
}
}
// TODO (jtikekar, 2023-09-04): aasIds
var stream = new MemoryStream();
file?.CopyTo(stream);
var packageId = _fileService.PostAASXPackage(stream.ToArray(), file?.FileName ?? string.Empty);
return CreatedAtAction(nameof(PostAASXPackage), packageId);
}
/// <summary>
/// Updates the AASX package at the server
/// </summary>
/// <param name="packageId">Package ID from the package list (BASE64-URL-encoded)</param>
/// <param name="file">AASX Package</param>
/// <param name="aasIds">Included AAS Identifiers</param>
/// <returns></returns>
[HttpPut]
[Route("/packages/{packageId}")]
[ValidateModelState]
[SwaggerOperation("PutAASXPackageById")]
public virtual IActionResult PutAASXPackageById([FromRoute] [Required] string packageId, IFormFile? file, [FromQuery] string? aasIds)
{
// TODO (jtikekar, 2023-09-04): aasIds
var decodedPackageId = _decoderService.Decode("packageId", packageId);
if (decodedPackageId == null)
{
throw new NotAllowed($"Cannot proceed as {nameof(decodedPackageId)} is null");
}
_logger.LogInformation($"Received request to update the AASX Package with package id {decodedPackageId}.");
var aas = _fileService.GetAssetAdministrationShellByPackageId(decodedPackageId);
var authResult = _authorizationService.AuthorizeAsync(User, aas, "SecurityPolicy").Result;
if (!authResult.Succeeded)
{
var failedReasons = authResult.Failure.FailureReasons;
var authorizationFailureReasons = failedReasons.ToList();
if (authorizationFailureReasons.Count != 0)
{
throw new NotAllowed(authorizationFailureReasons.First().Message); // TODO (jtikekar, 2023-09-04): write AuthResultMiddlewareHandler
}
if (HttpContext.Response.StatusCode == 307)
{
var url = HttpContext.Response.Headers["redirectInfo"].First();
return new RedirectResult(url ?? string.Empty);
}
}
var stream = new MemoryStream();
file?.CopyTo(stream);
var fileName = file?.FileName ?? string.Empty;
_fileService.UpdateAASXPackageById(decodedPackageId, stream.ToArray(), fileName);
return NoContent();
}
}