initial commit
This commit is contained in:
+31
@@ -0,0 +1,31 @@
|
||||
# OS files
|
||||
Thumbs.db
|
||||
.DS_Store
|
||||
*.swp
|
||||
*.swo
|
||||
|
||||
# IDE
|
||||
.vscode/
|
||||
.idea/
|
||||
*.sublime-project
|
||||
*.sublime-workspace
|
||||
|
||||
# .NET
|
||||
bin/
|
||||
obj/
|
||||
*.user
|
||||
*.suo
|
||||
*.cache
|
||||
*.log
|
||||
*.vs/
|
||||
packages/
|
||||
*.nupkg
|
||||
|
||||
# Docker
|
||||
.dockerignore
|
||||
|
||||
# Uploads & Logs
|
||||
wwwroot/uploads/*
|
||||
!wwwroot/uploads/.gitkeep
|
||||
wwwroot/xlogs/*
|
||||
!wwwroot/xlogs/.gitkeep
|
||||
@@ -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,30 @@
|
||||
using Indotalent.Infrastructure.AutoNumberGenerator;
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
|
||||
namespace Indotalent.ConfigBackEnd.Extensions;
|
||||
|
||||
public static class AppDbContextExtensions
|
||||
{
|
||||
public static async Task<string> GenerateAutoNumberAsync(
|
||||
this AppDbContext context,
|
||||
string entityName,
|
||||
string prefixTemplate,
|
||||
string? suffixTemplate = null,
|
||||
int paddingLength = 4,
|
||||
bool useYear = true,
|
||||
bool useMonth = false,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var generator = context.GetService<AutoNumberGeneratorService>();
|
||||
|
||||
return await generator.GenerateNextNumberAsync(
|
||||
entityName,
|
||||
prefixTemplate,
|
||||
suffixTemplate,
|
||||
paddingLength,
|
||||
useYear,
|
||||
useMonth,
|
||||
ct);
|
||||
}
|
||||
}
|
||||
@@ -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,11 @@
|
||||
namespace Indotalent.ConfigBackEnd.Interfaces;
|
||||
|
||||
public interface ICurrentUserService
|
||||
{
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using Indotalent.ConfigFrontEnd.Extensions;
|
||||
using Indotalent.ConfigFrontEnd.Models;
|
||||
using Microsoft.AspNetCore.Components;
|
||||
using Microsoft.AspNetCore.Components.Authorization;
|
||||
|
||||
namespace Indotalent.ConfigFrontEnd.Common;
|
||||
|
||||
|
||||
public abstract class BaseAppPage : ComponentBase
|
||||
{
|
||||
[Inject]
|
||||
protected AuthenticationStateProvider AuthStateProvider { get; set; } = default!;
|
||||
|
||||
[Inject]
|
||||
protected CurrentUserState State { get; set; } = default!;
|
||||
|
||||
protected override async Task OnParametersSetAsync()
|
||||
{
|
||||
await SyncUserContext();
|
||||
await base.OnParametersSetAsync();
|
||||
}
|
||||
|
||||
private async Task SyncUserContext()
|
||||
{
|
||||
var authState = await AuthStateProvider.GetAuthenticationStateAsync();
|
||||
var user = authState.User;
|
||||
|
||||
if (user.Identity?.IsAuthenticated == true)
|
||||
{
|
||||
State.UserId = user.GetUserId();
|
||||
State.UserName = user.GetUserName();
|
||||
State.Email = user.GetEmail();
|
||||
State.FullName = user.GetFullName();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
using Indotalent.ConfigBackEnd.Interfaces;
|
||||
using Indotalent.Features.Account.Login.Cqrs;
|
||||
using Indotalent.Infrastructure.Authentication.Identity;
|
||||
using Indotalent.Shared.Models;
|
||||
using Microsoft.AspNetCore.Components;
|
||||
using MudBlazor;
|
||||
using RestSharp;
|
||||
using System.Net;
|
||||
|
||||
namespace Indotalent.ConfigFrontEnd.Common;
|
||||
|
||||
public abstract class BaseService
|
||||
{
|
||||
protected readonly IHttpClientFactory ClientFactory;
|
||||
protected readonly NavigationManager Nav;
|
||||
protected readonly ISnackbar Snackbar;
|
||||
protected readonly ICurrentUserService CurrentUserService;
|
||||
protected readonly TokenProvider TokenProvider;
|
||||
|
||||
public BaseService(
|
||||
IHttpClientFactory clientFactory,
|
||||
NavigationManager nav,
|
||||
ISnackbar snackbar,
|
||||
ICurrentUserService currentUserService,
|
||||
TokenProvider tokenProvider)
|
||||
{
|
||||
ClientFactory = clientFactory;
|
||||
Nav = nav;
|
||||
Snackbar = snackbar;
|
||||
CurrentUserService = currentUserService;
|
||||
TokenProvider = tokenProvider;
|
||||
}
|
||||
|
||||
protected HttpClient CreateClient()
|
||||
{
|
||||
var client = ClientFactory.CreateClient();
|
||||
if (client.BaseAddress == null)
|
||||
{
|
||||
client.BaseAddress = new Uri(Nav.BaseUri);
|
||||
}
|
||||
return client;
|
||||
}
|
||||
|
||||
protected async Task<ApiResponse<T>?> ExecuteWithResponseAsync<T>(RestClient client, RestRequest request)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!string.IsNullOrEmpty(TokenProvider.Token))
|
||||
request.AddOrUpdateHeader("Authorization", $"Bearer {TokenProvider.Token}");
|
||||
|
||||
if (!string.IsNullOrEmpty(TokenProvider.RefreshToken))
|
||||
request.AddOrUpdateHeader("X-Refresh-Token", TokenProvider.RefreshToken);
|
||||
|
||||
if (!string.IsNullOrEmpty(CurrentUserService.UserId))
|
||||
{
|
||||
request.AddOrUpdateHeader("X-UserId", CurrentUserService.UserId);
|
||||
request.AddOrUpdateHeader("X-UserName", CurrentUserService.UserName ?? string.Empty);
|
||||
request.AddOrUpdateHeader("X-Email", CurrentUserService.Email ?? string.Empty);
|
||||
request.AddOrUpdateHeader("X-FullName", CurrentUserService.FullName ?? string.Empty);
|
||||
}
|
||||
|
||||
var response = await client.ExecuteAsync<ApiResponse<T>>(request);
|
||||
|
||||
|
||||
if (response.StatusCode == HttpStatusCode.Unauthorized)
|
||||
{
|
||||
var httpClient = CreateClient();
|
||||
|
||||
var refreshRequestMessage = new HttpRequestMessage(HttpMethod.Post, "/api/account/refresh-token");
|
||||
|
||||
if (!string.IsNullOrEmpty(TokenProvider.RefreshToken))
|
||||
{
|
||||
refreshRequestMessage.Headers.Add("X-Refresh-Token", TokenProvider.RefreshToken);
|
||||
}
|
||||
|
||||
var refreshResponse = await httpClient.SendAsync(refreshRequestMessage);
|
||||
|
||||
if (refreshResponse.IsSuccessStatusCode)
|
||||
{
|
||||
var result = await refreshResponse.Content.ReadFromJsonAsync<LoginResponse>();
|
||||
if (result != null && !string.IsNullOrEmpty(result.Token))
|
||||
{
|
||||
TokenProvider.Token = result.Token;
|
||||
|
||||
request.AddOrUpdateHeader("Authorization", $"Bearer {TokenProvider.Token}");
|
||||
response = await client.ExecuteAsync<ApiResponse<T>>(request);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Nav.NavigateTo("/account/login");
|
||||
return default;
|
||||
}
|
||||
}
|
||||
|
||||
if (response.Data != null)
|
||||
{
|
||||
if (!response.Data.IsSuccess)
|
||||
{
|
||||
HandleApiError(response.Data);
|
||||
}
|
||||
return response.Data;
|
||||
}
|
||||
|
||||
var fallbackMessage = GetFriendlyInfrastructureErrorMessage(response);
|
||||
Snackbar.Add(fallbackMessage, Severity.Error);
|
||||
|
||||
return new ApiResponse<T>
|
||||
{
|
||||
IsSuccess = false,
|
||||
StatusCode = (int)response.StatusCode,
|
||||
Message = fallbackMessage
|
||||
};
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var systemError = $"Client System Error: {ex.Message}";
|
||||
Snackbar.Add(systemError, Severity.Error);
|
||||
return new ApiResponse<T> { IsSuccess = false, Message = systemError };
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleApiError<T>(ApiResponse<T> response)
|
||||
{
|
||||
var mainMessage = response.Message ?? "Operation failed";
|
||||
if (response.Errors != null && response.Errors.Any())
|
||||
{
|
||||
var combinedErrors = string.Join(Environment.NewLine, response.Errors.Select(e => $"• {e}"));
|
||||
Snackbar.Add(combinedErrors, Severity.Error, config =>
|
||||
{
|
||||
config.ShowCloseIcon = true;
|
||||
config.VisibleStateDuration = 3000;
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add(mainMessage, Severity.Error);
|
||||
}
|
||||
}
|
||||
|
||||
private string GetFriendlyInfrastructureErrorMessage(RestResponse response)
|
||||
{
|
||||
return response.StatusCode switch
|
||||
{
|
||||
HttpStatusCode.ServiceUnavailable => "Server is currently under maintenance.",
|
||||
HttpStatusCode.GatewayTimeout => "Server took too long to respond.",
|
||||
HttpStatusCode.Unauthorized => "Session expired. Please login again.",
|
||||
HttpStatusCode.Forbidden => "You do not have permission to access this resource.",
|
||||
HttpStatusCode.InternalServerError => "A critical error occurred on the server.",
|
||||
_ => "Unable to reach the server. Please check your connection."
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using Indotalent.ConfigBackEnd.Interfaces;
|
||||
using Indotalent.ConfigFrontEnd.Models;
|
||||
using Indotalent.ConfigFrontEnd.Service;
|
||||
using MudBlazor;
|
||||
using MudBlazor.Services;
|
||||
|
||||
namespace Indotalent.ConfigFrontEnd;
|
||||
|
||||
public static class DI
|
||||
{
|
||||
public static IServiceCollection AddConfigFrontEndDI(this IServiceCollection services)
|
||||
{
|
||||
services.AddMudServices(config =>
|
||||
{
|
||||
config.SnackbarConfiguration.PositionClass = Defaults.Classes.Position.TopRight;
|
||||
config.SnackbarConfiguration.PreventDuplicates = true;
|
||||
config.SnackbarConfiguration.NewestOnTop = true;
|
||||
config.SnackbarConfiguration.ShowCloseIcon = true;
|
||||
config.SnackbarConfiguration.VisibleStateDuration = 5000;
|
||||
config.SnackbarConfiguration.HideTransitionDuration = 300;
|
||||
config.SnackbarConfiguration.ShowTransitionDuration = 300;
|
||||
config.SnackbarConfiguration.SnackbarVariant = Variant.Filled;
|
||||
});
|
||||
|
||||
|
||||
services.AddHttpClient("AppClient", client =>
|
||||
{
|
||||
client.Timeout = TimeSpan.FromMinutes(30);
|
||||
client.DefaultRequestHeaders.Add("Accept", "application/json");
|
||||
});
|
||||
|
||||
services.AddScoped<CurrentUserState>();
|
||||
services.AddScoped<ICurrentUserService, CurrentUserService>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace Indotalent.ConfigFrontEnd.Extensions;
|
||||
|
||||
public static class IdentityClaimPrincipalExtension
|
||||
{
|
||||
public static string? GetUserId(this ClaimsPrincipal? user)
|
||||
{
|
||||
return user?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||
}
|
||||
|
||||
public static string? GetEmail(this ClaimsPrincipal? user)
|
||||
{
|
||||
return user?.FindFirst(ClaimTypes.Email)?.Value;
|
||||
}
|
||||
|
||||
public static string? GetUserName(this ClaimsPrincipal? user)
|
||||
{
|
||||
return user?.FindFirst(ClaimTypes.Name)?.Value;
|
||||
}
|
||||
|
||||
public static string? GetFullName(this ClaimsPrincipal? user)
|
||||
{
|
||||
return user?.FindFirst(ClaimTypes.GivenName)?.Value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using Indotalent.ConfigBackEnd.Interfaces;
|
||||
using Indotalent.ConfigFrontEnd.Extensions;
|
||||
|
||||
namespace Indotalent.ConfigFrontEnd.Filter;
|
||||
|
||||
public class CurrentUserFilter : IEndpointFilter
|
||||
{
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
|
||||
public CurrentUserFilter(ICurrentUserService currentUserService)
|
||||
{
|
||||
_currentUserService = currentUserService;
|
||||
}
|
||||
|
||||
public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
|
||||
{
|
||||
var httpContext = context.HttpContext;
|
||||
var user = httpContext.User;
|
||||
|
||||
string? userId = user.GetUserId();
|
||||
string? email = user.GetEmail();
|
||||
string? userName = user.GetUserName();
|
||||
string? fullName = user.GetFullName();
|
||||
|
||||
|
||||
if (string.IsNullOrEmpty(userId))
|
||||
{
|
||||
userId = httpContext.Request.Headers["X-UserId"].ToString();
|
||||
userName = httpContext.Request.Headers["X-UserName"].ToString();
|
||||
email = httpContext.Request.Headers["X-Email"].ToString();
|
||||
fullName = httpContext.Request.Headers["X-FullName"].ToString();
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(userId))
|
||||
{
|
||||
_currentUserService.UserId = userId;
|
||||
_currentUserService.UserName = userName;
|
||||
_currentUserService.Email = email;
|
||||
_currentUserService.FullName = fullName;
|
||||
}
|
||||
|
||||
return await next(context);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace Indotalent.ConfigFrontEnd.Models;
|
||||
|
||||
public class CurrentUserState
|
||||
{
|
||||
public string? UserId { get; set; }
|
||||
public string? UserName { get; set; }
|
||||
public string? Email { get; set; }
|
||||
public string? FullName { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
using Indotalent.ConfigBackEnd.Interfaces;
|
||||
using Indotalent.ConfigFrontEnd.Models;
|
||||
|
||||
namespace Indotalent.ConfigFrontEnd.Service;
|
||||
|
||||
public class CurrentUserService : ICurrentUserService
|
||||
{
|
||||
private readonly CurrentUserState _state;
|
||||
|
||||
public CurrentUserService(CurrentUserState state)
|
||||
{
|
||||
_state = state;
|
||||
}
|
||||
|
||||
public string? UserId
|
||||
{
|
||||
get => _state.UserId;
|
||||
set => _state.UserId = value;
|
||||
}
|
||||
|
||||
public string? UserName
|
||||
{
|
||||
get => _state.UserName;
|
||||
set => _state.UserName = value;
|
||||
}
|
||||
|
||||
public string? Email
|
||||
{
|
||||
get => _state.Email;
|
||||
set => _state.Email = value;
|
||||
}
|
||||
|
||||
public string? FullName
|
||||
{
|
||||
get => _state.FullName;
|
||||
set => _state.FullName = value;
|
||||
}
|
||||
|
||||
public Task<bool> IsInRoleAsync(string role)
|
||||
{
|
||||
return Task.FromResult(false);
|
||||
}
|
||||
|
||||
public Task<bool> HasPermissionAsync(string permission)
|
||||
{
|
||||
return Task.FromResult(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using Indotalent.Data.Entities;
|
||||
using Indotalent.Infrastructure.Authentication.Identity;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
|
||||
namespace Indotalent.ConfigFrontEnd.Service;
|
||||
|
||||
public static class JwtService
|
||||
{
|
||||
public static string GenerateNewJwt(ApplicationUser user, JwtSettingsModel _jwtSettings)
|
||||
{
|
||||
var authClaims = new List<Claim>
|
||||
{
|
||||
new(ClaimTypes.Name, user.UserName ?? ""),
|
||||
new(ClaimTypes.Email, user.Email ?? ""),
|
||||
new(ClaimTypes.NameIdentifier, user.Id),
|
||||
new(ClaimTypes.GivenName, user.FullName ?? ""),
|
||||
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
|
||||
};
|
||||
|
||||
var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.Key));
|
||||
|
||||
var token = new JwtSecurityToken(
|
||||
issuer: _jwtSettings.Issuer,
|
||||
audience: _jwtSettings.Audience,
|
||||
expires: DateTime.Now.AddMinutes(_jwtSettings.DurationInMinutes),
|
||||
claims: authClaims,
|
||||
signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)
|
||||
);
|
||||
|
||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using Indotalent.Data.Interfaces;
|
||||
using Indotalent.Shared.Utils;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Indotalent.Data.Abstracts;
|
||||
|
||||
public abstract class BaseEntity : IHasAudit, IHasIsDeleted
|
||||
{
|
||||
[Key]
|
||||
public string Id { get; set; } = SequentialGuidGenerator.NewSequentialId();
|
||||
public DateTimeOffset? CreatedAt { get; set; }
|
||||
public string? CreatedBy { get; set; }
|
||||
public DateTimeOffset? UpdatedAt { get; set; }
|
||||
public string? UpdatedBy { get; set; }
|
||||
public bool IsDeleted { get; set; } = false;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using Indotalent.Data.Interfaces;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class ApplicationUser : IdentityUser, IHasIsDeleted
|
||||
{
|
||||
public string? FullName { get; set; }
|
||||
public string? FirstName { get; set; }
|
||||
public string? LastName { get; set; }
|
||||
public string? ShortBio { get; set; }
|
||||
public string? JobTitle { get; set; }
|
||||
public DateTime DateOfBirth { get; set; }
|
||||
public string? StreetAddress { get; set; }
|
||||
public string? City { get; set; }
|
||||
public string? StateProvince { get; set; }
|
||||
public string? ZipCode { get; set; }
|
||||
public string? Country { get; set; }
|
||||
public string SocialMediaLinkedIn { get; set; } = string.Empty;
|
||||
public string SocialMediaX { get; set; } = string.Empty;
|
||||
public string SocialMediaFacebook { get; set; } = string.Empty;
|
||||
public string SocialMediaInstagram { get; set; } = string.Empty;
|
||||
public string SocialMediaTikTok { get; set; } = string.Empty;
|
||||
public string OtherInformation1 { get; set; } = string.Empty;
|
||||
public string OtherInformation2 { get; set; } = string.Empty;
|
||||
public string OtherInformation3 { get; set; } = string.Empty;
|
||||
public string? SsoIdFirebase { get; set; }
|
||||
public string? SsoIdKeycloak { get; set; }
|
||||
public string? SsoIdAzure { get; set; }
|
||||
public string? SsoIdAws { get; set; }
|
||||
public string? SsoIdOther1 { get; set; }
|
||||
public string? SsoIdOther2 { get; set; }
|
||||
public string? SsoIdOther3 { get; set; }
|
||||
public DateTime CreatedAt { get; set; } = DateTime.Now;
|
||||
public DateTime? LastLoginAt { get; set; }
|
||||
public DateTime? UpdatedAt { get; set; }
|
||||
public bool IsActive { get; set; } = true;
|
||||
public bool IsDeleted { get; set; } = false;
|
||||
public string? AvatarFile { get; set; }
|
||||
public string? RefreshToken { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Infrastructure.AutoNumberGenerator;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class AutoNumberSequence : BaseEntity, IAutoNumberGenerator
|
||||
{
|
||||
public string? EntityName { get; set; }
|
||||
public int? Year { get; set; }
|
||||
public int? Month { get; set; }
|
||||
public long? CurrentSequence { get; set; }
|
||||
public string? PrefixTemplate { get; set; }
|
||||
public string? SuffixTemplate { get; set; }
|
||||
public int? PaddingLength { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
using Indotalent.Data.Enums;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class Bill : BaseEntity, IHasAutoNumber
|
||||
{
|
||||
public string? AutoNumber { get; set; }
|
||||
public DateTime? BillDate { get; set; }
|
||||
public BillStatus BillStatus { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public string? PurchaseOrderId { get; set; }
|
||||
public PurchaseOrder? PurchaseOrder { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
using Indotalent.Data.Enums;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class Booking : BaseEntity, IHasAutoNumber
|
||||
{
|
||||
public string? Subject { get; set; }
|
||||
public string? AutoNumber { get; set; }
|
||||
public DateTime? StartTime { get; set; }
|
||||
public DateTime? EndTime { get; set; }
|
||||
public string? StartTimezone { get; set; }
|
||||
public string? EndTimezone { get; set; }
|
||||
public string? Location { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public bool? IsAllDay { get; set; }
|
||||
public bool? IsReadOnly { get; set; }
|
||||
public bool? IsBlock { get; set; }
|
||||
public string? RecurrenceRule { get; set; }
|
||||
public string? RecurrenceID { get; set; }
|
||||
public string? FollowingID { get; set; }
|
||||
public string? RecurrenceException { get; set; }
|
||||
public BookingStatus Status { get; set; }
|
||||
public string? BookingResourceId { get; set; }
|
||||
public BookingResource? BookingResource { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class BookingGroup : BaseEntity
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class BookingResource : BaseEntity
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public string? BookingGroupId { get; set; }
|
||||
public BookingGroup? BookingGroup { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class Company : BaseEntity, IHasAutoNumber
|
||||
{
|
||||
public string? AutoNumber { get; set; }
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public string Description { get; set; } = string.Empty;
|
||||
public bool IsDefault { get; set; } = false;
|
||||
public string CurrencyId { get; set; } = string.Empty;
|
||||
public Currency? Currency { get; set; }
|
||||
public string TaxIdentification { get; set; } = string.Empty;
|
||||
public string BusinessLicense { get; set; } = string.Empty;
|
||||
public string CompanyLogo { get; set; } = string.Empty;
|
||||
public string StreetAddress { get; set; } = string.Empty;
|
||||
public string City { get; set; } = string.Empty;
|
||||
public string StateProvince { get; set; } = string.Empty;
|
||||
public string ZipCode { get; set; } = string.Empty;
|
||||
public string Phone { get; set; } = string.Empty;
|
||||
public string Email { get; set; } = string.Empty;
|
||||
public string SocialMediaLinkedIn { get; set; } = string.Empty;
|
||||
public string SocialMediaX { get; set; } = string.Empty;
|
||||
public string SocialMediaFacebook { get; set; } = string.Empty;
|
||||
public string SocialMediaInstagram { get; set; } = string.Empty;
|
||||
public string SocialMediaTikTok { get; set; } = string.Empty;
|
||||
public string OtherInformation1 { get; set; } = string.Empty;
|
||||
public string OtherInformation2 { get; set; } = string.Empty;
|
||||
public string OtherInformation3 { get; set; } = string.Empty;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class Currency : BaseEntity, IHasAutoNumber
|
||||
{
|
||||
public string? AutoNumber { get; set; }
|
||||
public string? Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public string? Code { get; set; }
|
||||
public string? Symbol { get; set; }
|
||||
public string? CountryOwner { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class Employee : BaseEntity, IHasAutoNumber
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public string? AutoNumber { get; set; }
|
||||
public string? JobTitle { get; set; }
|
||||
public decimal CommissionRate { get; set; }
|
||||
public string? EmployeeNumber { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public string? Street { get; set; }
|
||||
public string? City { get; set; }
|
||||
public string? State { get; set; }
|
||||
public string? ZipCode { get; set; }
|
||||
public string? Country { get; set; }
|
||||
public string? PhoneNumber { get; set; }
|
||||
public string? FaxNumber { get; set; }
|
||||
public string? EmailAddress { get; set; }
|
||||
public string? Website { get; set; }
|
||||
public string? WhatsApp { get; set; }
|
||||
public string? LinkedIn { get; set; }
|
||||
public string? Facebook { get; set; }
|
||||
public string? Instagram { get; set; }
|
||||
public string? TwitterX { get; set; }
|
||||
public string? TikTok { get; set; }
|
||||
public string? EmployeeGroupId { get; set; }
|
||||
public EmployeeGroup? EmployeeGroup { get; set; }
|
||||
public string? EmployeeCategoryId { get; set; }
|
||||
public EmployeeCategory? EmployeeCategory { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class EmployeeCategory : BaseEntity
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
using Indotalent.Infrastructure.Database;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class EmployeeGroup : BaseEntity
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
|
||||
internal static async Task GenerateDataAsync(AppDbContext context)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
using Indotalent.Data.Enums;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class InventoryTransaction : BaseEntity, IHasAutoNumber
|
||||
{
|
||||
public string? ModuleId { get; set; }
|
||||
public string? ModuleName { get; set; }
|
||||
public string? ModuleCode { get; set; }
|
||||
public string? ModuleNumber { get; set; }
|
||||
public DateTime? MovementDate { get; set; }
|
||||
public InventoryTransactionStatus Status { get; set; }
|
||||
public string? AutoNumber { get; set; }
|
||||
public string? WarehouseId { get; set; }
|
||||
public Warehouse? Warehouse { get; set; }
|
||||
public string? ProductId { get; set; }
|
||||
public Product? Product { get; set; }
|
||||
public double? Movement { get; set; }
|
||||
public InventoryTransType? TransType { get; set; }
|
||||
public double? Stock { get; set; }
|
||||
public string? WarehouseFromId { get; set; }
|
||||
public Warehouse? WarehouseFrom { get; set; }
|
||||
public string? WarehouseToId { get; set; }
|
||||
public Warehouse? WarehouseTo { get; set; }
|
||||
public double? QtySCSys { get; set; }
|
||||
public double? QtySCCount { get; set; }
|
||||
public double? QtySCDelta { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
using Indotalent.Data.Enums;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class Invoice : BaseEntity, IHasAutoNumber
|
||||
{
|
||||
public string? AutoNumber { get; set; }
|
||||
public DateTime? InvoiceDate { get; set; }
|
||||
public InvoiceStatus InvoiceStatus { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public string? SalesOrderId { get; set; }
|
||||
public SalesOrder? SalesOrder { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Enums;
|
||||
using Indotalent.Data.Interfaces;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class MedicalRecord : BaseEntity, IHasAutoNumber
|
||||
{
|
||||
public string? AutoNumber { get; set; }
|
||||
public DateTime? RecordDate { get; set; }
|
||||
public string? PatientId { get; set; }
|
||||
public Patient? Patient { get; set; }
|
||||
public string? EmployeeId { get; set; }
|
||||
public Employee? Employee { get; set; }
|
||||
public string? Subjective { get; set; }
|
||||
public string? Objective { get; set; }
|
||||
public string? Assessment { get; set; }
|
||||
public string? Planning { get; set; }
|
||||
public string? BloodPressure { get; set; }
|
||||
public string? Temperature { get; set; }
|
||||
public string? HeartRate { get; set; }
|
||||
public string? Weight { get; set; }
|
||||
public string? Height { get; set; }
|
||||
public MedicalRecordStatus Status { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public string? MedicalRecordGroupId { get; set; }
|
||||
public MedicalRecordGroup? MedicalRecordGroup { get; set; }
|
||||
public string? MedicalRecordCategoryId { get; set; }
|
||||
public MedicalRecordCategory? MedicalRecordCategory { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class MedicalRecordCategory : BaseEntity
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
using Indotalent.Infrastructure.Database;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class MedicalRecordGroup : BaseEntity
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class Patient : BaseEntity, IHasAutoNumber
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public string? AutoNumber { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public string? Street { get; set; }
|
||||
public string? City { get; set; }
|
||||
public string? State { get; set; }
|
||||
public string? ZipCode { get; set; }
|
||||
public string? Country { get; set; }
|
||||
public string? PhoneNumber { get; set; }
|
||||
public string? FaxNumber { get; set; }
|
||||
public string? EmailAddress { get; set; }
|
||||
public string? Website { get; set; }
|
||||
public string? WhatsApp { get; set; }
|
||||
public string? LinkedIn { get; set; }
|
||||
public string? Facebook { get; set; }
|
||||
public string? Instagram { get; set; }
|
||||
public string? TwitterX { get; set; }
|
||||
public string? TikTok { get; set; }
|
||||
public string? PatientGroupId { get; set; }
|
||||
public PatientGroup? PatientGroup { get; set; }
|
||||
public string? PatientCategoryId { get; set; }
|
||||
public PatientCategory? PatientCategory { get; set; }
|
||||
public ICollection<PatientContact> PatientContactList { get; set; } = new List<PatientContact>();
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class PatientCategory : BaseEntity
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class PatientContact : BaseEntity, IHasAutoNumber
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public string? AutoNumber { get; set; }
|
||||
public string? Title { get; set; }
|
||||
public string? PhoneNumber { get; set; }
|
||||
public string? EmailAddress { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public string? PatientId { get; set; }
|
||||
public Patient? Patient { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class PatientGroup : BaseEntity
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
using Indotalent.Data.Enums;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class PaymentDisburse : BaseEntity, IHasAutoNumber
|
||||
{
|
||||
public string? BillId { get; set; }
|
||||
public Bill? Bill { get; set; }
|
||||
public string? AutoNumber { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public DateTime? PaymentDate { get; set; }
|
||||
public string? PaymentMethodId { get; set; }
|
||||
public PaymentMethod? PaymentMethod { get; set; }
|
||||
public decimal? PaymentAmount { get; set; }
|
||||
public PaymentDisburseStatus Status { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class PaymentMethod : BaseEntity
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
using Indotalent.Data.Enums;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class PaymentReceive : BaseEntity, IHasAutoNumber
|
||||
{
|
||||
public string? InvoiceId { get; set; }
|
||||
public Invoice? Invoice { get; set; }
|
||||
public string? AutoNumber { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public DateTime? PaymentDate { get; set; }
|
||||
public string? PaymentMethodId { get; set; }
|
||||
public PaymentMethod? PaymentMethod { get; set; }
|
||||
public decimal? PaymentAmount { get; set; }
|
||||
public PaymentReceiveStatus Status { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class Product : BaseEntity, IHasAutoNumber
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public string? AutoNumber { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public decimal? UnitPrice { get; set; }
|
||||
public bool? Physical { get; set; } = true;
|
||||
public string? UnitMeasureId { get; set; }
|
||||
public UnitMeasure? UnitMeasure { get; set; }
|
||||
public string? ProductGroupId { get; set; }
|
||||
public ProductGroup? ProductGroup { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class ProductGroup : BaseEntity
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
using Indotalent.Data.Enums;
|
||||
using System.Numerics;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class PurchaseOrder : BaseEntity, IHasAutoNumber
|
||||
{
|
||||
public string? AutoNumber { get; set; }
|
||||
public DateTime? OrderDate { get; set; }
|
||||
public PurchaseOrderStatus OrderStatus { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public string? VendorId { get; set; }
|
||||
public Vendor? Vendor { get; set; }
|
||||
public string? TaxId { get; set; }
|
||||
public Tax? Tax { get; set; }
|
||||
public decimal? BeforeTaxAmount { get; set; }
|
||||
public decimal? TaxAmount { get; set; }
|
||||
public decimal? AfterTaxAmount { get; set; }
|
||||
public ICollection<PurchaseOrderItem> PurchaseOrderItemList { get; set; } = new List<PurchaseOrderItem>();
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class PurchaseOrderItem : BaseEntity
|
||||
{
|
||||
public string? PurchaseOrderId { get; set; }
|
||||
public PurchaseOrder? PurchaseOrder { get; set; }
|
||||
public string? ProductId { get; set; }
|
||||
public Product? Product { get; set; }
|
||||
public string? Summary { get; set; }
|
||||
public decimal? UnitPrice { get; set; } = 0;
|
||||
public double? Quantity { get; set; } = 1;
|
||||
public decimal? Total { get; set; } = 0;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
using Indotalent.Data.Enums;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class SalesOrder : BaseEntity, IHasAutoNumber
|
||||
{
|
||||
public string? AutoNumber { get; set; }
|
||||
public DateTime? OrderDate { get; set; }
|
||||
public SalesOrderStatus OrderStatus { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public string? CustomerId { get; set; }
|
||||
public Patient? Customer { get; set; }
|
||||
public string? EmployeeId { get; set; }
|
||||
public Employee? Employee { get; set; }
|
||||
public string? TaxId { get; set; }
|
||||
public Tax? Tax { get; set; }
|
||||
public string? SalesOrderGroupId { get; set; }
|
||||
public SalesOrderGroup? SalesOrderGroup { get; set; }
|
||||
public string? SalesOrderCategoryId { get; set; }
|
||||
public SalesOrderCategory? SalesOrderCategory { get; set; }
|
||||
public decimal? BeforeTaxAmount { get; set; }
|
||||
public decimal? TaxAmount { get; set; }
|
||||
public decimal? AfterTaxAmount { get; set; }
|
||||
public ICollection<SalesOrderItem> SalesOrderItemList { get; set; } = new List<SalesOrderItem>();
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class SalesOrderCategory : BaseEntity
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class SalesOrderGroup : BaseEntity
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class SalesOrderItem : BaseEntity
|
||||
{
|
||||
public string? SalesOrderId { get; set; }
|
||||
public SalesOrder? SalesOrder { get; set; }
|
||||
public string? ProductId { get; set; }
|
||||
public Product? Product { get; set; }
|
||||
public string? Summary { get; set; }
|
||||
public decimal? UnitPrice { get; set; } = 0;
|
||||
public double? Quantity { get; set; } = 1;
|
||||
public decimal? Total { get; set; } = 0;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class SerilogLogs
|
||||
{
|
||||
[Key]
|
||||
public int Id { get; set; }
|
||||
public string? Message { get; set; }
|
||||
public string? MessageTemplate { get; set; }
|
||||
public string? Level { get; set; }
|
||||
public DateTimeOffset TimeStamp { get; set; }
|
||||
public string? Exception { get; set; }
|
||||
public string? Properties { get; set; }
|
||||
public string? LogEvent { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class Tax : BaseEntity, IHasAutoNumber
|
||||
{
|
||||
public string? AutoNumber { get; set; }
|
||||
public string? Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public string? Code { get; set; }
|
||||
public decimal PercentageValue { get; set; }
|
||||
public string? Category { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class Todo : BaseEntity, IHasAutoNumber
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public string? AutoNumber { get; set; }
|
||||
public DateTime? StartTime { get; set; }
|
||||
public DateTime? EndTime { get; set; }
|
||||
public bool IsCompleted { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public ICollection<TodoItem> TodoItemList { get; set; } = new List<TodoItem>();
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class TodoItem : BaseEntity
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public DateTime? StartTime { get; set; }
|
||||
public DateTime? EndTime { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public bool IsCompleted { get; set; }
|
||||
public string? TodoId { get; set; }
|
||||
public Todo? Todo { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class UnitMeasure : BaseEntity
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class Vendor : BaseEntity, IHasAutoNumber
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public string? AutoNumber { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public string? Street { get; set; }
|
||||
public string? City { get; set; }
|
||||
public string? State { get; set; }
|
||||
public string? ZipCode { get; set; }
|
||||
public string? Country { get; set; }
|
||||
public string? PhoneNumber { get; set; }
|
||||
public string? FaxNumber { get; set; }
|
||||
public string? EmailAddress { get; set; }
|
||||
public string? Website { get; set; }
|
||||
public string? WhatsApp { get; set; }
|
||||
public string? LinkedIn { get; set; }
|
||||
public string? Facebook { get; set; }
|
||||
public string? Instagram { get; set; }
|
||||
public string? TwitterX { get; set; }
|
||||
public string? TikTok { get; set; }
|
||||
public string? VendorGroupId { get; set; }
|
||||
public VendorGroup? VendorGroup { get; set; }
|
||||
public string? VendorCategoryId { get; set; }
|
||||
public VendorCategory? VendorCategory { get; set; }
|
||||
public ICollection<VendorContact> VendorContactList { get; set; } = new List<VendorContact>();
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class VendorCategory : BaseEntity
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class VendorContact : BaseEntity, IHasAutoNumber
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public string? AutoNumber { get; set; }
|
||||
public string? JobTitle { get; set; }
|
||||
public string? PhoneNumber { get; set; }
|
||||
public string? EmailAddress { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public string? VendorId { get; set; }
|
||||
public Vendor? Vendor { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class VendorGroup : BaseEntity
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using Indotalent.Data.Abstracts;
|
||||
using Indotalent.Data.Interfaces;
|
||||
|
||||
namespace Indotalent.Data.Entities;
|
||||
|
||||
public class Warehouse : BaseEntity
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public bool? SystemWarehouse { get; set; } = false;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace Indotalent.Data.Enums;
|
||||
|
||||
public enum BillStatus
|
||||
{
|
||||
[Description("Draft")]
|
||||
Draft = 0,
|
||||
[Description("Cancelled")]
|
||||
Cancelled = 1,
|
||||
[Description("Confirmed")]
|
||||
Confirmed = 2,
|
||||
[Description("Partial Paid")]
|
||||
PartialPaid = 3,
|
||||
[Description("Full Paid")]
|
||||
FullPaid = 4
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace Indotalent.Data.Enums;
|
||||
|
||||
public enum BookingStatus
|
||||
{
|
||||
[Description("Cancelled")]
|
||||
Cancelled = 0,
|
||||
[Description("Draft")]
|
||||
Draft = 1,
|
||||
[Description("Confirmed")]
|
||||
Confirmed = 2,
|
||||
[Description("OnProgress")]
|
||||
OnProgress = 3,
|
||||
[Description("Done")]
|
||||
Done = 4
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace Indotalent.Data.Enums;
|
||||
|
||||
public enum InventoryTransType
|
||||
{
|
||||
[Description("In")]
|
||||
In = 1,
|
||||
[Description("Out")]
|
||||
Out = -1,
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace Indotalent.Data.Enums;
|
||||
|
||||
public enum InventoryTransactionStatus
|
||||
{
|
||||
[Description("Draft")]
|
||||
Draft = 0,
|
||||
[Description("Cancelled")]
|
||||
Cancelled = 1,
|
||||
[Description("Confirmed")]
|
||||
Confirmed = 2,
|
||||
[Description("Archived")]
|
||||
Archived = 3
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace Indotalent.Data.Enums;
|
||||
|
||||
public enum InvoiceStatus
|
||||
{
|
||||
[Description("Draft")]
|
||||
Draft = 0,
|
||||
[Description("Cancelled")]
|
||||
Cancelled = 1,
|
||||
[Description("Confirmed")]
|
||||
Confirmed = 2,
|
||||
[Description("Partial Paid")]
|
||||
PartialPaid = 3,
|
||||
[Description("Full Paid")]
|
||||
FullPaid = 4
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace Indotalent.Data.Enums;
|
||||
|
||||
public enum MedicalRecordStatus
|
||||
{
|
||||
Draft,
|
||||
Examining,
|
||||
Completed,
|
||||
Cancelled
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace Indotalent.Data.Enums;
|
||||
|
||||
public enum PaymentDisburseStatus
|
||||
{
|
||||
[Description("Draft")]
|
||||
Draft = 0,
|
||||
[Description("Cancelled")]
|
||||
Cancelled = 1,
|
||||
[Description("Confirmed")]
|
||||
Confirmed = 2,
|
||||
[Description("Archived")]
|
||||
Archived = 3
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace Indotalent.Data.Enums;
|
||||
|
||||
public enum PaymentReceiveStatus
|
||||
{
|
||||
[Description("Draft")]
|
||||
Draft = 0,
|
||||
[Description("Cancelled")]
|
||||
Cancelled = 1,
|
||||
[Description("Confirmed")]
|
||||
Confirmed = 2,
|
||||
[Description("Archived")]
|
||||
Archived = 3
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace Indotalent.Data.Enums;
|
||||
|
||||
public enum ProgramManagerPriority
|
||||
{
|
||||
[Description("Low")]
|
||||
Low = 0,
|
||||
[Description("High")]
|
||||
High = 1,
|
||||
[Description("Normal")]
|
||||
Normal = 2,
|
||||
[Description("Critical")]
|
||||
Critical = 3
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace Indotalent.Data.Enums;
|
||||
|
||||
public enum PurchaseOrderStatus
|
||||
{
|
||||
[Description("Draft")]
|
||||
Draft = 0,
|
||||
[Description("Cancelled")]
|
||||
Cancelled = 1,
|
||||
[Description("Confirmed")]
|
||||
Confirmed = 2,
|
||||
[Description("Archived")]
|
||||
Archived = 3
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace Indotalent.Data.Enums;
|
||||
|
||||
public enum SalesOrderStatus
|
||||
{
|
||||
[Description("Draft")]
|
||||
Draft = 0,
|
||||
[Description("Cancelled")]
|
||||
Cancelled = 1,
|
||||
[Description("Confirmed")]
|
||||
Confirmed = 2,
|
||||
[Description("Archived")]
|
||||
Archived = 3
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace Indotalent.Data.Interfaces;
|
||||
|
||||
public interface IHasAudit
|
||||
{
|
||||
DateTimeOffset? CreatedAt { get; set; }
|
||||
string? CreatedBy { get; set; }
|
||||
DateTimeOffset? UpdatedAt { get; set; }
|
||||
string? UpdatedBy { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace Indotalent.Data.Interfaces;
|
||||
|
||||
public interface IHasAutoNumber
|
||||
{
|
||||
string? AutoNumber { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace Indotalent.Data.Interfaces;
|
||||
|
||||
public interface IHasIsDeleted
|
||||
{
|
||||
bool IsDeleted { get; set; }
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
# =====================================================================
|
||||
# Dockerfile untuk Blazor CMS (ASP.NET Core Blazor .NET 10)
|
||||
# =====================================================================
|
||||
# Multi-stage build:
|
||||
# Stage 1: Build aplikasi
|
||||
# Stage 2: Run production
|
||||
# =====================================================================
|
||||
|
||||
# ---- STAGE 1: BUILD ----
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
|
||||
WORKDIR /src
|
||||
|
||||
# Copy csproj dan restore dependencies (cache layer)
|
||||
COPY *.csproj .
|
||||
RUN dotnet restore
|
||||
|
||||
# Copy semua source code dan build
|
||||
COPY . .
|
||||
RUN dotnet publish -c Release -o /app --no-restore
|
||||
|
||||
# ---- STAGE 2: RUN ----
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS runtime
|
||||
WORKDIR /app
|
||||
|
||||
# Install ICU libraries untuk Blazor
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
libicu-dev \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Copy hasil build dari stage 1
|
||||
COPY --from=build /app .
|
||||
|
||||
# Set environment ke Production
|
||||
ENV ASPNETCORE_ENVIRONMENT=Production
|
||||
ENV ASPNETCORE_URLS=http://+:8080
|
||||
|
||||
# Expose port
|
||||
EXPOSE 8080
|
||||
|
||||
# Jalankan aplikasi
|
||||
ENTRYPOINT ["dotnet", "Indotalent.dll"]
|
||||
@@ -0,0 +1,63 @@
|
||||
@page "/account/access-denied"
|
||||
@using Indotalent.Features.Root
|
||||
@using MudBlazor
|
||||
@layout MainLayout
|
||||
|
||||
<PageTitle>Access Denied - Insufficient Permissions</PageTitle>
|
||||
|
||||
<MudContainer MaxWidth="MaxWidth.Medium" Class="d-flex align-center justify-center" Style="height: calc(100vh - 64px);">
|
||||
|
||||
<div class="text-center">
|
||||
|
||||
<MudIcon Icon="@Icons.Material.Filled.GppBad"
|
||||
Size="Size.Large"
|
||||
Color="Color.Error"
|
||||
Class="mb-6"
|
||||
Style="font-size: 120px;" />
|
||||
|
||||
<MudText Typo="Typo.h3" Class="mb-4" Style="font-weight: 800; color: #1a1a1a;">Access Denied</MudText>
|
||||
|
||||
<MudText Typo="Typo.body1" Class="mb-6" Style="color: #64748b;">
|
||||
Sorry, you do not have the required permissions to access this module.<br />
|
||||
This area is restricted to authorized administrative personnel only.
|
||||
</MudText>
|
||||
|
||||
<MudPaper Elevation="1" Class="pa-4 mb-8 d-inline-block" Style="border-radius: 8px; border: 1px solid #DCEBFA;">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">
|
||||
<strong>Error Code:</strong> <code>AGS_AUTH_INSUFFICIENT_PERMISSIONS</code>
|
||||
</MudText>
|
||||
<MudText Typo="Typo.caption" Style="color: #94a3b8; font-family: 'Consolas', monospace;">
|
||||
Verification failed for the current security context.
|
||||
</MudText>
|
||||
</MudPaper>
|
||||
|
||||
<div class="d-flex align-center justify-center gap-4">
|
||||
<MudButton Variant="Variant.Filled"
|
||||
Color="Color.Primary"
|
||||
Size="Size.Large"
|
||||
OnClick="GoHome"
|
||||
StartIcon="@Icons.Material.Filled.Home"
|
||||
Style="border-radius: 8px; font-weight: 700;">
|
||||
Back to Home
|
||||
</MudButton>
|
||||
|
||||
<MudButton Variant="Variant.Outlined"
|
||||
Color="Color.Default"
|
||||
Size="Size.Large"
|
||||
OnClick="Logout"
|
||||
StartIcon="@Icons.Material.Filled.Logout"
|
||||
Style="border-radius: 8px; font-weight: 700; border: 2px solid #e2e8f0;">
|
||||
Logout & Switch Account
|
||||
</MudButton>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</MudContainer>
|
||||
|
||||
@code {
|
||||
[Inject] private NavigationManager Nav { get; set; } = default!;
|
||||
|
||||
private void GoHome() => Nav.NavigateTo("/");
|
||||
private void Logout() => Nav.NavigateTo("/account/logout");
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
@inject NavigationManager Navigation
|
||||
@using Microsoft.AspNetCore.Authorization
|
||||
@using Microsoft.AspNetCore.Components.Authorization
|
||||
@attribute [AllowAnonymous]
|
||||
|
||||
<AuthorizeView>
|
||||
<NotAuthorized>
|
||||
@{
|
||||
var returnUrl = Navigation.ToBaseRelativePath(Navigation.Uri);
|
||||
Navigation.NavigateTo($"/account/login?returnUrl={Uri.EscapeDataString(returnUrl)}", forceLoad: false);
|
||||
}
|
||||
</NotAuthorized>
|
||||
<Authorized>
|
||||
@{
|
||||
Navigation.NavigateTo("/account/access-denied");
|
||||
}
|
||||
</Authorized>
|
||||
</AuthorizeView>
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
using Indotalent.ConfigFrontEnd.Service;
|
||||
using Indotalent.Data.Entities;
|
||||
using Indotalent.Features.Account.ForgotPassword.Cqrs;
|
||||
using Indotalent.Features.Account.Login.Cqrs;
|
||||
using Indotalent.Features.Account.Register.Cqrs;
|
||||
using Indotalent.Features.Account.ResetPassword.Cqrs;
|
||||
using Indotalent.Infrastructure.Authentication.Identity;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace Indotalent.Features.Account;
|
||||
|
||||
public static class AccountEndPoint
|
||||
{
|
||||
public static IEndpointConventionBuilder MapAccountEndpoints(this IEndpointRouteBuilder endpoints)
|
||||
{
|
||||
var group = endpoints.MapGroup("/account").WithTags("Account");
|
||||
|
||||
group.MapPost("/signin-sso", async ([FromQuery] string email, UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, IOptions<JwtSettingsModel> jwtOptions, HttpContext context) =>
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(email)) return Results.Json(new { status = 401, title = "Email is required" }, statusCode: 401);
|
||||
|
||||
var user = await userManager.FindByEmailAsync(email);
|
||||
|
||||
if (user == null || !user.IsActive)
|
||||
{
|
||||
return Results.Json(new { status = 401, title = "Account not found or inactive" }, statusCode: 401);
|
||||
}
|
||||
|
||||
var jwtSettings = jwtOptions.Value;
|
||||
var token = JwtService.GenerateNewJwt(user, jwtSettings);
|
||||
var refreshToken = Guid.NewGuid().ToString().Replace("-", "");
|
||||
|
||||
user.RefreshToken = refreshToken;
|
||||
user.LastLoginAt = DateTime.Now;
|
||||
await userManager.UpdateAsync(user);
|
||||
|
||||
await signInManager.SignInAsync(user, isPersistent: true);
|
||||
|
||||
context.Response.Cookies.Append("X-Auth-Token", token, new CookieOptions
|
||||
{
|
||||
HttpOnly = true,
|
||||
Secure = true,
|
||||
SameSite = SameSiteMode.Strict,
|
||||
Expires = DateTimeOffset.UtcNow.AddDays(1)
|
||||
});
|
||||
|
||||
context.Response.Cookies.Append("X-Refresh-Token", refreshToken, new CookieOptions
|
||||
{
|
||||
HttpOnly = true,
|
||||
Secure = true,
|
||||
SameSite = SameSiteMode.Strict,
|
||||
Expires = DateTimeOffset.UtcNow.AddDays(7)
|
||||
});
|
||||
|
||||
return Results.Ok(new { status = 200, title = "SSO Login successful" });
|
||||
});
|
||||
|
||||
group.MapGet("/active-user-exists", async ([FromQuery] string email, UserManager<ApplicationUser> userManager) =>
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(email))
|
||||
{
|
||||
return Results.Ok(new { exists = false, isActive = false });
|
||||
}
|
||||
|
||||
var user = await userManager.FindByEmailAsync(email);
|
||||
|
||||
if (user == null)
|
||||
{
|
||||
return Results.Ok(new { exists = false, isActive = false });
|
||||
}
|
||||
|
||||
return Results.Ok(new { exists = true, isActive = user.IsActive });
|
||||
});
|
||||
|
||||
group.MapPost("/signin", async ([FromBody] LoginRequest request, IMediator mediator, HttpContext context, UserManager<ApplicationUser> userManager) =>
|
||||
{
|
||||
var command = new LoginCommand(request);
|
||||
var response = await mediator.Send(command);
|
||||
|
||||
if (response.Succeeded)
|
||||
{
|
||||
var user = await userManager.FindByEmailAsync(request.Email);
|
||||
|
||||
if (user != null)
|
||||
{
|
||||
context.Response.Cookies.Append("X-Auth-Token", response.Token!, new CookieOptions
|
||||
{
|
||||
HttpOnly = true,
|
||||
Secure = true,
|
||||
SameSite = SameSiteMode.Strict,
|
||||
Expires = DateTimeOffset.UtcNow.AddDays(1)
|
||||
});
|
||||
|
||||
context.Response.Cookies.Append("X-Refresh-Token", user.RefreshToken!, new CookieOptions
|
||||
{
|
||||
HttpOnly = true,
|
||||
Secure = true,
|
||||
SameSite = SameSiteMode.Strict,
|
||||
Expires = DateTimeOffset.UtcNow.AddDays(7)
|
||||
});
|
||||
}
|
||||
|
||||
return Results.Ok(new { status = 200, title = response.Message });
|
||||
}
|
||||
return Results.Json(new { status = 401, title = response.Message }, statusCode: 401);
|
||||
});
|
||||
|
||||
|
||||
|
||||
group.MapPost("/refresh-token", async (HttpContext context) =>
|
||||
{
|
||||
var userManager = context.RequestServices.GetRequiredService<UserManager<ApplicationUser>>();
|
||||
var jwtSettings = context.RequestServices.GetRequiredService<IOptions<JwtSettingsModel>>().Value;
|
||||
|
||||
var refreshToken = context.Request.Headers["X-Refresh-Token"].ToString();
|
||||
|
||||
if (string.IsNullOrEmpty(refreshToken)) return Results.Unauthorized();
|
||||
|
||||
var user = await userManager.Users.FirstOrDefaultAsync(u => u.RefreshToken == refreshToken);
|
||||
|
||||
if (user == null || !user.IsActive) return Results.Unauthorized();
|
||||
|
||||
var newToken = JwtService.GenerateNewJwt(user, jwtSettings);
|
||||
|
||||
context.Response.Cookies.Append("X-Auth-Token", newToken, new CookieOptions
|
||||
{
|
||||
HttpOnly = true,
|
||||
Secure = true,
|
||||
SameSite = SameSiteMode.Strict,
|
||||
Expires = DateTimeOffset.UtcNow.AddDays(1)
|
||||
});
|
||||
|
||||
return Results.Ok(new LoginResponse { Succeeded = true, Token = newToken });
|
||||
});
|
||||
|
||||
group.MapPost("/signup", async ([FromBody] CreateUserRequest request, IMediator mediator) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var command = new CreateUserCommand(request);
|
||||
var response = await mediator.Send(command);
|
||||
return Results.Ok(response);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Results.BadRequest(new { errors = new[] { ex.Message } });
|
||||
}
|
||||
});
|
||||
|
||||
group.MapPost("/signout", async (
|
||||
SignInManager<ApplicationUser> signInManager,
|
||||
UserManager<ApplicationUser> userManager,
|
||||
HttpContext context) =>
|
||||
{
|
||||
var userId = context.User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
|
||||
if (!string.IsNullOrEmpty(userId))
|
||||
{
|
||||
var user = await userManager.FindByIdAsync(userId);
|
||||
if (user != null)
|
||||
{
|
||||
user.RefreshToken = null;
|
||||
await userManager.UpdateAsync(user);
|
||||
}
|
||||
}
|
||||
|
||||
await signInManager.SignOutAsync();
|
||||
|
||||
context.Response.Cookies.Delete("X-Auth-Token");
|
||||
context.Response.Cookies.Delete("X-Refresh-Token");
|
||||
|
||||
return Results.Ok(new { status = 200, title = "Successfully signed out" });
|
||||
|
||||
});
|
||||
|
||||
group.MapPost("/forgot-password", async ([FromBody] ForgotPasswordRequest request, IMediator mediator) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var command = new ForgotPasswordCommand(request);
|
||||
var response = await mediator.Send(command);
|
||||
return Results.Ok(response);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Results.BadRequest(new { errors = new[] { ex.Message } });
|
||||
}
|
||||
});
|
||||
|
||||
group.MapPost("/logout", async (SignInManager<ApplicationUser> signInManager) =>
|
||||
{
|
||||
await signInManager.SignOutAsync();
|
||||
return Results.Ok(new { title = "Success user logout" });
|
||||
}).RequireAuthorization();
|
||||
|
||||
group.MapPost("/reset-password", async ([FromBody] ResetPasswordRequest request, IMediator mediator) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var command = new ResetPasswordCommand(request);
|
||||
var response = await mediator.Send(command);
|
||||
return Results.Ok(response);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Results.BadRequest(new { errors = new[] { ex.Message } });
|
||||
}
|
||||
});
|
||||
|
||||
return group;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,538 @@
|
||||
@using Indotalent.Shared.Consts
|
||||
@inherits LayoutComponentBase
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
<MudThemeProvider Theme="_theme" />
|
||||
<MudDialogProvider />
|
||||
<MudSnackbarProvider />
|
||||
<MudPopoverProvider />
|
||||
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
|
||||
.auth-split-container {
|
||||
display: flex;
|
||||
min-height: 100vh;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* ===== LEFT PANEL ===== */
|
||||
.auth-left-panel {
|
||||
display: none;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
background: linear-gradient(135deg, #0C4A6E 0%, #0284C7 50%, #38BDF8 100%);
|
||||
}
|
||||
|
||||
.auth-left-panel::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: -120px;
|
||||
right: -120px;
|
||||
width: 400px;
|
||||
height: 400px;
|
||||
border-radius: 50%;
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.auth-left-panel::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
bottom: -80px;
|
||||
left: -80px;
|
||||
width: 280px;
|
||||
height: 280px;
|
||||
border-radius: 50%;
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.auth-left-content {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
max-width: 28rem;
|
||||
padding: 3rem;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.auth-brand-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
.auth-brand-icon {
|
||||
width: 3.5rem;
|
||||
height: 3.5rem;
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
backdrop-filter: blur(8px);
|
||||
border-radius: 0.75rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.auth-brand-name {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 800;
|
||||
color: #ffffff;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.auth-brand-sub {
|
||||
font-size: 0.8125rem;
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.auth-welcome-title {
|
||||
font-size: 1.875rem;
|
||||
font-weight: 800;
|
||||
color: #ffffff;
|
||||
line-height: 1.3;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.auth-welcome-desc {
|
||||
font-size: 0.9375rem;
|
||||
color: rgba(255, 255, 255, 0.8);
|
||||
line-height: 1.6;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
.auth-feature-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
margin-bottom: 2.5rem;
|
||||
}
|
||||
|
||||
.auth-feature-item {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.auth-feature-check {
|
||||
width: 1.25rem;
|
||||
height: 1.25rem;
|
||||
border-radius: 0.25rem;
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
margin-top: 0.125rem;
|
||||
}
|
||||
|
||||
.auth-feature-check svg {
|
||||
width: 0.75rem;
|
||||
height: 0.75rem;
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.auth-feature-title {
|
||||
font-size: 0.875rem;
|
||||
color: #ffffff;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.auth-feature-desc {
|
||||
font-size: 0.75rem;
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
margin-top: 0.125rem;
|
||||
}
|
||||
|
||||
.auth-support-card {
|
||||
padding: 1rem;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
backdrop-filter: blur(8px);
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
border-radius: 0.75rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.auth-support-icon {
|
||||
width: 2.5rem;
|
||||
height: 2.5rem;
|
||||
border-radius: 50%;
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.auth-support-title {
|
||||
font-size: 0.875rem;
|
||||
color: #ffffff;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.auth-support-desc {
|
||||
font-size: 0.75rem;
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
}
|
||||
|
||||
/* ===== RIGHT PANEL ===== */
|
||||
.auth-right-panel {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 1.5rem;
|
||||
background: #ffffff;
|
||||
}
|
||||
|
||||
.auth-form-wrapper {
|
||||
width: 100%;
|
||||
max-width: 28rem;
|
||||
}
|
||||
|
||||
.auth-card {
|
||||
border-radius: 1rem !important;
|
||||
border: 1px solid #E2E8F0 !important;
|
||||
box-shadow: 0 4px 24px rgba(0, 0, 0, 0.06) !important;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.auth-card-footer {
|
||||
text-align: center;
|
||||
padding: 0.5rem 0;
|
||||
margin-top: 1.5rem;
|
||||
font-size: 0.75rem;
|
||||
color: #94A3B8;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
/* ===== MOBILE BRAND STRIP ===== */
|
||||
.auth-mobile-brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.5rem;
|
||||
padding: 1rem;
|
||||
background: linear-gradient(135deg, #0C4A6E 0%, #0284C7 100%);
|
||||
margin-bottom: 1.5rem;
|
||||
border-radius: 0.75rem;
|
||||
}
|
||||
|
||||
.auth-mobile-brand-icon {
|
||||
width: 2.5rem;
|
||||
height: 2.5rem;
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
border-radius: 0.5rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.auth-mobile-brand-name {
|
||||
font-size: 1.25rem;
|
||||
font-weight: 800;
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
/* ===== RESPONSIVE ===== */
|
||||
@@media (min-width: 1024px) {
|
||||
.auth-left-panel {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 50%;
|
||||
}
|
||||
|
||||
.auth-right-panel {
|
||||
width: 50%;
|
||||
padding: 2rem 4rem;
|
||||
}
|
||||
|
||||
.auth-mobile-brand {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@@media (min-width: 1280px) {
|
||||
.auth-right-panel {
|
||||
padding: 2rem 6rem;
|
||||
}
|
||||
}
|
||||
|
||||
/* ===== FORM STYLES (shared across pages) ===== */
|
||||
.page-header {
|
||||
text-align: center;
|
||||
margin-bottom: 1.5rem;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.page-header h2 {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 800;
|
||||
color: #0F172A;
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.page-header p {
|
||||
font-size: 0.875rem;
|
||||
color: #64748B;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.form-label {
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 600;
|
||||
color: #475569;
|
||||
margin-bottom: 0.375rem;
|
||||
margin-left: 0.25rem;
|
||||
}
|
||||
|
||||
.form-label-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 0.375rem;
|
||||
}
|
||||
|
||||
.forgot-link {
|
||||
font-size: 0.75rem;
|
||||
color: #94A3B8;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
font-weight: 500;
|
||||
transition: color 0.2s;
|
||||
}
|
||||
|
||||
.forgot-link:hover {
|
||||
color: #0284C7;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.remember-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.divider-or {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
margin: 1.25rem 0;
|
||||
}
|
||||
|
||||
.divider-or::before,
|
||||
.divider-or::after {
|
||||
content: '';
|
||||
flex: 1;
|
||||
height: 1px;
|
||||
background: #E2E8F0;
|
||||
}
|
||||
|
||||
.divider-or span {
|
||||
font-size: 0.75rem;
|
||||
color: #94A3B8;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
|
||||
.auth-link {
|
||||
color: #0284C7;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
transition: color 0.2s;
|
||||
}
|
||||
|
||||
.auth-link:hover {
|
||||
color: #0369A1;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.btn-google {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.5rem;
|
||||
width: 100%;
|
||||
padding: 0.625rem 1rem;
|
||||
background: #ffffff;
|
||||
color: #475569;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
border-radius: 0.5rem;
|
||||
border: 1.5px solid #E2E8F0;
|
||||
transition: all 0.2s;
|
||||
cursor: pointer;
|
||||
font-family: "Poppins", sans-serif;
|
||||
}
|
||||
|
||||
.btn-google:hover {
|
||||
border-color: #CBD5E1;
|
||||
background: #F8FAFC;
|
||||
}
|
||||
|
||||
/* ===== LOGOUT / CONFIRM PAGES ===== */
|
||||
.logout-container,
|
||||
.confirm-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
text-align: center;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.logout-icon-wrapper,
|
||||
.confirm-icon-wrapper {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.logout-icon-circle,
|
||||
.confirm-icon-circle {
|
||||
background: #F0F9FF;
|
||||
border-radius: 50%;
|
||||
padding: 1.25rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.logout-title,
|
||||
.confirm-title {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 800;
|
||||
color: #0F172A;
|
||||
margin-bottom: 0.5rem;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.logout-desc,
|
||||
.confirm-desc {
|
||||
font-size: 0.875rem;
|
||||
color: #64748B;
|
||||
margin-bottom: 1.5rem;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
[x-cloak] { display: none !important; }
|
||||
</style>
|
||||
|
||||
<div class="auth-split-container">
|
||||
<!-- LEFT PANEL - Branding (hidden on mobile) -->
|
||||
<div class="auth-left-panel">
|
||||
<div class="auth-left-content">
|
||||
<div class="auth-brand-row">
|
||||
<div class="auth-brand-icon" @onclick="NavigateToHome">
|
||||
<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<rect width="32" height="32" rx="7" fill="#0284C7"/>
|
||||
<path d="M16 9v14M9 16h14" stroke="white" stroke-width="3" stroke-linecap="round"/>
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<div class="auth-brand-name">@GlobalConsts.AppName</div>
|
||||
<div class="auth-brand-sub">Clinic Management System</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2 class="auth-welcome-title">Welcome Back to<br/>Your Clinic Hub</h2>
|
||||
<p class="auth-welcome-desc">Sign in to access your dashboard, manage patients, schedule appointments, and collaborate with your medical team.</p>
|
||||
|
||||
<div class="auth-feature-list">
|
||||
<div class="auth-feature-item">
|
||||
<div class="auth-feature-check">
|
||||
<svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="3"><path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"/></svg>
|
||||
</div>
|
||||
<div>
|
||||
<div class="auth-feature-title">Sales & Purchase</div>
|
||||
<div class="auth-feature-desc">Orders, invoices, payments & full reporting</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="auth-feature-item">
|
||||
<div class="auth-feature-check">
|
||||
<svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="3"><path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"/></svg>
|
||||
</div>
|
||||
<div>
|
||||
<div class="auth-feature-title">Patients & Vendors</div>
|
||||
<div class="auth-feature-desc">Groups, categories, contacts & history</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="auth-feature-item">
|
||||
<div class="auth-feature-check">
|
||||
<svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="3"><path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"/></svg>
|
||||
</div>
|
||||
<div>
|
||||
<div class="auth-feature-title">Inventory & Medical Records</div>
|
||||
<div class="auth-feature-desc">Products, warehouse, EMR with SOAP notes</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="auth-support-card">
|
||||
<div class="auth-support-icon">
|
||||
<svg width="20" height="20" fill="none" viewBox="0 0 24 24" stroke="white" stroke-width="1.5"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75L11.25 15 15 9.75m-3-7.036A11.959 11.959 0 013.598 6 11.99 11.99 0 003 9.749c0 5.592 3.824 10.29 9 11.623 5.176-1.332 9-6.03 9-11.622 0-1.31-.21-2.571-.598-3.751h-.152c-3.196 0-6.1-1.248-8.25-3.285z"/></svg>
|
||||
</div>
|
||||
<div>
|
||||
<div class="auth-support-title">Production Ready</div>
|
||||
<div class="auth-support-desc">Built, tested & verified — deploy out of the box</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- RIGHT PANEL - Form Area -->
|
||||
<div class="auth-right-panel">
|
||||
<div class="auth-form-wrapper">
|
||||
<!-- Mobile Brand Strip (visible only on mobile) -->
|
||||
<div class="auth-mobile-brand">
|
||||
<div class="auth-mobile-brand-icon">
|
||||
<svg width="24" height="24" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<rect width="32" height="32" rx="7" fill="#0284C7"/>
|
||||
<path d="M16 9v14M9 16h14" stroke="white" stroke-width="3" stroke-linecap="round"/>
|
||||
</svg>
|
||||
</div>
|
||||
<span class="auth-mobile-brand-name">@GlobalConsts.AppName</span>
|
||||
</div>
|
||||
|
||||
<MudCard Elevation="0" Class="auth-card pa-4">
|
||||
<MudCardContent Class="pa-6">
|
||||
@Body
|
||||
</MudCardContent>
|
||||
</MudCard>
|
||||
|
||||
<div class="auth-card-footer">
|
||||
© @DateTime.Now.Year @GlobalConsts.AppInitial. ALL RIGHTS RESERVED.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
private MudTheme _theme = new()
|
||||
{
|
||||
PaletteLight = new PaletteLight()
|
||||
{
|
||||
Primary = "#0284C7",
|
||||
Secondary = "#0EA5E9",
|
||||
AppbarBackground = "#0284C7"
|
||||
}
|
||||
};
|
||||
|
||||
private void NavigateToHome()
|
||||
{
|
||||
Navigation.NavigateTo("/", forceLoad: true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
@page "/account/confirm-email"
|
||||
@layout AuthenticationLayout
|
||||
@using Indotalent.Shared.Consts
|
||||
@using Microsoft.AspNetCore.Identity
|
||||
@using Microsoft.AspNetCore.WebUtilities
|
||||
@using System.Text
|
||||
@using Indotalent.Data.Entities
|
||||
@inject UserManager<ApplicationUser> UserManager
|
||||
@inject NavigationManager Navigation
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<PageTitle>Confirming Email - @GlobalConsts.AppInitial</PageTitle>
|
||||
|
||||
<div class="confirm-container">
|
||||
<div class="confirm-icon-wrapper">
|
||||
<div class="confirm-icon-circle">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Email"
|
||||
Style="font-size:48px; color:#0284C7;" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2 class="confirm-title">Verifying Your Account</h2>
|
||||
<p class="confirm-desc">Please wait while we validate your email address...</p>
|
||||
|
||||
<MudProgressCircular Color="Color.Primary" Indeterminate="true" Size="Size.Large" />
|
||||
</div>
|
||||
|
||||
@code {
|
||||
[SupplyParameterFromQuery] public string? userId { get; set; }
|
||||
[SupplyParameterFromQuery] public string? code { get; set; }
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(code))
|
||||
{
|
||||
Snackbar.Add("Invalid or expired confirmation link.", Severity.Error);
|
||||
Navigation.NavigateTo("/account/login");
|
||||
return;
|
||||
}
|
||||
|
||||
var user = await UserManager.FindByIdAsync(userId);
|
||||
if (user == null)
|
||||
{
|
||||
Snackbar.Add("User record not found.", Severity.Error);
|
||||
Navigation.NavigateTo("/account/login");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var decodedCode = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
|
||||
var result = await UserManager.ConfirmEmailAsync(user, decodedCode);
|
||||
await Task.Delay(500);
|
||||
if (result.Succeeded)
|
||||
{
|
||||
Snackbar.Add("Email verified successfully! You can now sign in.", Severity.Success);
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add("Verification failed. The link may have expired.", Severity.Error);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
Snackbar.Add("An error occurred during verification.", Severity.Error);
|
||||
}
|
||||
|
||||
Navigation.NavigateTo("/account/login");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
@page "/account/forgot-password"
|
||||
@layout AuthenticationLayout
|
||||
@using System.ComponentModel.DataAnnotations
|
||||
@using Indotalent.Shared.Consts
|
||||
@using Microsoft.JSInterop
|
||||
@inject IJSRuntime JSRuntime
|
||||
@inject ISnackbar Snackbar
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
<PageTitle>Forgot Password - @GlobalConsts.AppInitial</PageTitle>
|
||||
|
||||
<div class="page-header">
|
||||
<h2>Forgot Password?</h2>
|
||||
<p>Enter your email address below and we'll send you a link to reset your password.</p>
|
||||
</div>
|
||||
|
||||
<MudForm @ref="form" @bind-IsValid="@success">
|
||||
|
||||
<div class="form-label">Email Address</div>
|
||||
<MudTextField T="string"
|
||||
@bind-Value="model.Email"
|
||||
Variant="Variant.Outlined"
|
||||
Placeholder="name@example.com"
|
||||
Margin="Margin.Dense"
|
||||
Adornment="Adornment.Start"
|
||||
AdornmentIcon="@Icons.Material.Filled.Email"
|
||||
Required="true"
|
||||
Validation="@(new EmailAddressAttribute() { ErrorMessage = "Invalid email address format" })"
|
||||
For="@(() => model.Email)"
|
||||
Class="mb-6" />
|
||||
|
||||
<MudButton Variant="Variant.Filled"
|
||||
Color="Color.Primary"
|
||||
Size="Size.Large"
|
||||
FullWidth="true"
|
||||
Disabled="!success || isProcessing"
|
||||
OnClick="HandleForgotPassword"
|
||||
Style="text-transform:none; border-radius:8px; height:48px; font-weight:600;">
|
||||
@if (isProcessing)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<span class="ms-2">Sending link...</span>
|
||||
}
|
||||
else
|
||||
{
|
||||
<span>Send Reset Link</span>
|
||||
}
|
||||
</MudButton>
|
||||
</MudForm>
|
||||
|
||||
<div class="text-center mt-6">
|
||||
<span style="font-size:0.875rem; color:#64748B;">Remember your password?</span>
|
||||
<a class="auth-link" href="/account/login" style="margin-left:0.25rem;">Back to Sign In</a>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
private MudForm form = default!;
|
||||
private bool success;
|
||||
private bool isProcessing;
|
||||
private ForgotPasswordModel model = new();
|
||||
|
||||
private class ForgotPasswordModel
|
||||
{
|
||||
public string Email { get; set; } = "";
|
||||
}
|
||||
|
||||
private async Task HandleForgotPassword()
|
||||
{
|
||||
await form.Validate();
|
||||
if (!success) return;
|
||||
|
||||
isProcessing = true;
|
||||
StateHasChanged();
|
||||
|
||||
var result = await JSRuntime.InvokeAsync<ApiResponse>("apiForgotPassword", model.Email);
|
||||
|
||||
if (result.Status == 200)
|
||||
{
|
||||
Snackbar.Add("If your email is registered, a reset link has been sent.", Severity.Success);
|
||||
await Task.Delay(500);
|
||||
Navigation.NavigateTo("/account/login");
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add(result.Title ?? "Failed to send reset link", Severity.Error);
|
||||
}
|
||||
|
||||
isProcessing = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
private class ApiResponse
|
||||
{
|
||||
public int Status { get; set; }
|
||||
public string? Title { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
<script>
|
||||
window.apiForgotPassword = async (email) => {
|
||||
try {
|
||||
const response = await fetch('/api/account/forgot-password', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email })
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
return { status: 200, title: 'Success' };
|
||||
} else {
|
||||
const data = await response.json();
|
||||
let msg = 'Error processing request';
|
||||
if (data.errors && data.errors.length > 0) msg = data.errors[0];
|
||||
return { status: response.status, title: msg };
|
||||
}
|
||||
} catch (error) {
|
||||
return { status: 500, title: 'Network error' };
|
||||
}
|
||||
};
|
||||
</script>
|
||||
@@ -0,0 +1,70 @@
|
||||
using Indotalent.Data.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.WebUtilities;
|
||||
using System.Text;
|
||||
|
||||
namespace Indotalent.Features.Account.ForgotPassword.Cqrs;
|
||||
|
||||
public class ForgotPasswordRequest
|
||||
{
|
||||
public string Email { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public class ForgotPasswordResponse
|
||||
{
|
||||
public string Message { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public record ForgotPasswordCommand(ForgotPasswordRequest Data) : IRequest<ForgotPasswordResponse>;
|
||||
|
||||
public class ForgotPasswordHandler : IRequestHandler<ForgotPasswordCommand, ForgotPasswordResponse>
|
||||
{
|
||||
private readonly UserManager<ApplicationUser> _userManager;
|
||||
private readonly IEmailSender<ApplicationUser> _emailSender;
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
|
||||
public ForgotPasswordHandler(
|
||||
UserManager<ApplicationUser> userManager,
|
||||
IEmailSender<ApplicationUser> emailSender,
|
||||
IHttpContextAccessor httpContextAccessor)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_emailSender = emailSender;
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
}
|
||||
|
||||
public async Task<ForgotPasswordResponse> Handle(ForgotPasswordCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var user = await _userManager.FindByEmailAsync(request.Data.Email);
|
||||
|
||||
if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
|
||||
{
|
||||
return new ForgotPasswordResponse { Message = "If your email is registered, you will receive a reset link." };
|
||||
}
|
||||
|
||||
var code = await _userManager.GeneratePasswordResetTokenAsync(user);
|
||||
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
|
||||
|
||||
var requestHttp = _httpContextAccessor.HttpContext?.Request;
|
||||
var scheme = requestHttp?.Scheme ?? "https";
|
||||
var host = requestHttp?.Host.Value ?? "localhost:8080";
|
||||
|
||||
var callbackUrl = $"{scheme}://{host}/account/reset-password?userId={user.Id}&code={code}";
|
||||
|
||||
var message = $@"
|
||||
<div style=""font-family: Arial, sans-serif;"">
|
||||
<h3>Password Reset Request</h3>
|
||||
<p>Hello, {user.FullName}!</p>
|
||||
<p>We received a request to reset your password. Click the link below to proceed:</p>
|
||||
<p><a href=""{callbackUrl}"" style=""color: #2196F3; font-weight: bold;"">Reset Password</a></p>
|
||||
<br/>
|
||||
<p style=""font-size: 0.8em; color: #666;"">If you didn't request this, you can safely ignore this email.</p>
|
||||
<p style=""font-size: 0.8em; color: #666;"">{callbackUrl}</p>
|
||||
</div>";
|
||||
|
||||
await _emailSender.SendPasswordResetLinkAsync(user, user.Email!, message);
|
||||
|
||||
return new ForgotPasswordResponse { Message = "Reset link has been sent." };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
@page "/account/login"
|
||||
@layout AuthenticationLayout
|
||||
@using Indotalent.Shared.Consts
|
||||
@using Microsoft.JSInterop
|
||||
@using Indotalent.Infrastructure.Authentication.Identity
|
||||
@using Microsoft.Extensions.Options
|
||||
@inject IJSRuntime JSRuntime
|
||||
@inject IOptions<IdentitySettingsModel> IdentityOptions
|
||||
@inject NavigationManager Navigation
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<PageTitle>Sign In - @GlobalConsts.AppInitial</PageTitle>
|
||||
|
||||
<div class="page-header">
|
||||
<h2>Sign In</h2>
|
||||
<p>Enter your credentials to access your account</p>
|
||||
</div>
|
||||
|
||||
<MudForm @ref="form" @bind-IsValid="@success" Validation="@(new Func<EditContext, Task<bool>>(ValidateForm))" Class="w-100">
|
||||
|
||||
<div class="form-label">Email Address</div>
|
||||
<MudTextField T="string"
|
||||
@bind-Value="model.Email"
|
||||
Variant="Variant.Outlined"
|
||||
Placeholder="you@clinic.com"
|
||||
Margin="Margin.Dense"
|
||||
Adornment="Adornment.Start"
|
||||
AdornmentIcon="@Icons.Material.Filled.Email"
|
||||
Required="true"
|
||||
For="@(() => model.Email)"
|
||||
Class="mb-4" />
|
||||
|
||||
<div class="form-label-row">
|
||||
<span class="form-label">Password</span>
|
||||
<a class="forgot-link" href="/account/forgot-password">Forgot password?</a>
|
||||
</div>
|
||||
<MudTextField T="string"
|
||||
@bind-Value="model.Password"
|
||||
Variant="Variant.Outlined"
|
||||
Placeholder="Enter your password"
|
||||
Margin="Margin.Dense"
|
||||
Adornment="Adornment.Start"
|
||||
AdornmentIcon="@Icons.Material.Filled.Lock"
|
||||
InputType="@(showPassword ? InputType.Text : InputType.Password)"
|
||||
AdornmentEndIcon="@(showPassword? Icons.Material.Filled.Visibility : Icons.Material.Filled.VisibilityOff)"
|
||||
OnAdornmentEndClick="() => showPassword = !showPassword"
|
||||
Required="true"
|
||||
For="@(() => model.Password)"
|
||||
Class="mb-4" />
|
||||
|
||||
<div class="remember-row">
|
||||
<MudCheckBox T="bool"
|
||||
@bind-Value="rememberMe"
|
||||
Label="Remember me"
|
||||
Color="Color.Primary"
|
||||
Dense="true" />
|
||||
</div>
|
||||
|
||||
<MudButton Variant="Variant.Filled"
|
||||
Color="Color.Primary"
|
||||
Size="Size.Large"
|
||||
FullWidth="true"
|
||||
Disabled="!success || isProcessing"
|
||||
OnClick="HandleLogin"
|
||||
Style="text-transform:none; border-radius:8px; height:48px; font-weight:600;">
|
||||
@if (isProcessing)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<span class="ms-2">Signing in...</span>
|
||||
}
|
||||
else
|
||||
{
|
||||
<span>Sign In</span>
|
||||
}
|
||||
</MudButton>
|
||||
|
||||
@if (IdentityOptions.Value.SsoFirebase.IsUsed)
|
||||
{
|
||||
<div class="divider-or"><span>Or continue with</span></div>
|
||||
|
||||
<MudButton Variant="Variant.Outlined"
|
||||
FullWidth="true"
|
||||
Size="Size.Large"
|
||||
Disabled="isProcessing"
|
||||
OnClick="HandleFirebaseGoogleLogin"
|
||||
StartIcon="@Icons.Custom.Brands.Google"
|
||||
Style="text-transform:none; border-radius:8px; background-color:white; height:40px; border:1.5px solid #E2E8F0; font-weight:500;">
|
||||
Sign in with Google
|
||||
</MudButton>
|
||||
}
|
||||
</MudForm>
|
||||
|
||||
<div class="text-center mt-6">
|
||||
<span style="font-size:0.875rem; color:#64748B;">Don't have an account?</span>
|
||||
<a class="auth-link" href="/account/register" style="margin-left:0.25rem;">Create one</a>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
private MudForm form = default!;
|
||||
private bool success;
|
||||
private bool isProcessing;
|
||||
private bool showPassword;
|
||||
private bool rememberMe;
|
||||
private LoginModel model = new();
|
||||
|
||||
private async Task<bool> ValidateForm(EditContext context) => await Task.FromResult(true);
|
||||
|
||||
private async Task HandleLogin()
|
||||
{
|
||||
await form.Validate();
|
||||
if (!success) return;
|
||||
isProcessing = true;
|
||||
StateHasChanged();
|
||||
|
||||
var result = await JSRuntime.InvokeAsync<ApiJSRuntimeResponse>("apiAccountSignIn", model.Email, model.Password, rememberMe);
|
||||
ProcessLoginResult(result);
|
||||
}
|
||||
|
||||
private async Task HandleFirebaseGoogleLogin()
|
||||
{
|
||||
isProcessing = true;
|
||||
StateHasChanged();
|
||||
|
||||
var firebaseUser = await JSRuntime.InvokeAsync<FirebaseUserResponse>("signInWithGoogle");
|
||||
|
||||
if (firebaseUser == null || string.IsNullOrEmpty(firebaseUser.Email))
|
||||
{
|
||||
Snackbar.Add("Google Sign-In failed or cancelled.", Severity.Error);
|
||||
isProcessing = false;
|
||||
return;
|
||||
}
|
||||
|
||||
var checkResult = await JSRuntime.InvokeAsync<ActiveCheckResponse>("apiCheckActiveUser", firebaseUser.Email);
|
||||
bool openForPublic = IdentityOptions.Value.SsoFirebase.OpenForPublic;
|
||||
|
||||
if (checkResult.Exists)
|
||||
{
|
||||
if (checkResult.IsActive)
|
||||
{
|
||||
await ExecuteSsoSignIn(firebaseUser.Email);
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add("Account is registered but not active.", Severity.Warning);
|
||||
isProcessing = false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var registerResult = await JSRuntime.InvokeAsync<ApiJSRuntimeResponse>(
|
||||
"apiAccountSignUpSso",
|
||||
firebaseUser.Email,
|
||||
firebaseUser.Email,
|
||||
openForPublic
|
||||
);
|
||||
|
||||
if (registerResult.Status == 200)
|
||||
{
|
||||
if (openForPublic)
|
||||
{
|
||||
await ExecuteSsoSignIn(firebaseUser.Email);
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add("Registration successful. Please wait for admin approval.", Severity.Info);
|
||||
isProcessing = false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add("Failed to auto-register account.", Severity.Error);
|
||||
isProcessing = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ExecuteSsoSignIn(string email)
|
||||
{
|
||||
var result = await JSRuntime.InvokeAsync<ApiJSRuntimeResponse>("apiAccountSsoSignIn", email);
|
||||
ProcessLoginResult(result);
|
||||
}
|
||||
|
||||
private void ProcessLoginResult(ApiJSRuntimeResponse result)
|
||||
{
|
||||
if (result.Status == 200)
|
||||
{
|
||||
Snackbar.Add(result.Title ?? "Login successful!", Severity.Success);
|
||||
Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(500);
|
||||
Navigation.NavigateTo("/home", forceLoad: true);
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add(result.Title ?? "Sign in failed.", Severity.Error);
|
||||
isProcessing = false;
|
||||
}
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
private class ApiJSRuntimeResponse { public int? Status { get; set; } public string? Title { get; set; } public string? Message { get; set; } }
|
||||
private class FirebaseUserResponse { public string? Email { get; set; } }
|
||||
private class ActiveCheckResponse { public bool Exists { get; set; } public bool IsActive { get; set; } }
|
||||
private class LoginModel { public string Email { get; set; } = ""; public string Password { get; set; } = ""; }
|
||||
}
|
||||
|
||||
<script>
|
||||
window.apiAccountSignIn = async (email, password, rememberMe) => {
|
||||
try {
|
||||
const response = await fetch('/api/account/signin', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, password, rememberMe }),
|
||||
credentials: 'include'
|
||||
});
|
||||
const result = await response.json();
|
||||
return { status: response.status, title: result.title };
|
||||
} catch (error) {
|
||||
return { status: 500, title: 'Network error' };
|
||||
}
|
||||
};
|
||||
|
||||
window.apiCheckActiveUser = async (email) => {
|
||||
try {
|
||||
const response = await fetch(`/api/account/active-user-exists?email=${encodeURIComponent(email)}`);
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
return { exists: false, isActive: false };
|
||||
}
|
||||
};
|
||||
|
||||
window.apiAccountSignUpSso = async (email, fullName, isOpenForPublic) => {
|
||||
try {
|
||||
const response = await fetch('/api/account/signup', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
email: email,
|
||||
fullName: fullName,
|
||||
password: 'SSO_AUTO_GENERATED_PASSWORD_123!',
|
||||
isActive: isOpenForPublic,
|
||||
emailConfirmed: isOpenForPublic
|
||||
})
|
||||
});
|
||||
const result = await response.json();
|
||||
return { status: response.status, message: result.message };
|
||||
} catch (error) {
|
||||
return { status: 500 };
|
||||
}
|
||||
};
|
||||
|
||||
window.apiAccountSsoSignIn = async (email) => {
|
||||
try {
|
||||
const response = await fetch(`/api/account/signin-sso?email=${encodeURIComponent(email)}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include'
|
||||
});
|
||||
const result = await response.json();
|
||||
return { status: response.status, title: result.title };
|
||||
} catch (error) {
|
||||
return { status: 500, title: 'SSO Network error' };
|
||||
}
|
||||
};
|
||||
</script>
|
||||
@@ -0,0 +1,74 @@
|
||||
using Indotalent.ConfigFrontEnd.Service;
|
||||
using Indotalent.Data.Entities;
|
||||
using Indotalent.Infrastructure.Authentication.Identity;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Indotalent.Features.Account.Login.Cqrs;
|
||||
|
||||
public class LoginRequest
|
||||
{
|
||||
public string Email { get; set; } = string.Empty;
|
||||
public string Password { get; set; } = string.Empty;
|
||||
public bool RememberMe { get; set; }
|
||||
}
|
||||
|
||||
public class LoginResponse
|
||||
{
|
||||
public bool Succeeded { get; set; }
|
||||
public string Message { get; set; } = string.Empty;
|
||||
public bool IsNotAllowed { get; set; }
|
||||
public string? Token { get; set; }
|
||||
public string? RefreshToken { get; set; }
|
||||
}
|
||||
|
||||
public record LoginCommand(LoginRequest Data) : IRequest<LoginResponse>;
|
||||
|
||||
public class LoginHandler : IRequestHandler<LoginCommand, LoginResponse>
|
||||
{
|
||||
private readonly SignInManager<ApplicationUser> _signInManager;
|
||||
private readonly UserManager<ApplicationUser> _userManager;
|
||||
private readonly JwtSettingsModel _jwtSettings;
|
||||
|
||||
public LoginHandler(
|
||||
SignInManager<ApplicationUser> signInManager,
|
||||
UserManager<ApplicationUser> userManager,
|
||||
IOptions<JwtSettingsModel> jwtSettings)
|
||||
{
|
||||
_signInManager = signInManager;
|
||||
_userManager = userManager;
|
||||
_jwtSettings = jwtSettings.Value;
|
||||
}
|
||||
|
||||
public async Task<LoginResponse> Handle(LoginCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var user = await _userManager.FindByEmailAsync(request.Data.Email);
|
||||
if (user == null) return new LoginResponse { Succeeded = false, Message = "Invalid credentials" };
|
||||
|
||||
var result = await _signInManager.PasswordSignInAsync(user, request.Data.Password, request.Data.RememberMe, false);
|
||||
|
||||
if (result.Succeeded)
|
||||
{
|
||||
var token = JwtService.GenerateNewJwt(user, _jwtSettings);
|
||||
|
||||
var refreshToken = Guid.NewGuid().ToString().Replace("-", "");
|
||||
|
||||
user.RefreshToken = refreshToken;
|
||||
user.LastLoginAt = DateTime.Now;
|
||||
await _userManager.UpdateAsync(user);
|
||||
|
||||
return new LoginResponse
|
||||
{
|
||||
Succeeded = true,
|
||||
Message = "Login successful",
|
||||
Token = token,
|
||||
RefreshToken = refreshToken
|
||||
};
|
||||
}
|
||||
|
||||
return new LoginResponse { Succeeded = false, Message = "Invalid credentials" };
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
@page "/account/logout"
|
||||
@layout AuthenticationLayout
|
||||
|
||||
@using Indotalent.Shared.Consts
|
||||
@using Microsoft.JSInterop
|
||||
@inject IJSRuntime JSRuntime
|
||||
@inject NavigationManager Navigation
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<PageTitle>Sign Out - @GlobalConsts.AppInitial</PageTitle>
|
||||
|
||||
<div class="logout-container">
|
||||
<div class="logout-icon-wrapper">
|
||||
<div class="logout-icon-circle">
|
||||
<MudIcon Icon="@Icons.Material.Filled.ExitToApp"
|
||||
Style="font-size:48px; color:#0284C7;" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2 class="logout-title">Sign Out</h2>
|
||||
<p class="logout-desc">Are you sure you want to sign out of your account?</p>
|
||||
|
||||
<MudButton Variant="Variant.Filled"
|
||||
Size="Size.Large"
|
||||
FullWidth="true"
|
||||
Disabled="@isLoggingOut"
|
||||
OnClick="Logout"
|
||||
Style="text-transform:none; border-radius:8px; background-color:#0284C7; color:white; height:48px; font-weight:700;">
|
||||
@if (isLoggingOut)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<span class="ms-2">Processing...</span>
|
||||
}
|
||||
else
|
||||
{
|
||||
<span>Sign Out</span>
|
||||
}
|
||||
</MudButton>
|
||||
|
||||
<MudButton Variant="Variant.Text"
|
||||
Class="mt-4"
|
||||
FullWidth="true"
|
||||
Href="/"
|
||||
Disabled="@isLoggingOut"
|
||||
Style="text-transform:none; color:#94A3B8; font-weight:600;">
|
||||
Cancel
|
||||
</MudButton>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
private bool isLoggingOut;
|
||||
|
||||
private async Task Logout()
|
||||
{
|
||||
isLoggingOut = true;
|
||||
StateHasChanged();
|
||||
|
||||
var result = await JSRuntime.InvokeAsync<ApiJSRuntimeResponse>("apiAccountLogout");
|
||||
|
||||
if (result.Status == 200)
|
||||
{
|
||||
Snackbar.Add("Successfully signed out!", Severity.Success);
|
||||
await Task.Delay(500);
|
||||
Navigation.NavigateTo("/", forceLoad: true);
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add(result.Title ?? "Failed to logout.", Severity.Error);
|
||||
await Task.Delay(500);
|
||||
}
|
||||
|
||||
isLoggingOut = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
private class ApiJSRuntimeResponse
|
||||
{
|
||||
public int? Status { get; set; }
|
||||
public string? Title { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
<script>
|
||||
window.apiAccountLogout = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/account/signout', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
credentials: 'include'
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error('Unknown error occurred');
|
||||
}
|
||||
return { status: 200, title: 'Success user logout' };
|
||||
} catch (error) {
|
||||
return { status: 500, title: 'Server / Network error' };
|
||||
}
|
||||
};
|
||||
</script>
|
||||
@@ -0,0 +1,181 @@
|
||||
@page "/account/register"
|
||||
@layout AuthenticationLayout
|
||||
|
||||
@using Indotalent.Shared.Consts
|
||||
@using Microsoft.JSInterop
|
||||
@inject IJSRuntime JSRuntime
|
||||
@inject ISnackbar Snackbar
|
||||
@inject NavigationManager Navigation
|
||||
@inject IConfiguration Configuration
|
||||
|
||||
<PageTitle>Sign Up - @GlobalConsts.AppInitial</PageTitle>
|
||||
|
||||
<div class="page-header">
|
||||
<h2>Sign Up</h2>
|
||||
<p>Please register your account</p>
|
||||
</div>
|
||||
|
||||
<MudForm @ref="form" @bind-IsValid="@success" Validation="@(new Func<EditContext, Task<bool>>(ValidateForm))">
|
||||
|
||||
<div class="form-label">Full Name</div>
|
||||
<MudTextField T="string"
|
||||
@bind-Value="model.FullName"
|
||||
Variant="Variant.Outlined"
|
||||
Placeholder="Enter your full name"
|
||||
Margin="Margin.Dense"
|
||||
Adornment="Adornment.Start"
|
||||
AdornmentIcon="@Icons.Material.Filled.Person"
|
||||
Required="true"
|
||||
For="@(() => model.FullName)"
|
||||
Class="mb-4" />
|
||||
|
||||
<div class="form-label">Email Address</div>
|
||||
<MudTextField T="string"
|
||||
@bind-Value="model.Email"
|
||||
Variant="Variant.Outlined"
|
||||
Placeholder="Enter your email"
|
||||
Margin="Margin.Dense"
|
||||
Adornment="Adornment.Start"
|
||||
AdornmentIcon="@Icons.Material.Filled.Email"
|
||||
Required="true"
|
||||
For="@(() => model.Email)"
|
||||
Class="mb-4" />
|
||||
|
||||
<div class="form-label">Password</div>
|
||||
<MudTextField T="string"
|
||||
@bind-Value="model.Password"
|
||||
Variant="Variant.Outlined"
|
||||
Placeholder="Create a password"
|
||||
Margin="Margin.Dense"
|
||||
InputType="@(showPassword ? InputType.Text : InputType.Password)"
|
||||
Adornment="Adornment.Start"
|
||||
AdornmentIcon="@Icons.Material.Filled.Lock"
|
||||
AdornmentEndIcon="@(showPassword? Icons.Material.Filled.Visibility : Icons.Material.Filled.VisibilityOff)"
|
||||
OnAdornmentEndClick="() => showPassword = !showPassword"
|
||||
Required="true"
|
||||
For="@(() => model.Password)"
|
||||
Class="mb-6" />
|
||||
|
||||
<MudButton Variant="Variant.Filled"
|
||||
Color="Color.Primary"
|
||||
Size="Size.Large"
|
||||
FullWidth="true"
|
||||
Disabled="!success || isProcessing"
|
||||
OnClick="HandleRegister"
|
||||
Style="text-transform:none; border-radius:8px; height:48px; font-weight:600;">
|
||||
@if (isProcessing)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<span class="ms-2">Processing...</span>
|
||||
}
|
||||
else
|
||||
{
|
||||
<span>Create Account</span>
|
||||
}
|
||||
</MudButton>
|
||||
</MudForm>
|
||||
|
||||
<div class="text-center mt-6">
|
||||
<span style="font-size:0.875rem; color:#64748B;">Already have an account?</span>
|
||||
<a class="auth-link" href="/account/login" style="margin-left:0.25rem;">Sign In</a>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
private MudForm form = default!;
|
||||
private bool success;
|
||||
private bool isProcessing;
|
||||
private bool showPassword;
|
||||
|
||||
private RegisterModel model = new();
|
||||
|
||||
private class RegisterModel
|
||||
{
|
||||
public string FullName { get; set; } = "";
|
||||
public string Email { get; set; } = "";
|
||||
public string Password { get; set; } = "";
|
||||
}
|
||||
|
||||
private async Task<bool> ValidateForm(EditContext context)
|
||||
{
|
||||
return await Task.FromResult(true);
|
||||
}
|
||||
|
||||
private async Task HandleRegister()
|
||||
{
|
||||
await form.Validate();
|
||||
|
||||
if (!success) return;
|
||||
|
||||
isProcessing = true;
|
||||
StateHasChanged();
|
||||
|
||||
var result = await JSRuntime.InvokeAsync<ApiJSRuntimeResponse>("apiAccountRegister", model.FullName, model.Email, model.Password);
|
||||
|
||||
if (result.Status == 200)
|
||||
{
|
||||
var requireConfirmation = Configuration.GetValue<bool>("IdentitySettings:SignIn:RequireConfirmedAccount");
|
||||
|
||||
if (requireConfirmation)
|
||||
{
|
||||
Snackbar.Add("Registration successful! Please check your email to confirm your account.", Severity.Info);
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add("Registration successful! You can now sign in.", Severity.Success);
|
||||
}
|
||||
|
||||
await Task.Delay(500);
|
||||
Navigation.NavigateTo("/account/login");
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add(result.Title ?? "Registration failed", Severity.Error);
|
||||
}
|
||||
|
||||
isProcessing = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
private class ApiJSRuntimeResponse
|
||||
{
|
||||
public int? Status { get; set; }
|
||||
public string? Title { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
<script>
|
||||
window.apiAccountRegister = async (fullName, email, password) => {
|
||||
try {
|
||||
const response = await fetch('/api/account/signup', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({ fullName, email, password })
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (response.ok) {
|
||||
return { status: 200, title: 'Success account registration' };
|
||||
} else {
|
||||
let errorMessage = data.title || data.message || 'Registration failed';
|
||||
|
||||
if (data.errors) {
|
||||
if (Array.isArray(data.errors) && data.errors.length > 0) {
|
||||
errorMessage = data.errors[0];
|
||||
} else if (typeof data.errors === 'object') {
|
||||
const firstKey = Object.keys(data.errors)[0];
|
||||
if (firstKey) {
|
||||
errorMessage = data.errors[firstKey][0];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { status: response.status, title: errorMessage };
|
||||
}
|
||||
} catch (error) {
|
||||
return { status: 500, title: 'Server / Network error' };
|
||||
}
|
||||
};
|
||||
</script>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user