initial commit
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
namespace Indotalent.ConfigBackEnd.Attributes;
|
||||
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
|
||||
public class AuthorizeAttribute : Attribute
|
||||
{
|
||||
public string Role { get; set; } = string.Empty;
|
||||
public string Permission { get; set; } = string.Empty;
|
||||
public string Policy { get; set; } = string.Empty;
|
||||
|
||||
public AuthorizeAttribute()
|
||||
{
|
||||
}
|
||||
|
||||
public AuthorizeAttribute(string role)
|
||||
{
|
||||
Role = role;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
namespace Indotalent.ConfigBackEnd.Behaviours;
|
||||
|
||||
using Indotalent.ConfigBackEnd.Attributes;
|
||||
using Indotalent.ConfigBackEnd.Exceptions;
|
||||
using Indotalent.ConfigBackEnd.Interfaces;
|
||||
using MediatR;
|
||||
using System.Reflection;
|
||||
|
||||
public class AuthorizationBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
|
||||
where TRequest : IRequest<TResponse>
|
||||
{
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
|
||||
public AuthorizationBehaviour(ICurrentUserService currentUserService)
|
||||
{
|
||||
_currentUserService = currentUserService;
|
||||
}
|
||||
|
||||
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
|
||||
{
|
||||
var authorizeAttributes = request.GetType().GetCustomAttributes<AuthorizeAttribute>();
|
||||
|
||||
if (authorizeAttributes.Any())
|
||||
{
|
||||
if (_currentUserService.UserId == null)
|
||||
{
|
||||
throw new UnauthorizedAccessException();
|
||||
}
|
||||
|
||||
var authorizeAttributesWithRoles = authorizeAttributes.Where(a => !string.IsNullOrWhiteSpace(a.Role));
|
||||
|
||||
if (authorizeAttributesWithRoles.Any())
|
||||
{
|
||||
var authorized = false;
|
||||
foreach (var role in authorizeAttributesWithRoles.Select(a => a.Role))
|
||||
{
|
||||
var isInRole = await _currentUserService.IsInRoleAsync(role.Trim());
|
||||
if (isInRole)
|
||||
{
|
||||
authorized = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!authorized)
|
||||
{
|
||||
throw new ForbiddenAccessException();
|
||||
}
|
||||
}
|
||||
|
||||
var authorizeAttributesWithPermissions = authorizeAttributes.Where(a => !string.IsNullOrWhiteSpace(a.Permission));
|
||||
|
||||
if (authorizeAttributesWithPermissions.Any())
|
||||
{
|
||||
foreach (var permission in authorizeAttributesWithPermissions.Select(a => a.Permission))
|
||||
{
|
||||
var hasPermission = await _currentUserService.HasPermissionAsync(permission.Trim());
|
||||
if (!hasPermission)
|
||||
{
|
||||
throw new ForbiddenAccessException();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return await next();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
namespace Indotalent.ConfigBackEnd.Behaviours;
|
||||
|
||||
using Indotalent.ConfigBackEnd.Interfaces;
|
||||
using MediatR.Pipeline;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
public class LoggingBehaviour<TRequest> : IRequestPreProcessor<TRequest>
|
||||
where TRequest : notnull
|
||||
{
|
||||
private readonly ILogger _logger;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
|
||||
public LoggingBehaviour(ILogger<TRequest> logger, ICurrentUserService currentUserService)
|
||||
{
|
||||
_logger = logger;
|
||||
_currentUserService = currentUserService;
|
||||
}
|
||||
|
||||
public Task Process(TRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
var requestName = typeof(TRequest).Name;
|
||||
var userId = _currentUserService.UserId ?? string.Empty;
|
||||
var userName = _currentUserService.UserName ?? string.Empty;
|
||||
|
||||
_logger.LogInformation("Request: {Name} {UserId} {UserName} {@Request}",
|
||||
requestName, userId, userName, request);
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
namespace Indotalent.ConfigBackEnd.Behaviours;
|
||||
|
||||
using Indotalent.ConfigBackEnd.Interfaces;
|
||||
using MediatR;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Diagnostics;
|
||||
|
||||
public class PerformanceBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
|
||||
where TRequest : IRequest<TResponse>
|
||||
{
|
||||
private readonly Stopwatch _timer;
|
||||
private readonly ILogger<TRequest> _logger;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
|
||||
public PerformanceBehaviour(
|
||||
ILogger<TRequest> logger,
|
||||
ICurrentUserService currentUserService)
|
||||
{
|
||||
_timer = new Stopwatch();
|
||||
_logger = logger;
|
||||
_currentUserService = currentUserService;
|
||||
}
|
||||
|
||||
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
|
||||
{
|
||||
_timer.Start();
|
||||
|
||||
var response = await next();
|
||||
|
||||
_timer.Stop();
|
||||
|
||||
var elapsedMilliseconds = _timer.ElapsedMilliseconds;
|
||||
|
||||
if (elapsedMilliseconds > 500)
|
||||
{
|
||||
var requestName = typeof(TRequest).Name;
|
||||
var userId = _currentUserService.UserId ?? string.Empty;
|
||||
var userName = _currentUserService.UserName ?? string.Empty;
|
||||
|
||||
_logger.LogWarning("Long Running Request: {Name} ({ElapsedMilliseconds} milliseconds) {@UserId} {@UserName} {@Request}",
|
||||
requestName, elapsedMilliseconds, userId, userName, request);
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
namespace Indotalent.ConfigBackEnd.Behaviours;
|
||||
|
||||
using Indotalent.Shared.Consts;
|
||||
using MediatR;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
public class UnhandledExceptionBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
|
||||
where TRequest : IRequest<TResponse>
|
||||
{
|
||||
private readonly ILogger<TRequest> _logger;
|
||||
|
||||
public UnhandledExceptionBehaviour(ILogger<TRequest> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await next();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var requestName = typeof(TRequest).Name;
|
||||
|
||||
_logger.LogError(ex, GlobalConsts.BehaviourError + " {Name} {@Request}",
|
||||
requestName, request);
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
namespace Indotalent.ConfigBackEnd.Behaviours;
|
||||
|
||||
using FluentValidation;
|
||||
using MediatR;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
public class ValidationBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
|
||||
where TRequest : IRequest<TResponse>
|
||||
{
|
||||
private readonly IEnumerable<IValidator<TRequest>> _validators;
|
||||
|
||||
public ValidationBehaviour(IEnumerable<IValidator<TRequest>> validators)
|
||||
{
|
||||
_validators = validators;
|
||||
}
|
||||
|
||||
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_validators.Any())
|
||||
{
|
||||
var context = new ValidationContext<TRequest>(request);
|
||||
|
||||
var validationResults = await Task.WhenAll(
|
||||
_validators.Select(v => v.ValidateAsync(context, cancellationToken)));
|
||||
|
||||
var failures = validationResults
|
||||
.SelectMany(r => r.Errors)
|
||||
.Where(f => f != null)
|
||||
.ToList();
|
||||
|
||||
if (failures.Count != 0)
|
||||
{
|
||||
throw new ValidationException(failures);
|
||||
}
|
||||
}
|
||||
|
||||
return await next();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
namespace Indotalent.ConfigBackEnd;
|
||||
|
||||
using FluentValidation;
|
||||
using Indotalent.ConfigBackEnd.Behaviours;
|
||||
using MediatR;
|
||||
using MediatR.Pipeline;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
public static class DI
|
||||
{
|
||||
public static IServiceCollection AddConfigBackEndDI(this IServiceCollection services)
|
||||
{
|
||||
services.AddMediatR(cfg =>
|
||||
{
|
||||
cfg.RegisterServicesFromAssembly(typeof(DI).Assembly);
|
||||
|
||||
cfg.AddRequestPreProcessor(typeof(IRequestPreProcessor<>), typeof(LoggingBehaviour<>));
|
||||
cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(UnhandledExceptionBehaviour<,>));
|
||||
cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(PerformanceBehaviour<,>));
|
||||
cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(ValidationBehaviour<,>));
|
||||
cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(AuthorizationBehaviour<,>));
|
||||
|
||||
cfg.Lifetime = ServiceLifetime.Scoped;
|
||||
});
|
||||
|
||||
services.AddValidatorsFromAssembly(typeof(DI).Assembly);
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
namespace Indotalent.ConfigBackEnd.Exceptions;
|
||||
|
||||
public class AlreadyExistsException : Exception
|
||||
{
|
||||
public AlreadyExistsException()
|
||||
: base()
|
||||
{
|
||||
}
|
||||
|
||||
public AlreadyExistsException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public AlreadyExistsException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
}
|
||||
|
||||
public AlreadyExistsException(string name, object key)
|
||||
: base($"Entity \"{name}\" ({key}) already exists.")
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
namespace Indotalent.ConfigBackEnd.Exceptions;
|
||||
|
||||
public class ForbiddenAccessException : Exception
|
||||
{
|
||||
public ForbiddenAccessException() : base()
|
||||
{
|
||||
}
|
||||
|
||||
public ForbiddenAccessException(string message) : base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public ForbiddenAccessException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
namespace Indotalent.ConfigBackEnd.Exceptions;
|
||||
|
||||
public class MismatchException : Exception
|
||||
{
|
||||
public MismatchException()
|
||||
: base()
|
||||
{
|
||||
}
|
||||
|
||||
public MismatchException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public MismatchException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
}
|
||||
|
||||
public MismatchException(string name, object expected, object actual)
|
||||
: base($"Mismatch detected for \"{name}\". Expected: {expected}, but received: {actual}.")
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
namespace Indotalent.ConfigBackEnd.Exceptions;
|
||||
|
||||
public class NotFoundException : Exception
|
||||
{
|
||||
public NotFoundException()
|
||||
: base()
|
||||
{
|
||||
}
|
||||
|
||||
public NotFoundException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public NotFoundException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
}
|
||||
|
||||
public NotFoundException(string name, object key)
|
||||
: base($"Entity \"{name}\" ({key}) was not found.")
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
namespace Indotalent.ConfigBackEnd.Exceptions;
|
||||
|
||||
using FluentValidation.Results;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
public class ValidationException : Exception
|
||||
{
|
||||
public IDictionary<string, string[]> Errors { get; }
|
||||
|
||||
public ValidationException()
|
||||
: base("One or more validation failures have occurred.")
|
||||
{
|
||||
Errors = new Dictionary<string, string[]>();
|
||||
}
|
||||
|
||||
public ValidationException(IEnumerable<ValidationFailure> failures)
|
||||
: this()
|
||||
{
|
||||
Errors = failures
|
||||
.GroupBy(e => e.PropertyName, e => e.ErrorMessage)
|
||||
.ToDictionary(failureGroup => failureGroup.Key, failureGroup => failureGroup.ToArray());
|
||||
}
|
||||
|
||||
public ValidationException(string message)
|
||||
: base(message)
|
||||
{
|
||||
Errors = new Dictionary<string, string[]>();
|
||||
}
|
||||
|
||||
public ValidationException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
Errors = new Dictionary<string, string[]>();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace Indotalent.ConfigBackEnd.Extensions;
|
||||
|
||||
public static class DateTimeExtensions
|
||||
{
|
||||
private const string DefaultFormat = "dd MMM yyyy, HH:mm";
|
||||
|
||||
public static string ToString(this DateTimeOffset? dateTimeOffset, string format = DefaultFormat)
|
||||
{
|
||||
if (!dateTimeOffset.HasValue) return "-";
|
||||
|
||||
return dateTimeOffset.Value.ToLocalTime().ToString(format);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using System.ComponentModel;
|
||||
using System.Reflection;
|
||||
|
||||
namespace Indotalent.ConfigBackEnd.Extensions;
|
||||
|
||||
public static class EnumExtension
|
||||
{
|
||||
public static string GetDescription(this Enum value)
|
||||
{
|
||||
var field = value.GetType().GetField(value.ToString());
|
||||
if (field == null)
|
||||
{
|
||||
return value.ToString();
|
||||
}
|
||||
|
||||
var attribute = field.GetCustomAttribute<DescriptionAttribute>();
|
||||
|
||||
return attribute == null ? value.ToString() : attribute.Description;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
namespace Indotalent.ConfigBackEnd.Extensions;
|
||||
|
||||
using Indotalent.Shared.Models;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Text.Json;
|
||||
|
||||
public static class GenericExtensions
|
||||
{
|
||||
public static bool IsNullOrEmpty<T>(this IEnumerable<T>? enumerable)
|
||||
{
|
||||
return enumerable == null || !enumerable.Any();
|
||||
}
|
||||
|
||||
public static T? ToObject<T>(this string json)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(json)) return default;
|
||||
|
||||
return JsonSerializer.Deserialize<T>(json, new JsonSerializerOptions
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
});
|
||||
}
|
||||
|
||||
public static string ToJson<T>(this T obj)
|
||||
{
|
||||
return JsonSerializer.Serialize(obj);
|
||||
}
|
||||
|
||||
public static TDestination MapTo<TDestination>(this object source)
|
||||
where TDestination : new()
|
||||
{
|
||||
var json = JsonSerializer.Serialize(source);
|
||||
return JsonSerializer.Deserialize<TDestination>(json) ?? new TDestination();
|
||||
}
|
||||
|
||||
public static string ToCurrency(this decimal value, string culture = "id-ID")
|
||||
{
|
||||
return value.ToString("C0", new System.Globalization.CultureInfo(culture));
|
||||
}
|
||||
|
||||
public static bool IsBetween<T>(this T value, T low, T high) where T : IComparable<T>
|
||||
{
|
||||
return value.CompareTo(low) >= 0 && value.CompareTo(high) <= 0;
|
||||
}
|
||||
|
||||
public static IResult ToApiResponse<T>(this PagedList<T> result)
|
||||
{
|
||||
return Results.Ok(new ApiResponse<List<T>>
|
||||
{
|
||||
IsSuccess = true,
|
||||
StatusCode = 200,
|
||||
Value = result.Value,
|
||||
Pagination = new PaginationMetadata
|
||||
{
|
||||
Count = result.Count,
|
||||
Top = result.Top,
|
||||
Skip = result.Skip
|
||||
},
|
||||
ServerTime = DateTime.UtcNow
|
||||
});
|
||||
}
|
||||
|
||||
public static IResult ToApiResponse<T>(this T? result, string? message = null, int statusCode = 200)
|
||||
{
|
||||
if (result == null)
|
||||
{
|
||||
return Results.NotFound(new ApiResponse<T>
|
||||
{
|
||||
IsSuccess = false,
|
||||
StatusCode = 404,
|
||||
Message = message ?? "Data not found",
|
||||
ServerTime = DateTime.UtcNow
|
||||
});
|
||||
}
|
||||
|
||||
return Results.Ok(new ApiResponse<T>
|
||||
{
|
||||
IsSuccess = true,
|
||||
StatusCode = statusCode,
|
||||
Message = message,
|
||||
Value = result,
|
||||
Pagination = null,
|
||||
ServerTime = DateTime.UtcNow
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
namespace Indotalent.ConfigBackEnd.Extensions;
|
||||
|
||||
using Indotalent.Data.Interfaces;
|
||||
using Indotalent.Shared.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Linq.Expressions;
|
||||
|
||||
public static class IQueryableExtensions
|
||||
{
|
||||
public static IQueryable<T> WhereIf<T>(
|
||||
this IQueryable<T> query,
|
||||
bool condition,
|
||||
Expression<Func<T, bool>> predicate)
|
||||
{
|
||||
return condition ? query.Where(predicate) : query;
|
||||
}
|
||||
|
||||
public static async Task<PagedList<T>> ToPagedListAsync<T>(
|
||||
this IQueryable<T> query,
|
||||
int skip,
|
||||
int top)
|
||||
{
|
||||
top = top <= 0 ? 5 : top;
|
||||
skip = skip < 0 ? 0 : skip;
|
||||
|
||||
var count = await query.CountAsync();
|
||||
|
||||
var items = await query
|
||||
.Skip(skip)
|
||||
.Take(top)
|
||||
.ToListAsync();
|
||||
|
||||
return new PagedList<T>(items, count, skip, top);
|
||||
}
|
||||
|
||||
public static IQueryable<T> OrderByPropertyName<T>(
|
||||
this IQueryable<T> query,
|
||||
string? propertyName,
|
||||
bool isDescending)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(propertyName)) return query;
|
||||
|
||||
var parameter = Expression.Parameter(typeof(T), "x");
|
||||
var property = Expression.Property(parameter, propertyName);
|
||||
var lambda = Expression.Lambda(property, parameter);
|
||||
|
||||
var methodName = isDescending ? "OrderByDescending" : "OrderBy";
|
||||
var resultExpression = Expression.Call(
|
||||
typeof(Queryable),
|
||||
methodName,
|
||||
new Type[] { typeof(T), property.Type },
|
||||
query.Expression,
|
||||
Expression.Quote(lambda));
|
||||
|
||||
return query.Provider.CreateQuery<T>(resultExpression);
|
||||
}
|
||||
|
||||
public static IQueryable<T> NotDeletedOnly<T>(this IQueryable<T> query)
|
||||
where T : class, IHasIsDeleted
|
||||
{
|
||||
return query.Where(x => !x.IsDeleted);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
namespace Indotalent.ConfigBackEnd.Extensions;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
public static class ListExtensions
|
||||
{
|
||||
public static void AddIf<T>(this IList<T> list, bool condition, T item)
|
||||
{
|
||||
if (condition)
|
||||
{
|
||||
list.Add(item);
|
||||
}
|
||||
}
|
||||
|
||||
public static IEnumerable<IEnumerable<T>> Chunk<T>(this IEnumerable<T> source, int size)
|
||||
{
|
||||
while (source.Any())
|
||||
{
|
||||
yield return source.Take(size);
|
||||
source = source.Skip(size);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Shuffle<T>(this IList<T> list)
|
||||
{
|
||||
var rng = new Random();
|
||||
int n = list.Count;
|
||||
while (n > 1)
|
||||
{
|
||||
n--;
|
||||
int k = rng.Next(n + 1);
|
||||
T value = list[k];
|
||||
list[k] = list[n];
|
||||
list[n] = value;
|
||||
}
|
||||
}
|
||||
|
||||
public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector)
|
||||
{
|
||||
var seenKeys = new HashSet<TKey>();
|
||||
foreach (var element in source)
|
||||
{
|
||||
if (seenKeys.Add(keySelector(element)))
|
||||
{
|
||||
yield return element;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
namespace Indotalent.ConfigBackEnd.Extensions;
|
||||
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
public static class StringExtensions
|
||||
{
|
||||
public static string ToShortNameVowel(this string? value, int length = 3)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value)) return "GEN";
|
||||
|
||||
var vowels = new string(value.Where(c => "AEIOUaeiou".Contains(c)).ToArray());
|
||||
var baseName = vowels.Length >= length ? vowels : value;
|
||||
|
||||
return new string(baseName.Trim().Take(length).ToArray()).ToUpper();
|
||||
}
|
||||
|
||||
public static string ToShortNameConsonant(this string? value, int length = 3)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value)) return "GEN";
|
||||
|
||||
var consonants = new string(value.Where(c => char.IsLetter(c) && !"AEIOUaeiou".Contains(c)).ToArray());
|
||||
var baseName = consonants.Length >= length ? consonants : value;
|
||||
|
||||
return new string(baseName.Trim().Take(length).ToArray()).ToUpper();
|
||||
}
|
||||
|
||||
public static string ToInitial(this string? value)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value)) return "XX";
|
||||
|
||||
var words = value.Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
if (words.Length >= 2)
|
||||
{
|
||||
var firstInitial = words[0][0];
|
||||
var secondInitial = words[1][0];
|
||||
return $"{firstInitial}{secondInitial}".ToUpper();
|
||||
}
|
||||
|
||||
return new string(value.Trim().Take(2).ToArray()).ToUpper();
|
||||
}
|
||||
|
||||
public static bool IsNotNullOrWhiteSpace(this string? value)
|
||||
{
|
||||
return !string.IsNullOrWhiteSpace(value);
|
||||
}
|
||||
|
||||
public static string ToTitleCase(this string? value)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value)) return string.Empty;
|
||||
|
||||
return System.Globalization.CultureInfo.CurrentCulture.TextInfo
|
||||
.ToTitleCase(value.ToLower().Trim());
|
||||
}
|
||||
|
||||
public static string ToSlug(this string? value)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value)) return string.Empty;
|
||||
|
||||
var str = value.ToLower().Trim();
|
||||
str = Regex.Replace(str, @"[^a-z0-9\s-]", "");
|
||||
str = Regex.Replace(str, @"[\s-]+", " ").Trim();
|
||||
str = str.Replace(" ", "-");
|
||||
|
||||
return str;
|
||||
}
|
||||
|
||||
public static string MaskEmail(this string? email)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(email) || !email.Contains("@")) return "******";
|
||||
|
||||
var parts = email.Split('@');
|
||||
var name = parts[0];
|
||||
var domain = parts[1];
|
||||
|
||||
if (name.Length <= 2) return $"{name}***@{domain}";
|
||||
|
||||
return $"{name[..2]}***{name[^1..]}@{domain}";
|
||||
}
|
||||
|
||||
public static string Truncate(this string? value, int maxLength)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value)) return string.Empty;
|
||||
return value.Length <= maxLength ? value : $"{value[..maxLength]}...";
|
||||
}
|
||||
|
||||
public static string RemoveNonNumeric(this string? value)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value)) return string.Empty;
|
||||
return Regex.Replace(value, "[^0-9]", "");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace Indotalent.ConfigBackEnd.Interfaces;
|
||||
|
||||
public interface ICurrentUserService
|
||||
{
|
||||
string? TenantId { get; set; }
|
||||
string? UserId { get; set; }
|
||||
string? UserName { get; set; }
|
||||
string? Email { get; set; }
|
||||
string? FullName { get; set; }
|
||||
Task<bool> IsInRoleAsync(string role);
|
||||
Task<bool> HasPermissionAsync(string permission);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace Indotalent.ConfigBackEnd.Mappings;
|
||||
|
||||
using AutoMapper;
|
||||
|
||||
public interface IMapFrom<T>
|
||||
{
|
||||
void Mapping(Profile profile) => profile.CreateMap(typeof(T), GetType());
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
namespace Indotalent.ConfigBackEnd.Mappings;
|
||||
|
||||
using AutoMapper;
|
||||
using System.Reflection;
|
||||
|
||||
public class MappingProfile : Profile
|
||||
{
|
||||
public MappingProfile()
|
||||
{
|
||||
ApplyMappingsFromAssembly(Assembly.GetExecutingAssembly());
|
||||
}
|
||||
|
||||
private void ApplyMappingsFromAssembly(Assembly assembly)
|
||||
{
|
||||
var types = assembly.GetExportedTypes()
|
||||
.Where(t => t.GetInterfaces().Any(i =>
|
||||
i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMapFrom<>)))
|
||||
.ToList();
|
||||
|
||||
foreach (var type in types)
|
||||
{
|
||||
var instance = Activator.CreateInstance(type);
|
||||
|
||||
var methodInfo = type.GetMethod("Mapping")
|
||||
?? type.GetInterface("IMapFrom`1")?.GetMethod("Mapping");
|
||||
|
||||
methodInfo?.Invoke(instance, new object[] { this });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
using Indotalent.ConfigBackEnd.Exceptions;
|
||||
using Indotalent.Shared.Consts;
|
||||
using Indotalent.Shared.Models;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Indotalent.ConfigBackEnd.Middleware;
|
||||
|
||||
public class ExceptionHandlingMiddleware
|
||||
{
|
||||
private readonly RequestDelegate _next;
|
||||
private readonly ILogger<ExceptionHandlingMiddleware> _logger;
|
||||
|
||||
public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger)
|
||||
{
|
||||
_next = next;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task Invoke(HttpContext context)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _next(context);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await HandleExceptionAsync(context, ex);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleExceptionAsync(HttpContext context, Exception exception)
|
||||
{
|
||||
var code = HttpStatusCode.InternalServerError;
|
||||
var message = "An unexpected error occurred on the server.";
|
||||
var errors = new List<string>();
|
||||
|
||||
switch (exception)
|
||||
{
|
||||
case ValidationException validationException:
|
||||
code = HttpStatusCode.BadRequest;
|
||||
message = "One or more validation failures have occurred.";
|
||||
foreach (var error in validationException.Errors)
|
||||
{
|
||||
errors.AddRange(error.Value);
|
||||
}
|
||||
break;
|
||||
|
||||
case NotFoundException notFoundException:
|
||||
code = HttpStatusCode.NotFound;
|
||||
message = notFoundException.Message;
|
||||
errors.Add(notFoundException.Message);
|
||||
break;
|
||||
|
||||
case AlreadyExistsException alreadyExistsException:
|
||||
code = HttpStatusCode.Conflict;
|
||||
message = alreadyExistsException.Message;
|
||||
errors.Add(alreadyExistsException.Message);
|
||||
break;
|
||||
|
||||
case MismatchException mismatchException:
|
||||
code = HttpStatusCode.BadRequest;
|
||||
message = mismatchException.Message;
|
||||
errors.Add(mismatchException.Message);
|
||||
break;
|
||||
|
||||
case ForbiddenAccessException:
|
||||
code = HttpStatusCode.Forbidden;
|
||||
message = "You do not have permission to access this resource.";
|
||||
errors.Add("Access denied to the requested resource.");
|
||||
break;
|
||||
|
||||
case UnauthorizedAccessException:
|
||||
code = HttpStatusCode.Unauthorized;
|
||||
message = "Authentication is required to access this resource.";
|
||||
errors.Add("Session invalid or expired.");
|
||||
break;
|
||||
|
||||
default:
|
||||
if (exception.StackTrace != null && exception.StackTrace.Contains(GlobalConsts.BehaviourError))
|
||||
{
|
||||
_logger.LogError(exception, GlobalConsts.GlobalError + " {Message} on {Path}",
|
||||
exception.Message, context.Request.Path);
|
||||
}
|
||||
message = "An unexpected error occurred on the HRM server.";
|
||||
errors.Add(exception.Message);
|
||||
break;
|
||||
}
|
||||
|
||||
context.Response.ContentType = "application/json";
|
||||
context.Response.StatusCode = (int)code;
|
||||
|
||||
var response = new ApiResponse<object>
|
||||
{
|
||||
IsSuccess = false,
|
||||
StatusCode = (int)code,
|
||||
Message = message,
|
||||
Errors = errors,
|
||||
ServerTime = DateTime.UtcNow
|
||||
};
|
||||
|
||||
var jsonOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
|
||||
await context.Response.WriteAsync(JsonSerializer.Serialize(response, jsonOptions));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user