This commit is contained in:
mmrbnjd
2024-04-17 15:49:34 +03:30
parent f829d80851
commit 3f0a37a08b
27 changed files with 1253 additions and 79 deletions

View File

@@ -0,0 +1,239 @@
using Back.Common;
using Back.Data.Contracts;
using Back.Data.Models;
using Microsoft.EntityFrameworkCore;
namespace Back.Services
{
public class CheckPermission
{
private readonly IAsyncRepository<PermissionPeriod> _repoPermissionPeriod;
private readonly IAsyncRepository<PermissionUser> _repoPermissionUser;
public CheckPermission(IAsyncRepository<PermissionPeriod> repoPermissionPeriod
,IAsyncRepository<PermissionUser> repoPermissionUser)
{
_repoPermissionPeriod = repoPermissionPeriod;
_repoPermissionUser = repoPermissionUser;
}
private async Task<bool> AllowPermissionInCompany(int CompanyID,int PermissionID,int Allowednumber = 1)
{
PermissionPeriod? permissionPeriod = _repoPermissionPeriod
.Get(w => w.CompanyID == CompanyID && w.PermissionID == PermissionID && (!w.IsLocked.HasValue || !w.IsLocked.Value))
.FirstOrDefault();
if (permissionPeriod == null)
return false;
//تعداد
if (permissionPeriod.CalculationTypeID == 1)
{
if (permissionPeriod.RemainingAmount < Allowednumber)
return false;
//permissionPeriod.RemainingAmount -= 1;
}
//تا تاریخ
else if (permissionPeriod.CalculationTypeID == 3)
{
string date = $"{permissionPeriod.RemainingAmount.ToString().Substring(0, 4)}/{permissionPeriod.RemainingAmount.ToString().Substring(4, 2)}/{permissionPeriod.RemainingAmount.ToString().Substring(6, 2)}";
DateTime dateTime = date.ToMiladi();
if (DateTime.Now > dateTime)
return false;
}
return await _repoPermissionPeriod.UpdateAsync(permissionPeriod);
}
public async Task<bool> AllowPermission(int UserID,int CompanyID, int PermissionID)
{
return await _repoPermissionUser
.Get(w => w.RolUser.UserID == UserID && w.RolUser.CompanyID == CompanyID && w.PermissionID==PermissionID)
.AnyAsync();
}
public async Task<bool> ExtensionofAccess(int CompanyID, int PermissionID, string value)
{
PermissionPeriod? permissionPeriod = _repoPermissionPeriod
.Get(w => w.CompanyID == CompanyID && w.PermissionID == PermissionID
&& (!w.IsLocked.HasValue || !w.IsLocked.Value))
.FirstOrDefault();
//تعداد
if (permissionPeriod.CalculationTypeID == 1)
{
if (permissionPeriod.RemainingAmount < 0)
permissionPeriod.RemainingAmount = Convert.ToInt32(value);
permissionPeriod.RemainingAmount += Convert.ToInt32(value);
}
try
{
return await _repoPermissionPeriod.UpdateAsync(permissionPeriod);
//SysLog log = new SysLog()
//{
// TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier,
// Datetime = DateTime.Now.ConvertMiladiToShamsi(),
// Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/ExtensionofAccess",
// Value = $"{permissionPeriod.RemainingAmount - Convert.ToInt32(value)}+({value})={permissionPeriod.RemainingAmount}",
// Route = _httpContextAccessor.HttpContext.Request.Path,
// Type = "User"
//};
//_contextMongodb.InsertItem(log);
}
catch (Exception ex)
{
//SysLog log = new SysLog()
//{
// TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier,
// Datetime = DateTime.Now.ConvertMiladiToShamsi(),
// Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/ExtensionofAccess",
// Value = ex.Message,
// Route = _httpContextAccessor.HttpContext.Request.Path,
// Type = "catch"
//};
//_contextMongodb.InsertItem(log);
return false;
}
}
//--------Customer---------
#region Customer
public async Task<bool> AllowAddCustomerInCompany(int CompanyID, int Allowednumber = 1)
{
//مشتری
int PermissionID = 5;
return await AllowPermissionInCompany(CompanyID, PermissionID,Allowednumber);
}
public async Task<bool> AllowSYSGetCustomer(int UserID, int CompanyID)
{
//مشتری
int PermissionID = 5;
return await AllowPermission(UserID, CompanyID, PermissionID);
}
public async Task<bool> AllowSYSAddCustomer(int UserID, int CompanyID)
{
//مشتری
int PermissionID = 7;
return await AllowPermission(UserID,CompanyID, PermissionID);
}
public async Task<bool> AllowSYSDeleteCustomer(int UserID, int CompanyID)
{
//مشتری
int PermissionID = 9;
return await AllowPermission(UserID, CompanyID, PermissionID);
}
public async Task<bool> AllowSYSUpdateCustomer(int UserID, int CompanyID)
{
//مشتری
int PermissionID = 8;
return await AllowPermission(UserID, CompanyID, PermissionID);
}
#endregion
//-----------COD-----------
#region COD
public async Task<bool> AllowAddCODInCompany(int CompanyID,int Allowednumber=1)
{
//کالا
int PermissionID = 4;
return await AllowPermissionInCompany(CompanyID, PermissionID,Allowednumber);
}
public async Task<bool> AllowSYSGetCOD(int UserID, int CompanyID)
{
//کالا
int PermissionID = 4;
return await AllowPermission(UserID, CompanyID, PermissionID);
}
public async Task<bool> AllowSYSAddCOD(int UserID, int CompanyID)
{
//کالا
int PermissionID = 10;
return await AllowPermission(UserID, CompanyID, PermissionID);
}
public async Task<bool> AllowSYSDeleteCOD(int UserID, int CompanyID)
{
//کالا
int PermissionID = 12;
return await AllowPermission(UserID, CompanyID, PermissionID);
}
public async Task<bool> AllowSYSUpdateCOD(int UserID, int CompanyID)
{
//کالا
int PermissionID = 11;
return await AllowPermission(UserID, CompanyID, PermissionID);
}
#endregion
//--------Invoice---------
#region Invoice
public async Task<bool> AllowAddInvoiceInCompany(int CompanyID, int Allowednumber = 1)
{
int PermissionID = 3;
return await AllowPermissionInCompany(CompanyID, PermissionID, Allowednumber);
}
public async Task<bool> AllowSYSGetInvoice(int UserID, int CompanyID)
{
int PermissionID = 3;
return await AllowPermission(UserID, CompanyID, PermissionID);
}
public async Task<bool> AllowSYSAddInvoice(int UserID, int CompanyID)
{
int PermissionID = 13;
return await AllowPermission(UserID, CompanyID, PermissionID);
}
public async Task<bool> AllowSYSDeleteInvoice(int UserID, int CompanyID)
{
int PermissionID = 15;
return await AllowPermission(UserID, CompanyID, PermissionID);
}
public async Task<bool> AllowSYSUpdateInvoice(int UserID, int CompanyID)
{
int PermissionID = 14;
return await AllowPermission(UserID, CompanyID, PermissionID);
}
#endregion
#region TaxPayer
public async Task<bool> AllowSendTaxPayerInCompany(int CompanyID)
{
int PermissionID = 16;
return await AllowPermissionInCompany(CompanyID, PermissionID);
}
public async Task<bool> AllowSYSGetTaxPayer(int UserID, int CompanyID)
{
int PermissionID = 16;
return await AllowPermission(UserID, CompanyID, PermissionID);
}
public async Task<bool> AllowSYSSendTaxPayer(int UserID, int CompanyID)
{
int PermissionID = 16;
return await AllowPermission(UserID, CompanyID, PermissionID);
}
#endregion
}
}

