using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using System.Text; using System.Threading.Tasks; using Microsoft.IdentityModel.Tokens; using MisIngredientesVue.Core.Models; using Stripe; namespace MisIngredientesVue.Core.Services { public interface IAuthenticationTokenService { Task GetTokenForUser(string tenantId, User user, InvoicingInfo invoicingInfo, bool isApiKey = false); AuthenticationToken GetTokenForSeller(Seller seller); } public class AuthenticationTokenService : IAuthenticationTokenService { private readonly ISettingsService _settingsService; private readonly IBillingService _billingService; public static string TOKEN_VERSION = "3"; public AuthenticationTokenService(ISettingsService settingsService, IBillingService billingService) { _settingsService = settingsService; _billingService = billingService; } public AuthenticationToken GetTokenForSeller(Seller seller) { //TODO: Store the token/user to verify if the user is already logged in var expires = DateTime.UtcNow.AddYears(1); var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes("this is my custom Secret key for authnetication"); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, seller.Email), new Claim("FirstName", seller.FirstName), new Claim("LastName", seller.LastName), new Claim("ShouldResetPassword", seller.ResetPassword ? "1" : "0"), //TODO new Claim("UserId", seller.Id.ToString()) }), Expires = expires, SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); return new AuthenticationToken() { Token = tokenHandler.WriteToken(token), Expires = expires }; } public async Task GetTokenForUser(string tenantId, User user, InvoicingInfo invoicingInfo, bool isApiKey = false) { //TODO: Store the token/user to verify if the user is already logged in var companyLogoUrl = await _settingsService.GetSettingValue(tenantId, ClientSettingType.CompanyLogoUrl); var companyName = await _settingsService.GetSettingValue(tenantId, ClientSettingType.CompanyName); var subscriptionLevel = SubscriptionLevelType.Free; if (!string.IsNullOrEmpty(user.StripePlanId)) //StripePlanId = PlanType { var planType = (PlanType)Convert.ToInt32(user.StripePlanId); if (planType == PlanType.FreeMonthly || planType == PlanType.FreeYearly) subscriptionLevel = SubscriptionLevelType.Free; if (planType == PlanType.BasicMonthly || planType == PlanType.BasicYearly) subscriptionLevel = SubscriptionLevelType.Basic; if (planType == PlanType.StartupMonthly || planType == PlanType.StartupYearly) subscriptionLevel = SubscriptionLevelType.Startup; if (planType == PlanType.EnterpriseMonthly || planType == PlanType.EnterpriseYearly) subscriptionLevel = SubscriptionLevelType.Enterprise; } if (tenantId == "test" || tenantId == "demo") subscriptionLevel = SubscriptionLevelType.Enterprise; var expires = DateTime.UtcNow.AddYears(1); var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes("this is my custom Secret key for authnetication"); var defaultPaymentMethodId = (tenantId == "test" || tenantId == "demo") ? "test" : (!string.IsNullOrEmpty(user.StripeCustomerId) ? await _billingService.GetDefaultPaymentMethodId(user.StripeCustomerId) : ""); var claims = new Claim[] { new Claim(ClaimTypes.Name, user.Email), new Claim("Version", TOKEN_VERSION), new Claim("IsApiKey", isApiKey ? "1" : "0"), //Propiedades específicas del usuario o que nunca cambiarán new Claim("TenantId", tenantId), new Claim("FirstName", user.FirstName ?? ""), new Claim("LastName", user.LastName ?? ""), new Claim("IsClient", user.IsClient ? "1" : "0"), new Claim("ClientOrSupplierId", user.ClientOrSupplierId?.ToString() ?? "-1"), new Claim("StripeCustomerId", user.StripeCustomerId ?? ""), new Claim("UserRole", ((int)user.Role).ToString() ?? ""), new Claim("ProfileImgSrc", user.ProfileImgSrc ?? $"/api/account/profileimg/{tenantId}_{user.Id}"), new Claim("TrialPeriodEnd", user.TrialPeriodEnd.HasValue ? user.TrialPeriodEnd.Value.ToString("yyyy-MM-ddTHH:mm:ss") : ""), new Claim("ShouldResetPassword", user.ResetPassword ? "1" : "0"), new Claim("UserId", user.Id.ToString() ?? ""), new Claim("AssignedBranches", string.Join(",", user.ClientBranchIds ?? new int[] { })), new Claim("Permissions", string.Join(",", user.CustomRole?.Permissions ?? "")), //Propiedades globales que pueden cambiar entre usuarios new Claim("DefaultPaymentMethodId", defaultPaymentMethodId ?? ""), new Claim("SubscriptionLevel", ((int)subscriptionLevel).ToString()), new Claim("SubscriptionId", user.StripeSubscriptionId ?? ""), new Claim("SubSubscriptionId", user.StripeSubSubscriptionId ?? ""), new Claim("PlanId", user.StripePlanId ?? ""), //StripePlanId = PlanType new Claim("CompanyLogoImgSrc", companyLogoUrl ?? ""), new Claim("CompanyName", companyName ?? ""), new Claim("Invoicing.InfoAvailable", !string.IsNullOrEmpty(invoicingInfo.Rfc) ? "1" : "0"), new Claim("Invoicing.Name", invoicingInfo.Name ?? ""), new Claim("Invoicing.Rfc", invoicingInfo.Rfc ?? ""), new Claim("Invoicing.FiscalReg", invoicingInfo.RegFiscal ?? ""), new Claim("Invoicing.FullAddress", $"{invoicingInfo.Street} {invoicingInfo.NumExt} {invoicingInfo.NumInt} {invoicingInfo.Col} {invoicingInfo.Mun} {invoicingInfo.State} {invoicingInfo.Zip}"), }; var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = expires, SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); return new AuthenticationToken() { Claims = claims, Token = tokenHandler.WriteToken(token), Expires = expires, IsClient = user.IsClient }; } } }