Files
moadiran/Back/Services/servUser.cs

532 lines
25 KiB
C#
Raw Normal View History

2024-04-17 15:49:34 +03:30
using Back.Common;
using Back.Data.Contracts;
2024-04-29 18:15:46 +03:30
using Back.Data.Infrastructure.Repository;
2024-04-17 15:49:34 +03:30
using Back.Data.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Shared.DTOs;
2024-06-18 16:15:17 +03:30
using System.ComponentModel.Design;
2024-06-18 13:59:32 +03:30
using System.Data.SqlTypes;
2024-04-17 15:49:34 +03:30
using System.IdentityModel.Tokens.Jwt;
2024-04-29 07:58:41 +03:30
using System.Reflection;
2024-04-17 15:49:34 +03:30
using System.Security.Claims;
using System.Text;
namespace Back.Services
{
public class servUser
{
private readonly IConfiguration _configuration;
2024-04-18 00:33:46 +03:30
2024-04-17 15:49:34 +03:30
private readonly servNotification _servNotification;
private readonly IAsyncRepository<User> _RepoUser;
2024-04-29 18:15:46 +03:30
private readonly RepositoryBase<Company> _RepoCompany;
2024-04-17 15:49:34 +03:30
private readonly IAsyncRepository<PermissionPeriod> _RepoPermissionPeriod;
2024-06-18 16:15:17 +03:30
private readonly IAsyncRepository<InvoiceItem> _invoiceitemRepo;
2024-06-18 13:59:32 +03:30
private readonly IAsyncRepository<Customer> _RepoCus;
private readonly IAsyncRepository<Invoice> _RepoInvoice;
private readonly IAsyncRepository<CODItem> _RepoCODItem;
2024-04-18 00:33:46 +03:30
public servUser(IConfiguration configuration
, servNotification servNotification
, IAsyncRepository<User> RepoUser
2024-04-29 18:15:46 +03:30
, IAsyncRepository<PermissionPeriod> RepoPermissionPeriod
2024-06-18 13:59:32 +03:30
, RepositoryBase<Company> repoCompany, IAsyncRepository<Customer> RepoCus
2024-06-18 16:15:17 +03:30
, IAsyncRepository<Invoice> RepoInvoice, IAsyncRepository<CODItem> RepoCODItem
, IAsyncRepository<InvoiceItem> invoiceitemRepo)
2024-04-17 15:49:34 +03:30
{
2024-06-18 16:15:17 +03:30
_invoiceitemRepo = invoiceitemRepo;
2024-06-18 13:59:32 +03:30
_RepoCus = RepoCus;
_RepoInvoice = RepoInvoice;
_RepoCODItem = RepoCODItem;
2024-04-17 15:49:34 +03:30
_configuration = configuration;
_servNotification = servNotification;
_RepoUser = RepoUser;
_RepoPermissionPeriod = RepoPermissionPeriod;
2024-04-29 18:15:46 +03:30
_RepoCompany = repoCompany;
2024-04-17 15:49:34 +03:30
}
public async Task<User?> GetUserByUserNameAndPassword(string UserName, string Password)
{
return await _RepoUser.Get(w => w.Username == UserName && w.Password == Password.encrypted() && w.IsActive)
2024-04-18 00:33:46 +03:30
// .Include(i => i.RolUsers)
// .ThenInclude(ti => ti.rolePermissions)
// .Include(i => i.RolUsers)
// .ThenInclude(ti=>ti.Company)
//.ThenInclude(ti => ti.PermissionPeriods)
// .ThenInclude(ti => ti.Permission)
2024-04-29 18:15:46 +03:30
.Include(ti => ti.RolUsers)
2024-04-17 15:49:34 +03:30
.ThenInclude(ti => ti.Company)
2024-04-29 18:15:46 +03:30
//.ThenInclude(ti => ti.PermissionPeriods)
// .ThenInclude(ti => ti.CalculationType)
2024-04-17 15:49:34 +03:30
.FirstOrDefaultAsync();
}
2024-04-29 18:15:46 +03:30
public async Task<UserAuthenticationDTO?> UserAuthentication(string UserNameORUserID, string Password = "", bool newtoken = true)
2024-04-17 15:49:34 +03:30
{
UserAuthenticationDTO ret = new UserAuthenticationDTO();
User? user = null;
2024-04-29 18:15:46 +03:30
if (string.IsNullOrEmpty(Password) && int.TryParse(UserNameORUserID, out int UserID))
2024-04-17 15:49:34 +03:30
user = await GetUserByUserID(UserID);
else
2024-04-29 18:15:46 +03:30
user = await GetUserByUserNameAndPassword(UserNameORUserID, Password);
2024-04-17 15:49:34 +03:30
if (user == null)
return null;
2024-04-18 18:26:12 +03:30
string Jwt_Lifetime_Minutes = await GetJwt_Lifetime_Minutes();
2024-04-29 07:58:41 +03:30
ret.UserName = user.Username;
2024-04-29 18:15:46 +03:30
ret.Token = newtoken ? await CerateToken(user.ID, user.Username, Jwt_Lifetime_Minutes) : user.Token;
2024-04-17 15:49:34 +03:30
ret.FullName = user.Fullname;
2024-04-29 18:15:46 +03:30
ret.Photo = user.Photo == null ? null : Convert.ToBase64String(user.Photo);
2024-04-17 17:34:34 +03:30
//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);
2024-04-17 15:49:34 +03:30
2024-04-17 17:34:34 +03:30
// #region Child
2024-04-17 15:49:34 +03:30
2024-04-17 17:34:34 +03:30
// 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
2024-04-17 15:49:34 +03:30
2024-04-17 17:34:34 +03:30
// PermissionAuthenticationDTO permissionAuthenticationDTO = new PermissionAuthenticationDTO
// {
// ID = per.Permission.ID,
// ParentID = per.Permission.ParentID,
// Title = per.Permission.Title,
// accessibility = _accessibility,
// //TODO
// ChildPermissions = ChildpermissionAuthenticationDTOs
2024-04-17 15:49:34 +03:30
2024-04-17 17:34:34 +03:30
// //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()
// //}
2024-04-17 15:49:34 +03:30
2024-04-17 17:34:34 +03:30
// };
// permissions.Add(permissionAuthenticationDTO);
// }
2024-04-17 15:49:34 +03:30
2024-04-17 17:34:34 +03:30
// 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*/
// });
//}
ret.Company = new CompanyAuthenticationDTO
{
2024-05-03 18:18:38 +03:30
ID = user.RolUsers.First().CompanyID,
2024-04-17 17:34:34 +03:30
Name = user.RolUsers.First().Company.Name,
2024-07-29 23:32:54 +03:30
Credit = user.RolUsers.First().Company.Credit,
2024-04-17 17:34:34 +03:30
IsAdmin = user.RolUsers.First().IsAdmin,
Logo = user.RolUsers.First().Company.Logo == null ? null : Convert.ToBase64String(user.RolUsers.First().Company.Logo)
2024-04-17 15:49:34 +03:30
2024-04-17 17:34:34 +03:30
};
2024-04-18 18:26:12 +03:30
var dt = newtoken ? DateTime.Now : user.DateLastLogin.ToMiladiByTime();
2024-04-29 18:15:46 +03:30
ret.enterDate = dt;
ret.exitDate = dt.AddMinutes(Convert.ToInt32(Jwt_Lifetime_Minutes));
2024-04-17 15:49:34 +03:30
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)
{
2024-04-29 18:15:46 +03:30
return await _RepoUser.GetAll().AnyAsync(w => w.Username == UserName);
2024-04-17 15:49:34 +03:30
}
public async Task<User> GetUserByUsername(string UserName)
{
return await _RepoUser.Get(w => w.Username == UserName).FirstOrDefaultAsync();
}
public async Task<User?> GetUserByUserID(int UserID)
{
2024-04-18 18:26:12 +03:30
return await _RepoUser.Get(w => w.ID == UserID)
.Include(ti => ti.RolUsers)
.ThenInclude(ti => ti.Company)
.FirstOrDefaultAsync();
2024-04-17 15:49:34 +03:30
}
2024-04-29 18:15:46 +03:30
public async Task SetTokenAndDateLogininDB(int UserID, string Token)
2024-04-17 15:49:34 +03:30
{
var user = await GetUserByUserID(UserID);
if (user != null)
{
user.Token = Token;
2024-04-29 18:15:46 +03:30
user.DateLastLogin = DateTime.Now.ConvertMiladiToShamsiByTime();
await _RepoUser.UpdateAsync(user);
2024-04-17 15:49:34 +03:30
}
}
2024-04-29 07:58:41 +03:30
public async Task<bool> ChangePasswordByMobile(string mobile, string newpassword)
{
2024-04-29 18:15:46 +03:30
var user = await GetUserByUsername(mobile);
2024-04-29 07:58:41 +03:30
if (user == null)
return false;
user.Password = newpassword.encrypted();
2024-04-29 18:15:46 +03:30
return await _RepoUser.UpdateAsync(user);
2024-04-29 07:58:41 +03:30
}
2024-06-10 17:26:31 +03:30
public async Task<DashBoardDTO> GetDashBoard(int UserID)
2024-04-17 15:49:34 +03:30
{
2024-06-10 17:26:31 +03:30
var user = await GetUserByUserID(UserID);
2024-04-29 18:15:46 +03:30
DashBoardDTO request = new DashBoardDTO();
var period = await _RepoPermissionPeriod
2024-06-10 17:26:31 +03:30
.Get(w => w.CompanyID == user.RolUsers.First().CompanyID && (!w.IsLocked.HasValue || !w.IsLocked.Value))
2024-06-18 17:45:46 +03:30
.Include(inc => inc.CalculationType)
2024-06-10 17:26:31 +03:30
.Include(inc => inc.Permission)
.ToListAsync();
2024-04-17 15:49:34 +03:30
foreach (var item in period)
{
request.AlistofServices.Add(new ServiceInDashBoardDTO
{
2024-04-29 18:15:46 +03:30
PermissionID = item.PermissionID,
2024-04-17 15:49:34 +03:30
PermissionName = item.Permission.Title,
2024-04-29 18:15:46 +03:30
CalTypeID = item.CalculationTypeID,
2024-04-17 15:49:34 +03:30
CalTypeTitle = item.CalculationType.Title,
2024-04-29 18:15:46 +03:30
Total = item.CalculationTypeID == 1 ? item.TotalAmount.ToString() : "",
2024-06-10 20:49:31 +03:30
Remaining = item.CalculationTypeID == 1 ? item.RemainingAmount
: item.CalculationTypeID == 2 ? 0 : item.RemainingAmount
2024-04-17 15:49:34 +03:30
});
}
2024-04-29 18:15:46 +03:30
request.LastLoginDate = _RepoUser.Get(w => w.ID == UserID).Select(s => s.DateLastLogin).FirstOrDefault();
if (!string.IsNullOrEmpty(request.LastLoginDate))
2024-06-18 13:59:32 +03:30
request.LastLoginDate = $"{request.LastLoginDate.Substring(8, 2)}:{request.LastLoginDate.Substring(10, 2)} {request.LastLoginDate.Substring(0, 4)}/{request.LastLoginDate.Substring(4, 2)}/{request.LastLoginDate.Substring(6, 2)}";
2024-04-17 15:49:34 +03:30
2024-06-24 17:33:26 +03:30
//request.Warning.Add(new AlertDTO { Status = 6, Message = "تست هشدار آبی" });
//request.Warning.Add(new AlertDTO { Status = 5, Message = "تست هشدار زرد" });
2024-06-10 17:26:31 +03:30
//if (user.Mobile == user.Username)
// request.Warning.Add(new AlertDTO { Status = 0, Message = "موبایل و نام کاربری بهتر است شبیه هم نباشند" });
2024-04-17 15:49:34 +03:30
if (user.Mobile.encrypted() == user.Password)
2024-06-24 17:33:26 +03:30
request.Warning.Add(new AlertDTO { Status = 6, Message = "موبایل و کلمه عبور بهتر است شبیه هم نباشند" });
2024-06-10 17:26:31 +03:30
var Company = user.RolUsers.Where(w => w.CompanyID == user.RolUsers.First().CompanyID).Select(s => s.Company).FirstOrDefault();
2024-04-29 18:15:46 +03:30
if (Company != null)
2024-04-17 15:49:34 +03:30
{
2024-06-10 17:26:31 +03:30
if (/*string.IsNullOrEmpty(Company.Email) || string.IsNullOrEmpty(Company.Phone) || */
string.IsNullOrEmpty(Company.EconomicCode) || string.IsNullOrEmpty(Company.UniqeMemory)
2024-04-17 15:49:34 +03:30
|| string.IsNullOrEmpty(Company.PrivateKey))
{
2024-06-24 17:33:26 +03:30
request.Warning.Add(new AlertDTO { Status = 5, Message = "بهتر است اطلاعات شرکت بروزرسانی شود" });
2024-04-17 15:49:34 +03:30
}
}
2024-06-25 17:14:08 +03:30
var nots = await _servNotification.GetNotifications(UserID);
2024-04-17 15:49:34 +03:30
if (nots.Any())
2024-04-29 18:15:46 +03:30
request.Notifications = nots.Select(s => new AlertDTO
2024-04-17 15:49:34 +03:30
{
2024-06-25 17:14:08 +03:30
ViewSize=s.ID.ToString(),
2024-04-29 18:15:46 +03:30
Message = s.Message,
Status = s.Type,
2024-06-25 17:14:08 +03:30
Path = s.Title
2024-04-29 18:15:46 +03:30
}).ToList();
2024-06-18 13:59:32 +03:30
LastActivitySevice lastInvoice = new LastActivitySevice();
#region LastActivitySevice
//invoice
var lastinv = await _RepoInvoice.Get(w => w.CompanyID == user.RolUsers.First().CompanyID && !w.IsDeleted)
2024-06-18 17:45:46 +03:30
.Include(inc => inc.Customer)
.Select(s => new LastActivitySevice
2024-06-18 13:59:32 +03:30
{
ID = s.ID,
2024-06-18 17:45:46 +03:30
Date = s.InvoiceDate.ShamciToFormatShamci(),
Name = s.Customer.FullName,
PermissionID = 3,
TypeTitle = s.invoiceType.GetEnumDisplayName()
2024-06-18 13:59:32 +03:30
})
.OrderByDescending(o => o.ID).FirstOrDefaultAsync();
2024-06-18 17:45:46 +03:30
if (lastinv != null)
2024-06-18 13:59:32 +03:30
request.lastActivitiesSevices.Add(lastinv);
//cod
var lastcod = await _RepoCODItem.Get(w => w.CompanyID == user.RolUsers.First().CompanyID && !w.IsDeleted)
.Select(s => new LastActivitySevice
{
ID = s.ID,
Date = "",
Name = s.Title,
PermissionID = 4,
TypeTitle = ""
})
.OrderByDescending(o => o.ID).FirstOrDefaultAsync();
if (lastcod != null)
request.lastActivitiesSevices.Add(lastcod);
//cus
var lastcus = await _RepoCus.Get(w => w.CompanyID == user.RolUsers.First().CompanyID && !w.IsDeleted)
.Select(s => new LastActivitySevice
{
ID = s.ID,
Date = "",
Name = s.FullName,
PermissionID = 8,
TypeTitle = ""
})
.OrderByDescending(o => o.ID).FirstOrDefaultAsync();
if (lastcus != null)
request.lastActivitiesSevices.Add(lastcus);
#endregion
2024-06-18 16:15:17 +03:30
2024-06-20 18:22:34 +03:30
List<string> dt = new List<string>();
for (int i = -7; i < 1; i++)
dt.Add(DateTime.Now.AddDays(i).ConvertMiladiToShamsi());
2024-06-23 19:56:05 +03:30
2024-06-20 19:10:38 +03:30
request.MostInvoicedProduct = await _invoiceitemRepo.Get(w => w.invoice.CompanyID == user.RolUsers.First().CompanyID && !w.invoice.IsDeleted
2024-08-08 00:28:17 +03:30
&& (w.invoice.invoiceType == InvoiceType.BackFrmSale || w.invoice.invoiceType == InvoiceType.Repair || (w.invoice.invoiceType == InvoiceType.Sale && !w.invoice.Childinvoice.Any(a => !a.IsDeleted)))
2024-06-20 19:10:38 +03:30
&& (dt.Contains(w.invoice.InvoiceDate)))
2024-06-20 18:22:34 +03:30
.Include(inc => inc.cODItem)
.GroupBy(g => g.CODID)
.Select(s => new IdNameByCount<int>
{
ID = s.Key,
Title = s.Select(s => s.sstt).First(),
count = s.Sum(s => s.am)
}).OrderByDescending(o => o.count)
2024-06-18 16:15:17 +03:30
.ToListAsync();
2024-06-20 18:22:34 +03:30
2024-06-23 19:56:05 +03:30
request.MostInvoicedCustomer = await _RepoInvoice.Get(w => w.CompanyID == user.RolUsers.First().CompanyID && !w.IsDeleted
2024-08-08 00:28:17 +03:30
&& (w.invoiceType == InvoiceType.BackFrmSale || w.invoiceType == InvoiceType.Repair || (w.invoiceType == InvoiceType.Sale && !w.Childinvoice.Any(a => !a.IsDeleted) ))
2024-06-23 19:56:05 +03:30
&& dt.Contains(w.InvoiceDate))
2024-06-20 18:22:34 +03:30
.Include(inc => inc.Customer)
.GroupBy(g => g.CustomerID)
.Select(s => new IdNameByCount<int>
{
ID = s.Key,
Title = s.Select(s => s.Customer.FullName).First(),
count = s.Count()
}).OrderByDescending(o => o.count)
.ToListAsync();
var cdate = DateTime.Now.ConvertMiladiToShamsiAndGetYearMonth();
2024-06-23 19:56:05 +03:30
var sale = await _RepoInvoice.Get(w => w.CompanyID == user.RolUsers.First().CompanyID && !w.IsDeleted
2024-08-08 00:28:17 +03:30
&& (w.invoiceType == InvoiceType.BackFrmSale || w.invoiceType == InvoiceType.Repair || (w.invoiceType == InvoiceType.Sale && !w.Childinvoice.Any(a => !a.IsDeleted)))
2024-06-23 19:56:05 +03:30
&& w.InvoiceDate.StartsWith(cdate))
.Include(inc => inc.invoiceDetails)
.ThenInclude(inc => inc.cODItem)
.ThenInclude(inc => inc.CODUnit)
.Include(inc => inc.pattern)
.Select(s => s.tbill)
.ToListAsync();
request.SaleInMonth = sale.Sum();
2024-06-20 18:22:34 +03:30
cdate = DateTime.Now.AddMonths(-1).ConvertMiladiToShamsiAndGetYearMonth();
2024-06-20 19:10:38 +03:30
var lastonthsale = await _RepoInvoice.Get(w => w.CompanyID == user.RolUsers.First().CompanyID && !w.IsDeleted
2024-08-08 00:28:17 +03:30
&& (w.invoiceType == InvoiceType.BackFrmSale || w.invoiceType == InvoiceType.Repair || (w.invoiceType == InvoiceType.Sale && !w.Childinvoice.Any(a => !a.IsDeleted)))
2024-06-23 19:56:05 +03:30
&& w.InvoiceDate.StartsWith(cdate))
2024-06-20 18:22:34 +03:30
.Include(inc => inc.invoiceDetails)
.ThenInclude(inc => inc.cODItem)
.ThenInclude(inc => inc.CODUnit)
.Include(inc => inc.pattern)
.Select(s => s.tbill)
.ToListAsync();
decimal? total = lastonthsale.Sum();
decimal? part = request.SaleInMonth;
//decimal? total = 17892909;
//decimal? part = request.SaleInMonth;
if (total.HasValue && total.Value > 0)
2024-06-18 17:45:46 +03:30
{
2024-06-20 18:22:34 +03:30
if (!part.HasValue) part = 0;
2024-06-18 17:45:46 +03:30
2024-06-23 19:56:05 +03:30
request.Salepercent = decimal.Parse(((part.Value / total.Value) * 100).ToString().Split('.')[0]);
2024-06-18 17:45:46 +03:30
}
2024-06-23 19:56:05 +03:30
// request.ForSaleChart.AddRange(new List<IdNameByCount<int>>()
//{
// new IdNameByCount<int>{ID=0,Title="1",count=10},
// new IdNameByCount<int>{ID=1,Title="2",count=5},
// new IdNameByCount<int>{ID=2,Title="3",count=12},
// new IdNameByCount<int>{ID=3,Title="4",count=21}
//});
var dateTime = DateTime.Now.ConvertMiladiToShamsi();
for (int i = 1; i <= Convert.ToInt32(dateTime.Substring(6, 2)); i++)
{
var sumsale = await _RepoInvoice.Get(w => w.CompanyID == user.RolUsers.First().CompanyID && !w.IsDeleted
2024-08-08 00:28:17 +03:30
&& (w.invoiceType == InvoiceType.BackFrmSale || w.invoiceType == InvoiceType.Repair || (w.invoiceType == InvoiceType.Sale && !w.Childinvoice.Any(a => !a.IsDeleted)))
2024-06-23 19:56:05 +03:30
&& w.InvoiceDate == dateTime.Substring(0, 4) + dateTime.Substring(4, 2) + i.ToString("00"))
.Include(inc => inc.invoiceDetails)
.ThenInclude(inc => inc.cODItem)
.ThenInclude(inc => inc.CODUnit)
.Include(inc => inc.pattern)
.Select(s => s.tbill).ToListAsync();
2024-06-18 17:45:46 +03:30
2024-06-23 19:56:05 +03:30
request.ForSaleChart.Add(new IdNameByCount<int>
{
count = sumsale.Sum(),
ID = i - 1,
Title = i.ToString()
});
2024-06-18 16:15:17 +03:30
2024-06-23 19:56:05 +03:30
}
2024-04-17 15:49:34 +03:30
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);
}
2024-04-29 07:58:41 +03:30
public async Task<bool> ChangePassword(string newPass, int UserID)
{
var user = await GetUserByUserID(UserID);
if (user == null)
return false;
user.Password = newPass.encrypted();
return await _RepoUser.UpdateAsync(user);
}
2024-04-29 18:15:46 +03:30
public async Task<bool> ChangeUserName(string newUserName, int UserID)
{
var user = await GetUserByUserID(UserID);
if (user == null)
return false;
2024-06-18 17:45:46 +03:30
2024-04-29 18:15:46 +03:30
if (user != null)
{
2024-06-18 17:45:46 +03:30
using var transaction = await _RepoCompany._dbContext.Database.BeginTransactionAsync();
2024-04-29 18:15:46 +03:30
var company = user.RolUsers.First().Company;
company.Mobile = newUserName;
if (await _RepoCompany.UpdateAsync(company))
{
user.Username = newUserName;
user.Mobile = newUserName;
if (await _RepoUser.UpdateAsync(user))
{
2024-05-01 15:42:21 +03:30
await transaction.CommitAsync();
2024-04-29 18:15:46 +03:30
return true;
}
2024-06-18 17:45:46 +03:30
else
2024-05-01 15:42:21 +03:30
{
await transaction.RollbackAsync();
2024-04-29 18:15:46 +03:30
return false;
}
2024-06-18 17:45:46 +03:30
2024-04-29 18:15:46 +03:30
}
// return Ok(await _servCompany.AddORUpdateCompanyBoolResult(company));
}
return false;
}
public async Task<bool> PermissionChangePassword(string oldPass, int UserID)
{
return await _RepoUser.GetAll().AnyAsync(w => w.ID == UserID && w.Password == oldPass.encrypted() && w.IsActive);
}
public async Task<bool> ExistMobileInUser(string mobile, bool IsActive = true)
2024-04-29 07:58:41 +03:30
{
2024-04-29 18:15:46 +03:30
var resquest = _RepoUser.Get(w => w.Mobile == mobile || w.Username == mobile);
if (IsActive)
resquest = resquest.Where(w => w.IsActive);
2024-04-29 07:58:41 +03:30
2024-04-29 18:15:46 +03:30
return await resquest.AnyAsync();
2024-04-29 07:58:41 +03:30
}
2024-04-17 15:49:34 +03:30
//--------internal
2024-04-18 18:26:12 +03:30
private async Task<string> GetJwt_Lifetime_Minutes()
2024-04-17 15:49:34 +03:30
{
2024-04-18 18:26:12 +03:30
string Jwt_Lifetime_Minutes = "60";
2024-04-17 15:49:34 +03:30
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
}
2024-04-18 18:26:12 +03:30
return Jwt_Lifetime_Minutes;
}
2024-04-29 18:15:46 +03:30
private async Task<string> CerateToken(int UserId, string UserName, string Jwt_Lifetime_Minutes)
2024-04-18 18:26:12 +03:30
{
2024-04-17 15:49:34 +03:30
#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);
2024-04-29 18:15:46 +03:30
2024-04-17 15:49:34 +03:30
string Token = new JwtSecurityTokenHandler()
.WriteToken(jwtSecurityToke);
2024-04-29 18:15:46 +03:30
await SetTokenAndDateLogininDB(UserId, Token);
2024-04-17 15:49:34 +03:30
//_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
}
}
}