forked from ddrilling/AsbCloudServer
86 lines
2.4 KiB
C#
86 lines
2.4 KiB
C#
using AsbCloudApp.Data;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Security.Claims;
|
|
|
|
namespace Microsoft.AspNetCore.Mvc
|
|
{
|
|
public static class Extentions
|
|
{
|
|
public static int? GetCompanyId(this ClaimsPrincipal user)
|
|
{
|
|
var claimIdCompany = user.FindFirst(nameof(UserDto.IdCompany));
|
|
if (claimIdCompany is null)
|
|
return null;
|
|
|
|
return int.TryParse(claimIdCompany.Value, out int uid)
|
|
? uid
|
|
: null;
|
|
}
|
|
|
|
public static int? GetUserId(this ClaimsPrincipal user)
|
|
{
|
|
var userId = user.FindFirst(nameof(UserDto.Id));
|
|
if (userId is null)
|
|
return null;
|
|
|
|
return int.TryParse(userId.Value, out int uid)
|
|
? uid
|
|
: null;
|
|
}
|
|
|
|
public static IActionResult MakeBadRequest(this ControllerBase controller, string paramName, params string[] errors)
|
|
{
|
|
return controller.BadRequest(new
|
|
{
|
|
name = paramName,
|
|
errors,
|
|
});
|
|
}
|
|
|
|
public static BadRequestBuilder BadRequestBuilder(this ControllerBase controller, string paramName, params string[] errors)
|
|
=> new BadRequestBuilder(paramName, errors);
|
|
}
|
|
|
|
public class BadRequestBuilder
|
|
{
|
|
private readonly Dictionary<string, List<string>> body;
|
|
|
|
private List<string> GetOrCreateNew(string paramName)
|
|
{
|
|
List<string> par;
|
|
if (body.ContainsKey(paramName))
|
|
par = body[paramName];
|
|
else
|
|
{
|
|
par = new List<string>();
|
|
body[paramName] = par;
|
|
}
|
|
return par;
|
|
}
|
|
|
|
public BadRequestBuilder(string paramName, params string[] errors)
|
|
{
|
|
body = new();
|
|
body[paramName] = new List<string>(errors);
|
|
}
|
|
|
|
public BadRequestBuilder Add(string paramName, params string[] errors)
|
|
{
|
|
var par = GetOrCreateNew(paramName);
|
|
par.AddRange(errors);
|
|
return this;
|
|
}
|
|
|
|
public BadRequestObjectResult Build()
|
|
{
|
|
var o = body.Select(e => new { name = e.Key, errors = e.Value.ToArray() });
|
|
|
|
return new BadRequestObjectResult(o);
|
|
}
|
|
|
|
public static implicit operator BadRequestObjectResult(BadRequestBuilder d) => d.Build();
|
|
}
|
|
}
|
|
|