View File

@@ -9,10 +9,18 @@ namespace Back.Services
{
private readonly IAsyncRepository<VerificationCode> _verificationCodeRepo;
private readonly IAsyncRepository<Ticket> _ticket;
public ServValidatinMsg(IAsyncRepository<VerificationCode> verificationCodeRepo, IAsyncRepository<Ticket> ticket)
private readonly IAsyncRepository<User> _UserRepo;
private readonly IAsyncRepository<Company> _CompanyRepo;
private readonly servSendMsg _servSendMsg;
public ServValidatinMsg(IAsyncRepository<VerificationCode> verificationCodeRepo
, IAsyncRepository<Ticket> ticket, IAsyncRepository<User> UserRepo
, IAsyncRepository<Company> CompanyRepo, servSendMsg servSendMsg)
{
_verificationCodeRepo = verificationCodeRepo;
_ticket = ticket;
_UserRepo = UserRepo;
_CompanyRepo = CompanyRepo;
_servSendMsg = servSendMsg;
}
public async Task<VerificationCode> GetCodeByPrm(string Prm)
{
@@ -37,6 +45,26 @@ namespace Back.Services
}
return false;
}
public async Task<bool> SubmittedCompanyRegistration(VerificationCode code)
{
var user = await _UserRepo.Get(w => w.ID == Convert.ToInt32(code.val) && !w.IsActive).FirstOrDefaultAsync();
var company = await _CompanyRepo.Get(w => w.ID == Convert.ToInt32(code.prm) && !w.IsActive).FirstOrDefaultAsync();
if (user != null && company != null)
{
user.IsActive = true;
if (await _UserRepo.UpdateAsync(user) != null)
{
company.IsActive = true;
if (await _CompanyRepo.UpdateAsync(company))
{
_servSendMsg.SuccessfulRegistration(user.Mobile, $"{user.Mobile};{user.Mobile}");
return true;
}
}
}
return false;
}
public async Task<int> GenerateCode(VerificationCode code)
{
code.Code = Random.Shared.Next(1000, 9000);

View File

@@ -0,0 +1,112 @@
using Back.Common;
using Back.Data.Contracts;
using Back.Data.Models;
using Microsoft.EntityFrameworkCore;
using Shared.DTOs;
namespace Back.Services
{
public class servCompany
{
private readonly IAsyncRepository<RolUser> _repoRolUser;
private readonly IAsyncRepository<Company> _repoCompany;
//private readonly servSendMsg _servSendMsg;
public servCompany(IAsyncRepository<RolUser> repoRolUser, IAsyncRepository<Company> repoCompany)
{
_repoCompany = repoCompany;
_repoRolUser = repoRolUser;
}
public async Task<bool> ExsistCompanyByComoanyIDandUserID(int ComoanyID, int UserID,bool InAdmin=false)
{
var res= _repoRolUser.Get(w => w.CompanyID == ComoanyID && w.UserID == UserID && w.Company.IsActive);
if (InAdmin)
res = res.Where( w=> w.IsAdmin);
return await res.AnyAsync();
}
public async Task<CompanyDTO?> GetCompany(int ComoanyID)
{
return await _repoCompany.Get(w => w.ID == ComoanyID && w.IsActive)
.Select(s=>new CompanyDTO()
{
BranchID = s.BranchID,
EconomicCode = s.EconomicCode,
ID = s.ID,
Email = s.Email,
Logo= s.Logo==null ?null: System.Text.Encoding.UTF8.GetString(s.Logo) ,
Mobile = s.Mobile,
Name = s.Name,
Phone = s.Phone,
PrivateKey= s.PrivateKey,
UniqeMemory = s.UniqeMemory
}).FirstOrDefaultAsync();
}
public async Task<Company?> GetCompanyOrg(int ComoanyID,bool IsActive=true)
{
var inv = _repoCompany.Get(w => w.ID == ComoanyID);
if (IsActive)
inv= inv.Where(w=>w.IsActive);
return await inv.FirstOrDefaultAsync();
}
public async Task<Company?> GetCompanyOrgByMobileAndCompanynotActive(string Mobile)
{
var inv = _repoCompany.Get(w => w.Mobile == Mobile && !w.IsActive);
return await inv.FirstOrDefaultAsync();
}
public async Task<Company> AddORUpdateCompany(Company item)
{
try
{
//SysLog log = new SysLog()
//{
// TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier,
// Datetime = DateTime.Now.ConvertMiladiToShamsi(),
// Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/AddORUpdateCompany",
// Value = "*" + JsonConvert.SerializeObject(item),
// Route = _httpContextAccessor.HttpContext.Request.Path,
// Type = "User"
//};
//_contextMongodb.InsertItem(log);
if (item.ID == null || item.ID ==0)
{
return await _repoCompany.AddAsync(item);
}
else
{
return await _repoCompany.UpdateByObjAsync(item);
}
}
catch (Exception ex)
{
//SysLog log = new SysLog()
//{
// TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier,
// Datetime = DateTime.Now.ConvertMiladiToShamsi(),
// Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/AddORUpdateCompany",
// Value = ex.Message,
// Route = _httpContextAccessor.HttpContext.Request.Path,
// Type = "catch"
//};
//_contextMongodb.InsertItem(log);
return null;
}
}
public async Task<bool> ExistMobileAndCompanyIsActive(string mobile)
{
return await _repoCompany.GetAll().AnyAsync(w => w.Mobile == mobile && w.IsActive);
}
}
}

View File

@@ -0,0 +1,20 @@
using Back.Data.Contracts;
using Back.Data.Models;
using Microsoft.EntityFrameworkCore;
namespace Back.Services
{
public class servNotification
{
private readonly IAsyncRepository<Notification> _NotificationRepo;
public servNotification(IAsyncRepository<Notification> NotificationRepo)
{
_NotificationRepo = NotificationRepo;
}
public async Task<List<Notification>> GetNotifications()
{
return await _NotificationRepo.Get(w=>w.Status).ToListAsync();
}
}
}

View File

@@ -0,0 +1,117 @@
using Back.Data.Contracts;
using Back.Data.Models;
using Microsoft.EntityFrameworkCore;
namespace Back.Services
{
public class servPermission
{
private readonly IAsyncRepository<Permission> _repoPermission;
private readonly IAsyncRepository<PermissionPeriod> _repoPermissionPeriod;
private readonly IAsyncRepository<RolUser> _repoRolUser;
private readonly IAsyncRepository<PermissionUser> _repoPermissionUser;
public servPermission(IAsyncRepository<Permission> repoPermission, IAsyncRepository<PermissionPeriod> repoPermissionPeriod
, IAsyncRepository<RolUser> repoRolUser, IAsyncRepository<PermissionUser> repoPermissionUser)
{
_repoPermission = repoPermission;
_repoPermissionPeriod = repoPermissionPeriod;
_repoPermissionUser = repoPermissionUser;
_repoRolUser= repoRolUser;
}
public async Task<List<Permission>> GetChildPermission(int PermissionID)
{
return await _repoPermission.Get(w => w.ParentID == PermissionID).ToListAsync();
}
public async Task<List<Permission>> GetPermissions()
{
return await _repoPermission.GetAll().ToListAsync();
}
public async Task<RolUser> AddRolUser(RolUser rolUser)
{
//SysLog log = new SysLog()
//{
// TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier,
// Datetime = DateTime.Now.ConvertMiladiToShamsi(),
// Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/AddRolUser",
// Value = "*" + JsonConvert.SerializeObject(rolUser),
// Route = _httpContextAccessor.HttpContext.Request.Path,
// Type = "User"
//};
//_contextMongodb.InsertItem(log);
return await _repoRolUser.AddAsync(rolUser);
}
public async Task<bool> AddRangePermissionPeriodByCompany(IEnumerable<PermissionPeriod> permissions)
{
try
{
return await _repoPermissionPeriod.AddRangeAsync(permissions.ToList())/*.Wait()*/;
//SysLog log = new SysLog()
//{
// TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier,
// Datetime = DateTime.Now.ConvertMiladiToShamsi(),
// Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/AddRangePermissionPeriodByCompany",
// Value = JsonConvert.SerializeObject(permissions),
// Route = _httpContextAccessor.HttpContext.Request.Path,
// Type = "User"
//};
//_contextMongodb.InsertItem(log);
}
catch (Exception ex)
{
//SysLog log = new SysLog()
//{
// TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier,
// Datetime = DateTime.Now.ConvertMiladiToShamsi(),
// Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/AddRangePermissionPeriodByCompany",
// Value = ex.Message,
// Route = _httpContextAccessor.HttpContext.Request.Path,
// Type = "catch"
//};
//_contextMongodb.InsertItem(log);
return false;
}
}
public async Task<bool> AddPermissionUser(int RolUserID, int[] PermissionIDs)
{
try
{
List<PermissionUser> permissionUsers = new List<PermissionUser>();
foreach (int permissionID in PermissionIDs)
permissionUsers.Add(new PermissionUser() { PermissionID=permissionID,RolUserID= RolUserID });
return await _repoPermissionUser.AddRangeAsync(permissionUsers);
//SysLog log = new SysLog()
//{
// TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier,
// Datetime = DateTime.Now.ConvertMiladiToShamsi(),
// Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/AddPermissionUser",
// Value = RolUserID+" "+JsonConvert.SerializeObject(PermissionIDs),
// Route = _httpContextAccessor.HttpContext.Request.Path,
// Type = "User"
//};
//_contextMongodb.InsertItem(log);
}
catch (Exception ex)
{
//SysLog log = new SysLog()
//{
// TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier,
// Datetime = DateTime.Now.ConvertMiladiToShamsi(),
// Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/AddPermissionUser",
// Value = ex.Message,
// Route = _httpContextAccessor.HttpContext.Request.Path,
// Type = "catch"
//};
//_contextMongodb.InsertItem(log);
return false;
}
}
}
}

View File

@@ -0,0 +1,14 @@
namespace Back.Services
{
public class servSendMsg
{
private readonly mpNuget.RestClient _restClient;
public servSendMsg(mpNuget.RestClient restClient)=> _restClient = restClient;
private void SendMsgByPatern(string Text, string To, int bodyID) {/*_restClient.SendByBaseNumber(Text, To, bodyID);*/ }
private void SendMsg(string Text, string To)=> _restClient.Send(To, "50004001660045", Text, false);
public void Authentication(string to,string code) => SendMsgByPatern(code, to, 0);
public void SuccessfulRegistration(string to, string code) => SendMsgByPatern(code, to, 1);
public void SuccessfulPayment(string to, string code) => SendMsgByPatern(code, to, 2);
// public void firstEntry(string to, string code) => SendMsgByPatern(code, to, 3);
}
}

286
Back/Services/servUser.cs Normal file
View File

@@ -0,0 +1,286 @@
using Back.Common;
using Back.Data.Contracts;
using Back.Data.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Shared.DTOs;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace Back.Services
{
public class servUser
{
private readonly IConfiguration _configuration;
private readonly CheckPermission _checkPermission;
private readonly servPermission _servPermission;
private readonly servNotification _servNotification;
private readonly IAsyncRepository<User> _RepoUser;
private readonly IAsyncRepository<PermissionPeriod> _RepoPermissionPeriod;
public servUser(IConfiguration configuration,
CheckPermission checkPermission, servPermission servPermission
, servNotification servNotification, IAsyncRepository<User> RepoUser, IAsyncRepository<PermissionPeriod> RepoPermissionPeriod)
{
_configuration = configuration;
_checkPermission = checkPermission;
_servPermission = servPermission;
_servNotification = servNotification;
_RepoUser = RepoUser;
_RepoPermissionPeriod = RepoPermissionPeriod;
}
public async Task<User?> GetUserByUserNameAndPassword(string UserName, string Password)
{
return await _RepoUser.Get(w => w.Username == UserName && w.Password == Password.encrypted() && w.IsActive)
.Include(i => i.RolUsers)
.ThenInclude(ti => ti.rolePermissions)
.Include(i => i.RolUsers)
.ThenInclude(ti=>ti.Company)
.ThenInclude(ti => ti.PermissionPeriods)
.ThenInclude(ti => ti.Permission)
.Include(ti=>ti.RolUsers)
.ThenInclude(ti => ti.Company)
.ThenInclude(ti => ti.PermissionPeriods)
.ThenInclude(ti => ti.CalculationType)
.FirstOrDefaultAsync();
}
public async Task<UserAuthenticationDTO?> UserAuthentication(string UserNameORUserID, string Password="")
{
UserAuthenticationDTO ret = new UserAuthenticationDTO();
User? user = null;
if (string.IsNullOrEmpty(Password) && int.TryParse(UserNameORUserID,out int UserID))
user = await GetUserByUserID(UserID);
else
user =await GetUserByUserNameAndPassword(UserNameORUserID, Password);
if (user == null)
return null;
ret.Token =await CerateToken(user.ID, user.Username);
ret.FullName = user.Fullname;
ret.Photo = user.Photo==null ? null : Convert.ToBase64String(user.Photo);
foreach (var rol in user.RolUsers)
{
if (!rol.Company.IsActive)
continue;
List<PermissionAuthenticationDTO> permissions = new List<PermissionAuthenticationDTO>();
foreach (var per in rol.Company.PermissionPeriods)
{
bool _accessibility = await _checkPermission.AllowPermission(user.ID, rol.CompanyID, per.Permission.ID);
#region Child
List<Permission> Chidpermissions = _accessibility ? await _servPermission.GetChildPermission(per.Permission.ID):new List<Permission>();
List<PermissionAuthenticationDTO> ChildpermissionAuthenticationDTOs = new List<PermissionAuthenticationDTO>();
foreach (Permission childper in Chidpermissions)
{
bool _childaccessibility = await _checkPermission.AllowPermission(user.ID, rol.CompanyID, childper.ID);
PermissionAuthenticationDTO ChildpermissionAuthenticationDTO = new PermissionAuthenticationDTO
{
ID = childper.ID,
ParentID = childper.ParentID,
Title = childper.Title,
accessibility = _childaccessibility,
//TODO
ChildPermissions = null
};
ChildpermissionAuthenticationDTOs.Add(ChildpermissionAuthenticationDTO);
}
#endregion
PermissionAuthenticationDTO permissionAuthenticationDTO = new PermissionAuthenticationDTO
{
ID = per.Permission.ID,
ParentID = per.Permission.ParentID,
Title = per.Permission.Title,
accessibility = _accessibility,
//TODO
ChildPermissions = ChildpermissionAuthenticationDTOs
//Period=new PeriodDTO()
//{
// CalculationTypeID = rol.Company.PermissionPeriods.Where(w => w.PermissionID == per.ID).Select(s => s.CalculationType.ID).FirstOrDefault(),
// CalculationTypeTitle = rol.Company.PermissionPeriods.Where(w => w.PermissionID == per.ID).Select(s => s.CalculationType.Title).FirstOrDefault(),
// RemainingAmount = rol.Company.PermissionPeriods.Where(w => w.PermissionID == per.ID).Select(s => s.RemainingAmount).FirstOrDefault(),
// TotalAmount = rol.Company.PermissionPeriods.Where(w => w.PermissionID == per.ID).Select(s => s.TotalAmount).FirstOrDefault()
//}
};
permissions.Add(permissionAuthenticationDTO);
}
ret.Companies.Add(new CompanyAuthenticationDTO
{
ID = rol.CompanyID,
Name = rol.Company.Name,
IsAdmin = rol.IsAdmin,
Logo= rol.Company.Logo == null ? null : Convert.ToBase64String(rol.Company.Logo)
/*, permissions = permissions*/
});
}
return ret;
}
public async Task<User> AddUser(User item)
{
//_contextMongodb.InsertItem(new SysLog()
//{
// TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier,
// Datetime = DateTime.Now.ConvertMiladiToShamsi(),
// Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/AddUser",
// Value = JsonConvert.SerializeObject(item),
// Route = _httpContextAccessor.HttpContext.Request.Path,
// Type = "User"
//});
return await _RepoUser.AddAsync(item);
}
public async Task<bool> ExistUser(string UserName)
{
return await _RepoUser.GetAll().AnyAsync(w=>w.Username==UserName);
}
public async Task<User> GetUserByUsername(string UserName)
{
return await _RepoUser.Get(w => w.Username == UserName).FirstOrDefaultAsync();
}
public async Task<User?> GetUserByUserID(int UserID)
{
return await _RepoUser.Get(w => w.ID == UserID).FirstOrDefaultAsync();
}
public async void SetTokenAndDateLogininDB(int UserID,string Token)
{
var user = await GetUserByUserID(UserID);
if (user != null)
{
user.Token = Token;
user.DateLastLogin=DateTime.Now.ConvertMiladiToShamsi();
await _RepoUser.UpdateAsync(user);
}
}
public async Task<DashBoardDTO> GetDashBoard(int CompanyID,int UserID)
{
DashBoardDTO request=new DashBoardDTO();
var period=await _RepoPermissionPeriod
.Get(w=>w.CompanyID==CompanyID && (!w.IsLocked.HasValue || !w.IsLocked.Value)).ToListAsync();
foreach (var item in period)
{
request.AlistofServices.Add(new ServiceInDashBoardDTO
{
PermissionID= item.PermissionID,
PermissionName = item.Permission.Title,
CalTypeID= item.CalculationTypeID,
CalTypeTitle = item.CalculationType.Title,
Total = item.CalculationTypeID == 1 ? item.TotalAmount.ToString() :"",
Remaining = item.CalculationTypeID == 1 ? item.RemainingAmount.ToString()
: item.CalculationTypeID== 2 ? "" : item.RemainingAmount.ToString().ShamciToFormatShamci()
});
}
request.LastLoginDate= _RepoUser.Get(w=>w.ID==UserID).Select(s=>s.DateLastLogin).FirstOrDefault();
if(!string.IsNullOrEmpty(request.LastLoginDate))
request.LastLoginDate.ShamciToFormatShamci();
var user = await GetUserByUserID(UserID);
if (user.Mobile == user.Username)
request.Warning.Add(new AlertDTO { Status=0,Message= "موبایل و نام کاربری بهتر است شبیه هم نباشند" });
if (user.Mobile.encrypted() == user.Password)
request.Warning.Add(new AlertDTO { Status = 0, Message = "موبایل و کلمه عبور بهتر است شبیه هم نباشند" });
var Company = user.RolUsers.Where(w=>w.CompanyID== CompanyID).Select(s=>s.Company).FirstOrDefault();
if (Company!=null)
{
if (string.IsNullOrEmpty(Company.Email) || string.IsNullOrEmpty(Company.Phone)
|| string.IsNullOrEmpty(Company.EconomicCode) || string.IsNullOrEmpty(Company.UniqeMemory)
|| string.IsNullOrEmpty(Company.PrivateKey))
{
request.Warning.Add(new AlertDTO { Status = 0, Message = "بهتر است اطلاعات شرکت بروزرسانی شود" });
}
}
var nots= await _servNotification.GetNotifications();
if (nots.Any())
request.Notifications= nots.Select(s=>new AlertDTO
{
Message=s.Message,
Status=s.Type,
Path=s.Path,
ViewSize=s.ViewSize
}).ToList();
return request;
}
public async Task<User> UpdateUser(User user)
{
//_contextMongodb.InsertItem(new SysLog()
//{
// TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier,
// Datetime = DateTime.Now.ConvertMiladiToShamsi(),
// Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/UpdateUser",
// Value = JsonConvert.SerializeObject(user),
// Route = _httpContextAccessor.HttpContext.Request.Path,
// Type = "User"
//});
return await _RepoUser.UpdateByObjAsync(user);
}
//--------internal
private async Task<string> CerateToken(int UserId, string UserName)
{
string Jwt_Lifetime_Minutes = "";
try
{
Jwt_Lifetime_Minutes = _configuration["Fixedvalues:Jwt_Lifetime_Minutes"].ToString();
if (string.IsNullOrEmpty(Jwt_Lifetime_Minutes))
Jwt_Lifetime_Minutes = "60";
}
catch (Exception ex)
{
//SysLog log = new SysLog()
//{
// TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier,
// Datetime = DateTime.Now.ConvertMiladiToShamsi(),
// Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/CerateToken",
// Value = ex.Message,
// Route = _httpContextAccessor.HttpContext.Request.Path,
// Type = "catch"
//};
//_contextMongodb.InsertItem(log);
Jwt_Lifetime_Minutes = "60";
//To DO
}
#region CreateToken
var securityKey = new SymmetricSecurityKey(
Encoding.ASCII.GetBytes(Fixedvalues.SecretForKey)
);
var signingCredentials = new SigningCredentials(
securityKey, SecurityAlgorithms.HmacSha256
);
var claimsForToken = new List<Claim>();
claimsForToken.Add(new Claim("UserID", UserId.ToString()));
claimsForToken.Add(new Claim(ClaimTypes.NameIdentifier, UserName));
var jwtSecurityToke = new JwtSecurityToken(
Fixedvalues.Issuer, Fixedvalues.Audience, claimsForToken,
DateTime.Now, DateTime.Now.AddMinutes(Convert.ToInt32(Jwt_Lifetime_Minutes)), signingCredentials);
string Token = new JwtSecurityTokenHandler()
.WriteToken(jwtSecurityToke);
SetTokenAndDateLogininDB(UserId, Token);
//_contextMongodb.InsertItem(new SysLog()
//{
// TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier,
// Datetime = DateTime.Now.ConvertMiladiToShamsi(),
// Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/CerateToken",
// Value = UserId + " " + UserName+"=> "+Token,
// Route = _httpContextAccessor.HttpContext.Request.Path,
// Type = "User"
//});
return Token;
#endregion
}
}
}