public IActionResult GetOrderById(int id, string fields = "")
        {
            if (id <= 0)
            {
                return Error(HttpStatusCode.BadRequest, "id", "invalid id");
            }

            var order = _orderApiService.GetOrderById(id);

            if (order == null)
            {
                return Error(HttpStatusCode.NotFound, "order", "not found");
            }

            var ordersRootObject = new OrdersRootObject();

            string decryptedCardNumber = _encryptionService.DecryptText(order.MaskedCreditCardNumber);
            if (!string.IsNullOrWhiteSpace(decryptedCardNumber))
            {
                order.CardNumber = decryptedCardNumber;
            }

            var orderDto = _dtoHelper.PrepareOrderDTO(order);
            ordersRootObject.Orders.Add(orderDto);

            var json = JsonFieldsSerializer.Serialize(ordersRootObject, fields);

            return new RawJsonActionResult(json);
        }
示例#2
0
        public async Task <MailAccount> GetMailAccount(int accountId, bool includeUser = false)
        {
            if (accountId <= 0)
            {
                _logger.Warn($"MailAccountService.GetMailAccount() no mail account found with id:{accountId}");
                throw new ArgumentException($"MailAccountService.GetMailAccount() no mail account found with id:{accountId}");
            }

            // get the mail account
            var mailAccount = await _repo.GetMailAccount(accountId, includeUser);

            // log if we don't have the requested mail account
            if (mailAccount == null)
            {
                _logger.Debug($"MailAccountService.GetMailAccount() no mail account found with id:{accountId}");
                return(null);
            }

            // decrypt the mail accounts password
            mailAccount.SmtpPassword = _encryptionService.DecryptText(mailAccount.SmtpPassword);

            // if we have an user account, we need to decrypt its password too
            if (mailAccount.User != null)
            {
                mailAccount.User.Password = _encryptionService.DecryptText(mailAccount.User.Password);
            }

            return(mailAccount);
        }
        /// <summary>
        /// Check whether the entered password matches with a saved one
        /// </summary>
        /// <param name="customerPassword">Customer password</param>
        /// <param name="enteredPassword">The entered password</param>
        /// <returns>True if passwords match; otherwise false</returns>
        protected bool PasswordsMatch(CustomerPassword customerPassword, string enteredPassword)
        {
            if (customerPassword == null || string.IsNullOrEmpty(enteredPassword))
            {
                return(false);
            }

            var savedPassword = string.Empty;

            //switch (customerPassword.PasswordFormat)
            //{
            //case PasswordFormat.Clear:
            //    savedPassword = enteredPassword;
            //    break;
            //case PasswordFormat.Encrypted:
            savedPassword = _encryptionService.DecryptText(customerPassword.Password);
            //break;
            //case PasswordFormat.Hashed:
            //    savedPassword = _encryptionService.CreatePasswordHash(enteredPassword, customerPassword.PasswordSalt, "");
            //    break;
            //}

            if (customerPassword.Password == null)
            {
                return(false);
            }



            return((savedPassword == enteredPassword)? true:false);
        }
示例#4
0
        //Get List Of Appointment Using Pagination in Stored Procedure
        public IActionResult Index(DataSourceRequest command)
        {
            ViewBag.FormName = "Appointments";
            var model = new AppointmentListModel();

            try
            {
                ViewBag.PageSizeDropdown = SelectListHelper.GetPageSizeDropdown(command.PageSize.ToString());
                var PagedList = _reportService.GetAllAppointment(
                    keywords: "",
                    page_num: command.Page,
                    page_size: command.PageSize == 0 ? 10 : command.PageSize,
                    GetAll: command.PageSize == 0 ? true : false);

                //pratiksha get hospital name in Decrypt format 28/nov/2019
                PagedList  = PagedList.Select(a => { a.HospitalName = _encryptionService.DecryptText(a.HospitalName); return(a); }).ToList();
                model.List = PagedList.GetPaged(command.Page, command.PageSize, ((PagedList.Count() != 0)?PagedList[0].TotalRecords:0));
                return(View(model));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(View(model));
            }
        }
        /// <summary>
        /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            //Get payment details
            var creditCardName            = _encryptionService.DecryptText(postProcessPaymentRequest.Order.CardName);
            var creditCardNumber          = _encryptionService.DecryptText(postProcessPaymentRequest.Order.CardNumber);
            var creditCardExpirationYear  = _encryptionService.DecryptText(postProcessPaymentRequest.Order.CardExpirationYear);
            var creditCardExpirationMonth = _encryptionService.DecryptText(postProcessPaymentRequest.Order.CardExpirationMonth);
            var creditCardCvv2            = _encryptionService.DecryptText(postProcessPaymentRequest.Order.CardCvv2);

            //Save details in an object
            var processPaymentRequest = new ProcessPaymentRequest
            {
                CreditCardName        = creditCardName,
                CreditCardNumber      = creditCardNumber,
                CreditCardExpireYear  = Convert.ToInt32(creditCardExpirationYear),
                CreditCardExpireMonth = Convert.ToInt32(creditCardExpirationMonth),
                CreditCardCvv2        = creditCardCvv2,
                OrderGuid             = postProcessPaymentRequest.Order.OrderGuid,
                OrderTotal            = postProcessPaymentRequest.Order.OrderTotal,
            };

            //Convert data from ProcessPaymentRequest to Xml object
            var postData = _kuveytTurkService.GetDataAsXml(processPaymentRequest);
            //Send Xml object to url and get result
            var result = _kuveytTurkService.PostPaymentDataToUrl("https://boa.kuveytturk.com.tr/sanalposservice/Home/ThreeDModelPayGate", postData);

            //Create directory and save Html Code in it
            var file = _kuveytTurkService.PutHtmlCodeInFile(result);

            //Redirect to new file HTML page
            _httpContextAccessor.HttpContext.Response.Redirect($"{_webHelper.GetStoreLocation()}OrderPayments/{file}");
        }
示例#6
0
        public IActionResult Login(UserModel userParam)
        {
            ResultModel _Respose = new ResultModel();
            var         user     = _userService.Authenticate(userParam.Username, userParam.Password);

            if (user == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }

            if (user == null)
            {
                _Respose.Message  = ValidationMessages.MobileUserError;
                _Respose.Status   = 0;
                _Respose.Response = null;
                return(Ok(_Respose));
            }
            else
            {
                UserModel userdata = new UserModel();
                userdata.FirstName = _encryptionService.DecryptText(user.FirstName);
                userdata.LastName  = _encryptionService.DecryptText(user.LastName);
                userdata.Username  = _encryptionService.DecryptText(user.Username);
                userdata.Token     = user.Token;
                userdata.Password  = user.Password;
                _Respose.Message   = "Success";
                _Respose.Status    = 1;
                _Respose.Response  = userdata;
                return(Ok(_Respose));
            }
        }
示例#7
0
        public ActionResult Configure()
        {
            //load settings for a chosen store scope
            var storeScope           = this.GetActiveStoreScopeConfiguration(_storeService, _workContext);
            var ogonePaymentSettings = _settingService.LoadSetting <OgonePaymentSettings>(storeScope);

            var model = new ConfigurationModel();

            model.PSPId                  = ogonePaymentSettings.PSPId;
            model.SHAInPassPhrase        = _encryptionService.DecryptText(ogonePaymentSettings.SHAInPassPhrase);
            model.SHAOutPassPhrase       = _encryptionService.DecryptText(ogonePaymentSettings.SHAOutPassPhrase);
            model.AdditionalFee          = ogonePaymentSettings.AdditionalFee;
            model.HashAllParameters      = ogonePaymentSettings.HashAllParameters;
            model.HashingAlgorithmId     = Convert.ToInt32(ogonePaymentSettings.HashingAlgorithm);
            model.HashingAlgorithmValues = ogonePaymentSettings.HashingAlgorithm.ToSelectList();
            model.OgoneGatewayUrl        = ogonePaymentSettings.OgoneGatewayUrl;
            model.TemplateUrl            = ogonePaymentSettings.TemplateUrl;
            model.TemplateTitle          = ogonePaymentSettings.TemplateTitle;
            model.BackgroundColor        = ogonePaymentSettings.BackgroundColor;
            model.TextColor              = ogonePaymentSettings.TextColor;
            model.TableBackgroundColor   = ogonePaymentSettings.TableBackgroundColor;
            model.TableTextColor         = ogonePaymentSettings.TableTextColor;
            model.ButtonBackgroundColor  = ogonePaymentSettings.ButtonBackgroundColor;
            model.ButtonTextColor        = ogonePaymentSettings.ButtonTextColor;
            model.FontFamily             = ogonePaymentSettings.FontFamily;
            model.LogoUrl                = ogonePaymentSettings.LogoUrl;
            model.ParamVar               = ogonePaymentSettings.ParamVar;
            model.OrderIdPrefix          = ogonePaymentSettings.OrderIdPrefix;
            model.PmList                 = ogonePaymentSettings.PmList;
            model.ExclPmList             = ogonePaymentSettings.ExclPmList;

            model.ActiveStoreScopeConfiguration = storeScope;
            if (storeScope > 0)
            {
                model.PSPId_OverrideForStore                 = _settingService.SettingExists(ogonePaymentSettings, x => x.PSPId, storeScope);
                model.SHAInPassPhrase_OverrideForStore       = _settingService.SettingExists(ogonePaymentSettings, x => x.SHAInPassPhrase, storeScope);
                model.SHAOutPassPhrase_OverrideForStore      = _settingService.SettingExists(ogonePaymentSettings, x => x.SHAOutPassPhrase, storeScope);
                model.AdditionalFee_OverrideForStore         = _settingService.SettingExists(ogonePaymentSettings, x => x.AdditionalFee, storeScope);
                model.HashAllParameters_OverrideForStore     = _settingService.SettingExists(ogonePaymentSettings, x => x.HashAllParameters, storeScope);
                model.HashingAlgorithmId_OverrideForStore    = _settingService.SettingExists(ogonePaymentSettings, x => x.HashingAlgorithm, storeScope);
                model.OgoneGatewayUrl_OverrideForStore       = _settingService.SettingExists(ogonePaymentSettings, x => x.OgoneGatewayUrl, storeScope);
                model.TemplateUrl_OverrideForStore           = _settingService.SettingExists(ogonePaymentSettings, x => x.TemplateUrl, storeScope);
                model.TemplateTitle_OverrideForStore         = _settingService.SettingExists(ogonePaymentSettings, x => x.TemplateTitle, storeScope);
                model.BackgroundColor_OverrideForStore       = _settingService.SettingExists(ogonePaymentSettings, x => x.BackgroundColor, storeScope);
                model.TextColor_OverrideForStore             = _settingService.SettingExists(ogonePaymentSettings, x => x.TextColor, storeScope);
                model.TableBackgroundColor_OverrideForStore  = _settingService.SettingExists(ogonePaymentSettings, x => x.TableBackgroundColor, storeScope);
                model.TableTextColor_OverrideForStore        = _settingService.SettingExists(ogonePaymentSettings, x => x.TableTextColor, storeScope);
                model.ButtonBackgroundColor_OverrideForStore = _settingService.SettingExists(ogonePaymentSettings, x => x.ButtonBackgroundColor, storeScope);
                model.ButtonTextColor_OverrideForStore       = _settingService.SettingExists(ogonePaymentSettings, x => x.ButtonTextColor, storeScope);
                model.FontFamily_OverrideForStore            = _settingService.SettingExists(ogonePaymentSettings, x => x.FontFamily, storeScope);
                model.LogoUrl_OverrideForStore               = _settingService.SettingExists(ogonePaymentSettings, x => x.LogoUrl, storeScope);
                model.ParamVar_OverrideForStore              = _settingService.SettingExists(ogonePaymentSettings, x => x.ParamVar, storeScope);
                model.OrderIdPrefix_OverrideForStore         = _settingService.SettingExists(ogonePaymentSettings, x => x.OrderIdPrefix, storeScope);
                model.PmList_OverrideForStore                = _settingService.SettingExists(ogonePaymentSettings, x => x.PmList, storeScope);
                model.ExclPmList_OverrideForStore            = _settingService.SettingExists(ogonePaymentSettings, x => x.ExclPmList, storeScope);
            }

            return(View("~/Plugins/Payments.Ogone/Views/PaymentOgone/Configure.cshtml", model));
        }
示例#8
0
        /// <summary>
        /// Refunds a payment
        /// </summary>
        /// <param name="refundPaymentRequest">Request</param>
        /// <returns>Result</returns>
        public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest)
        {
            var result = new RefundPaymentResult();

            PrepareAuthorizeNet();

            var maskedCreditCardNumberDecrypted = _encryptionService.DecryptText(refundPaymentRequest.Order.MaskedCreditCardNumber);

            if (String.IsNullOrEmpty(maskedCreditCardNumberDecrypted) || maskedCreditCardNumberDecrypted.Length < 4)
            {
                result.AddError("Last four digits of Credit Card Not Available");
                return(result);
            }

            var lastFourDigitsCardNumber = maskedCreditCardNumberDecrypted.Substring(maskedCreditCardNumberDecrypted.Length - 4);
            var creditCard = new creditCardType
            {
                cardNumber     = lastFourDigitsCardNumber,
                expirationDate = "XXXX"
            };

            var codes = (string.IsNullOrEmpty(refundPaymentRequest.Order.CaptureTransactionId) ? refundPaymentRequest.Order.AuthorizationTransactionCode : refundPaymentRequest.Order.CaptureTransactionId).Split(',');
            var transactionRequest = new transactionRequestType
            {
                transactionType = transactionTypeEnum.refundTransaction.ToString(),
                amount          = Math.Round(refundPaymentRequest.AmountToRefund, 2),
                refTransId      = codes[0],
                currencyCode    = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode,

                order = new orderType
                {
                    //x_invoice_num is 20 chars maximum. hece we also pass x_description
                    invoiceNumber = refundPaymentRequest.Order.OrderGuid.ToString().Substring(0, 20),
                    description   = string.Format("Full order #{0}", refundPaymentRequest.Order.OrderGuid)
                },

                payment = new paymentType {
                    Item = creditCard
                }
            };

            var request = new createTransactionRequest {
                transactionRequest = transactionRequest
            };

            // instantiate the contoller that will call the service
            var controller = new createTransactionController(request);

            controller.Execute();

            GetApiResponse(controller, result.Errors);
            result.NewPaymentStatus = PaymentStatus.PartiallyRefunded;

            return(result);
        }
示例#9
0
 private string GetPrivateKey()
 {
     if (_simplifyPaymentSettings.LiveMode)
     {
         return(_encryptionService.DecryptText(_simplifyPaymentSettings.LivePrivateKey).Trim());
     }
     else
     {
         return(_encryptionService.DecryptText(_simplifyPaymentSettings.SandboxPrivateKey).Trim());
     }
 }
        //30/10/19 aakansha
        public virtual void PrintTreatmentRecordList(Document doc, IList <TreatmentRecordVM> TreatmentRecord)
        {
            var table = new PdfPTable(new float[] { 25F, 30F, 30F, 50F, 25F, 25F, 35F, 25F, 30F, 30F })
            {
                RunDirection    = PdfWriter.RUN_DIRECTION_LTR,
                WidthPercentage = 100f
            };

            table.SpacingBefore       = 4f;
            table.HorizontalAlignment = Element.ALIGN_LEFT;
            table.AddCell(_pdfCommonSettings.GetBodyCell(text: "Pateint", columnType: ColumnType.Text, IsHeader: true));
            table.AddCell(_pdfCommonSettings.GetBodyCell(text: "Nurse", columnType: ColumnType.Text, IsHeader: true));
            table.AddCell(_pdfCommonSettings.GetBodyCell(text: "Hospital", columnType: ColumnType.Text, IsHeader: true));
            table.AddCell(_pdfCommonSettings.GetBodyCell(text: "Contact Person", columnType: ColumnType.Text, IsHeader: true));
            table.AddCell(_pdfCommonSettings.GetBodyCell(text: "Doctor", columnType: ColumnType.Text, IsHeader: true));
            table.AddCell(_pdfCommonSettings.GetBodyCell(text: "Room", columnType: ColumnType.Text, IsHeader: true));
            table.AddCell(_pdfCommonSettings.GetBodyCell(text: "Equipment", columnType: ColumnType.Text, IsHeader: true));
            table.AddCell(_pdfCommonSettings.GetBodyCell(text: "Serial", columnType: ColumnType.Text, IsHeader: true));

            table.AddCell(_pdfCommonSettings.GetBodyCell(text: "PMDate", columnType: ColumnType.Text, IsHeader: true));
            table.AddCell(_pdfCommonSettings.GetBodyCell(text: "Status", columnType: ColumnType.Text, IsHeader: true));


            foreach (var item in TreatmentRecord)
            {
                //table.AddCell(_pdfCommonSettings.GetBodyCell(text: item.TreatmentRecord.PateintName + "(" + item.Product.Barcode + ")", columnType: ColumnType.Text, RemoveBorder: true));

                table.AddCell(_pdfCommonSettings.GetBodyCell(text: _encryptionService.DecryptText(item.PateintName).ToString(), columnType: ColumnType.Text, RemoveBorder: true));
                table.AddCell(_pdfCommonSettings.GetBodyCell(text: _encryptionService.DecryptText(item.NurseFirstName) + " " + _encryptionService.DecryptText(item.NurseLastName).ToString(), columnType: ColumnType.Text, RemoveBorder: true));
                table.AddCell(_pdfCommonSettings.GetBodyCell(text: _encryptionService.DecryptText(item.HospitalName).ToString(), columnType: ColumnType.Text, RemoveBorder: true));
                table.AddCell(_pdfCommonSettings.GetBodyCell(text: _encryptionService.DecryptText(item.ContactPerson.ToString()), columnType: ColumnType.Text, RemoveBorder: true));
                table.AddCell(_pdfCommonSettings.GetBodyCell(text: item.DoctorName.ToString(), columnType: ColumnType.Text, RemoveBorder: true));
                table.AddCell(_pdfCommonSettings.GetBodyCell(text: item.Room.ToString(), columnType: ColumnType.Text, RemoveBorder: true));
                table.AddCell(_pdfCommonSettings.GetBodyCell(text: item.EquipmentName.ToString(), columnType: ColumnType.Text, RemoveBorder: true));
                table.AddCell(_pdfCommonSettings.GetBodyCell(text: item.EquipSerial.ToString(), columnType: ColumnType.Number, RemoveBorder: true));
                var StringPMDate = "";
                if (item.PMDate != null)
                {
                    var PMDate = Convert.ToDateTime(item.PMDate);

                    StringPMDate = PMDate.ToShortDateString();
                }
                table.AddCell(_pdfCommonSettings.GetBodyCell(text: StringPMDate, columnType: ColumnType.Number, RemoveBorder: true));

                table.AddCell(_pdfCommonSettings.GetBodyCell(text: item.TreatmentStatus.ToString(), columnType: ColumnType.Text, RemoveBorder: true));
            }

            doc.Add(table);
        }
示例#11
0
        public IActionResult LoginUser(LoginModel model)
        {
            if (ModelState.IsValid && !string.IsNullOrEmpty(model.Password) && !string.IsNullOrEmpty(model.Email))
            {
                var user = _userService.GetByMail(model.Email);

                if (user == null)
                {
                    return(Json("Unknown"));
                }

                if (!model.Password.Equals(_encryptionService.DecryptText(user.Password)))
                {
                    //Ajouter un lock temporaires au bout de 5 tentatives échouées
                    return(Json("Wrong infos"));
                }

                _authenticationService.SignIn(user, true);
                return(RedirectToAction("IndexConnected", "Home"));
            }
            else
            {
                return(Json("Modèle invalide"));
            }
        }
示例#12
0
        private IList <SelectListItem> PreparePatientDropdown(string SelectedText = "Select Patient", int Id = 0)
        {
            var PatientList             = _treatmentRecordServices.GetAllPatientMaster().Where(a => a.Deleted != true);
            List <SelectListItem> items = new List <SelectListItem>();

            foreach (var patientdata in PatientList)
            {
                items.Add(new SelectListItem {
                    Text = _encryptionService.DecryptText(patientdata.PatientName), Value = patientdata.Id.ToString()
                });
            }



            return(items);
        }
        public IActionResult GetAllAppointments(GetAppointmentPaginationVM model)
        {
            ResultModel resultModel = new ResultModel();

            try
            {
                var _AppointmentList = _reportService.GetAllAppointment(page_num: model.Page,
                                                                        page_size: model.PageSize == 0 ? 10 : model.PageSize,
                                                                        GetAll: true,
                                                                        keywords: model.Keyword);
                _AppointmentList = _AppointmentList.Select(a => { a.HospitalName = _encryptionService.DecryptText(a.HospitalName); return(a); }).ToList();

                foreach (var item in _AppointmentList)
                {
                    item._appointmentDates = _reportService.GetAppointmentDates(item.Id);
                }

                resultModel.Message  = ValidationMessages.Success;
                resultModel.Status   = 1;
                resultModel.Response = _AppointmentList;
                return(Ok(resultModel));
            }
            catch (Exception ex)
            {
                resultModel.Message  = ValidationMessages.Failure;
                resultModel.Status   = 0;
                resultModel.Response = null;
                return(Ok(resultModel));
            }
        }
        public void CanEncryptAndDecrypt()
        {
            var password          = "******";
            var encryptedPassword = _encryptionService.EncryptText(password);
            var decryptedPassword = _encryptionService.DecryptText(encryptedPassword);

            decryptedPassword.Should().Be(password);
        }
        public void Can_encrypt_and_decrypt()
        {
            var    password          = "******";
            string encryptedPassword = _encryptionService.EncryptText(password);
            var    decryptedPassword = _encryptionService.DecryptText(encryptedPassword);

            decryptedPassword.ShouldEqual(password);
        }
        public void Can_encrypt_and_decrypt()
        {
            //encrypt and then decrypt password
            string password  = "******";
            string encrypted = _encryptionService.EncryptText(password);
            string decrypted = _encryptionService.DecryptText(encrypted);

            Assert.AreEqual(password, decrypted);
        }
示例#17
0
        public async Task <IActionResult> ChangeEncryptionKey(GeneralCommonSettingsModel model)
        {
            if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManageSettings))
            {
                return(AccessDeniedView());
            }

            var tenantScope      = _tenantContext.ActiveTenantScopeConfiguration;
            var securitySettings = _settingService.LoadSetting <SecuritySettings>(tenantScope);

            try
            {
                if (model.SecuritySettings.EncryptionKey == null)
                {
                    model.SecuritySettings.EncryptionKey = string.Empty;
                }

                model.SecuritySettings.EncryptionKey = model.SecuritySettings.EncryptionKey.Trim();

                var newEncryptionPrivateKey = model.SecuritySettings.EncryptionKey;
                if (string.IsNullOrEmpty(newEncryptionPrivateKey) || newEncryptionPrivateKey.Length != 16)
                {
                    throw new DefaultException("Encryption private key must be 16 characters long.");
                }

                var oldEncryptionPrivateKey = securitySettings.EncryptionKey;
                if (oldEncryptionPrivateKey == newEncryptionPrivateKey)
                {
                    throw new DefaultException("The new encryption key is the same as the old one.");
                }

                //update password information
                var userPasswords = _userService.GetUserPasswords(passwordFormat: PasswordFormat.Encrypted);
                foreach (var userPassword in userPasswords)
                {
                    var decryptedPassword = _encryptionService.DecryptText(userPassword.Password, oldEncryptionPrivateKey);
                    var encryptedPassword = _encryptionService.EncryptText(decryptedPassword, newEncryptionPrivateKey);

                    userPassword.Password = encryptedPassword;
                    _userService.UpdateUserPassword(userPassword);
                }

                securitySettings.EncryptionKey = newEncryptionPrivateKey;
                _settingService.SaveSetting(securitySettings);

                _notificationService.SuccessNotification("Encryption key changed");
            }
            catch (Exception ex)
            {
                _notificationService.ErrorNotification(ex);
            }

            return(RedirectToAction("GeneralCommon"));
        }
示例#18
0
        public virtual ActionResult ChangeEncryptionKey(GeneralCommonSettingsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
            {
                return(AccessDeniedView());
            }

            this.Server.ScriptTimeout = 300;

            var securitySettings = _settingService.LoadSetting <SecuritySettings>();

            try
            {
                if (model.SecuritySettings.EncryptionKey == null)
                {
                    model.SecuritySettings.EncryptionKey = "";
                }

                model.SecuritySettings.EncryptionKey = model.SecuritySettings.EncryptionKey.Trim();

                var newEncryptionPrivateKey = model.SecuritySettings.EncryptionKey;
                if (string.IsNullOrEmpty(newEncryptionPrivateKey) || newEncryptionPrivateKey.Length != 16)
                {
                    throw new SiteException(_localizationService.GetResource("Admin.Configuration.Settings.GeneralCommon.EncryptionKey.TooShort"));
                }

                string oldEncryptionPrivateKey = securitySettings.EncryptionKey;
                if (oldEncryptionPrivateKey == newEncryptionPrivateKey)
                {
                    throw new SiteException(_localizationService.GetResource("Admin.Configuration.Settings.GeneralCommon.EncryptionKey.TheSame"));
                }

                //更改所有该加密格式的用户密码密钥
                var customerPasswords = _customerService.GetCustomerPasswords(passwordFormat: PasswordFormat.Encrypted);
                foreach (var customerPassword in customerPasswords)
                {
                    var decryptedPassword = _encryptionService.DecryptText(customerPassword.Password, oldEncryptionPrivateKey);
                    var encryptedPassword = _encryptionService.EncryptText(decryptedPassword, newEncryptionPrivateKey);

                    customerPassword.Password = encryptedPassword;
                    _customerService.UpdateCustomerPassword(customerPassword);
                }

                securitySettings.EncryptionKey = newEncryptionPrivateKey;
                _settingService.SaveSetting(securitySettings);

                SuccessNotification(_localizationService.GetResource("Admin.Configuration.Settings.GeneralCommon.EncryptionKey.Changed"));
            }
            catch (Exception e)
            {
                ErrorNotification(e);
            }
            return(RedirectToAction("GeneralCommon"));
        }
示例#19
0
        public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            Debug.WriteLine("PostProcessPayment");

            var nfi        = new CultureInfo("en-US", false).NumberFormat;
            var url        = GetPaymentUrl();
            var gatewayUrl = new Uri(url);
            var post       = new RemotePost {
                Url = gatewayUrl.ToString(), Method = "POST"
            };
            var order = postProcessPaymentRequest.Order;

            post.Add("mid", _easyPay2PaymentSettings.mid);
            post.Add("ref", order.OrderGuid.ToString());
            post.Add("cur", _easyPay2PaymentSettings.cur);
            post.Add("amt", order.OrderTotal.ToString());
            post.Add("ccnum", _encryptionService.DecryptText(order.CardNumber));
            post.Add("ccdate", _encryptionService.DecryptText(order.CardExpirationYear) + _encryptionService.DecryptText(order.CardExpirationMonth));
            post.Add("cccvv", _encryptionService.DecryptText(order.CardCvv2));
            post.Add("paytype", "3");

            if (_easyPay2PaymentSettings.transactMode == TransactMode.Authorize)
            {
                post.Add("transtype", "auth");
            }
            else if (_easyPay2PaymentSettings.transactMode == TransactMode.AuthorizeAndCapture)
            {
                post.Add("transtype", "sale");
            }
            else
            {
                throw new NopException("Not supported transaction mode");
            }

            post.Add("statusurl", GetReturnStatusUrl("statusurl", postProcessPaymentRequest));
            post.Add("returnurl", GetReturnStatusUrl("returnurl", postProcessPaymentRequest));
            Debug.Print("ccdate: " + _encryptionService.DecryptText(order.CardExpirationYear) + _encryptionService.DecryptText(order.CardExpirationMonth));
            post.Post();
        }
示例#20
0
        public ActionResult Configure()
        {
            //load settings for a chosen store scope
            var storeScope = this.GetActiveStoreScopeConfiguration(_storeService, _workContext);

            Log("Configure storeScope " + storeScope);

            var simplifyPaymentSettings = _settingService.LoadSetting <SimplifyPaymentSettings>(storeScope);

            Log("Configure settings " + simplifyPaymentSettings.ToString());

            var model = new ConfigurationModel();

            model.HostedMode        = simplifyPaymentSettings.HostedMode;
            model.LiveMode          = simplifyPaymentSettings.LiveMode;
            model.SandboxPublicKey  = simplifyPaymentSettings.SandboxPublicKey;
            model.SandboxPrivateKey = _encryptionService.DecryptText(simplifyPaymentSettings.SandboxPrivateKey);
            model.LivePublicKey     = simplifyPaymentSettings.LivePublicKey;
            model.LivePrivateKey    = _encryptionService.DecryptText(simplifyPaymentSettings.LivePrivateKey);
            model.DebugEnabled      = simplifyPaymentSettings.DebugEnabled;

            model.ActiveStoreScopeConfiguration = storeScope;
            if (storeScope > 0)
            {
                _logger.Information("Configure checking store scope overrides");
                model.HostedMode_OverrideForStore        = _settingService.SettingExists(simplifyPaymentSettings, x => x.HostedMode, storeScope);
                model.LiveMode_OverrideForStore          = _settingService.SettingExists(simplifyPaymentSettings, x => x.LiveMode, storeScope);
                model.SandboxPublicKey_OverrideForStore  = _settingService.SettingExists(simplifyPaymentSettings, x => x.SandboxPublicKey, storeScope);
                model.SandboxPrivateKey_OverrideForStore = _settingService.SettingExists(simplifyPaymentSettings, x => x.SandboxPrivateKey, storeScope);
                model.LivePublicKey_OverrideForStore     = _settingService.SettingExists(simplifyPaymentSettings, x => x.LivePublicKey, storeScope);
                model.LivePrivateKey_OverrideForStore    = _settingService.SettingExists(simplifyPaymentSettings, x => x.LivePrivateKey, storeScope);
                model.DebugEnabled_OverrideForStore      = _settingService.SettingExists(simplifyPaymentSettings, x => x.DebugEnabled, storeScope);
            }

            Log("Configure model " + model.ToString());

            return(View("~/Plugins/Payments.Simplify/Views/PaymentSimplify/Configure.cshtml", model));
        }
 /// <summary>
 /// 根据访问Token获取用户对象
 /// </summary>
 /// <param name="token"></param>
 /// <param name="device"></param>
 /// <returns></returns>
 protected Nop.Core.Domain.Customers.Customer GetCustomerFromToken(string token, string device)
 {
     try
     {
         string   text   = _encryptionService.DecryptText(token);
         string[] strArr = Regex.Split(text, ":::", RegexOptions.IgnoreCase);
         if (strArr.Length == 2)
         {
             if (strArr[1].Equals(device, StringComparison.OrdinalIgnoreCase))
             {
                 int customerId = Convert.ToInt32(strArr[0]);
                 var customer   = _customerService.GetCustomerById(customerId);
                 return(customer);
             }
         }
     }
     catch { }
     return(null);
 }
示例#22
0
        public IHttpActionResult WebGetExecutiveById(ExecutiveMaster Executive)
        {
            ACS.Core.Domain.Master.ExecutiveMaster _Executive = _ExecutiveService.GetExecutiveById(Executive.Id);
            var reporting     = _Executive.ExecutiveReportings.Where(i => i.Deactivate == "N").ToList().FirstOrDefault();
            var divisionLinks = _Executive.ExecutiveDivisionLinks.Where(a => a.Deactivate == "N").ToList();
            var query         = new
            {
                Password      = _encryptionService.DecryptText(_Executive.Password, _ExecutiveService.KeyValue("encriptionkey")),
                Executivename = _Executive.executiveName,
                Email         = _Executive.Emailid,
                Phone         = _Executive.Phoneno,
                Mobile        = _Executive.Mobile,
                DepartmentId  = _Executive.DepartmentId,
                Id            = _Executive.Id,
                Code          = _Executive.executivecode
            };


            return(Json(SerializeObj.SerializeObject(new { query, reporting, divisionLinks })));
        }
示例#23
0
        public async Task Invoke(HttpContext context)
        {
            const string name   = "__moz__token";
            var          cookie = context.Request?.Cookies[name];

            if (!string.IsNullOrEmpty(cookie) && !(context.Request?.Headers?.ContainsKey("Authorization") ?? false))
            {
                var key = _options.Value.AppSecret ?? "gvPXwK50tpE9b6P7";
                try
                {
                    var decryptString = _encryptionService.DecryptText(cookie, key);
                    context.Request?.Headers?.Append("Authorization", "Bearer " + decryptString);
                }
                catch (Exception ex)
                {
                    // ignored
                }
            }
            await _next.Invoke(context);
        }
示例#24
0
        public bool PasswordMatch(CustomerPassword customerPassword, string enteredPassword)
        {
            switch (_customerSettings.DefaultPasswordFormat)
            {
            case PasswordFormat.Clear:
                return(customerPassword.Password.Equals(enteredPassword, StringComparison.InvariantCulture));

            case PasswordFormat.Encrypted:
                return(_encryptionService.DecryptText(customerPassword.Password).Equals(enteredPassword));

            case PasswordFormat.Hashed:
                return(customerPassword.Password.Equals(
                           _encryptionService.CreateHash(enteredPassword,
                                                         _customerSettings.HashedPasswordFormat),
                           StringComparison.InvariantCultureIgnoreCase));

            default:
                return(false);
            }
        }
示例#25
0
        public void AddUpdateOrderPaymentToNebim(Core.Domain.Orders.Order order, string orderNumber)
        {
            var nebimIntegrationProvider = LoadNebimIntegrationServiceBySystemName("Misc.Nebim");
            int paymentType = 1;

            if (order.PaymentMethodSystemName == "Payments.PurchaseOrder")
            {
                paymentType = 2;
            }
            else
            {
                paymentType = 1;
            }
            int installment = order.Installment.HasValue ? order.Installment.Value : 1;

            installment = installment < 1 ? 1 : installment;
            string maskedCCno         = _encryptionService.DecryptText(order.MaskedCreditCardNumber);
            string provisionNo        = order.AuthorizationTransactionId;
            string creditCardTypeCode = null;

            if (paymentType == 1)// credit card
            {
                Dictionary <string, string> paymentMethodSystemNameCreditCardType = new Dictionary <string, string>();
                try
                {
                    foreach (var match in _NebimIntegrationSettings.PaymentMethodSystemName_API_CreditCardTypeCode.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        var codes = match.Split(new string[] { "--" }, StringSplitOptions.RemoveEmptyEntries);
                        paymentMethodSystemNameCreditCardType.Add(codes[0], codes[1]);
                    }
                    creditCardTypeCode = order.PaymentMethodSystemName == "" ? "indirim kuponu" : paymentMethodSystemNameCreditCardType[order.PaymentMethodSystemName];
                }
                catch (Exception ex)
                {
                    _logger.Error("Not able to match credit card type. Edit _NebimIntegrationSettings.PaymentMethodSystemName_API_CreditCardTypeCode", ex);
                }
            }
            nebimIntegrationProvider.AddUpdateOrderPaymentToNebim(orderNumber, paymentType, creditCardTypeCode, (byte)installment, maskedCCno, provisionNo);
        }
示例#26
0
        public async Task <MailUser> GetUserAccount(int userId)
        {
            if (userId <= 0)
            {
                _logger.Warn($"UserAccountService.GetUserAccount() invalid userId provided ({userId})");
                throw new ArgumentException($"Invalid userId provided: {userId}");
            }

            // fetch the user from the repository
            var userAccount = await _repo.GetUserAccount(userId);

            // ensure that we have a user to work with
            if (userAccount == null)
            {
                _logger.Debug($"UserAccountService.GetUserAccount() no user account found for userId ({userId})");
                return(null);
            }

            // we now need to decode the users password
            userAccount.Password = _encryption.DecryptText(userAccount.Password);

            return(userAccount);
        }
示例#27
0
        public Customer GetCurrentUser()
        {
            string sessionKey = WebConst.UserLoginSessionKey;
            var    user       = SessionHelper.Get <Customer>(sessionKey);

            if (user != null)
            {
                return(user);
            }

            string cookieKey = WebConst.UserLoginCookieKey;
            string username  = CookieHelper.Get(cookieKey);

            if (!username.IsEmpty())
            {
                username = encryService.DecryptText(username);
                user     = userRep.GetUser(username);
                if (user != null)
                {
                    SessionHelper.Add(sessionKey, user);
                }
            }
            return(user);
        }
        /// <summary>
        /// Screen an order transaction for payment fraud
        /// </summary>
        /// <param name="order">NopCommerce order object</param>
        /// <returns>OrderResult</returns>
        public OrderResult ScreenOrder(NopOrder order)
        {
            //whether plugin is configured
            if (string.IsNullOrEmpty(_fraudLabsProSettings.ApiKey))
            {
                throw new NopException($"Plugin not configured");
            }

            try
            {
                // Configure FraudLabs Pro API KEY
                FraudLabsProConfig.APIKey = _fraudLabsProSettings.ApiKey;

                var customer = _customerService.GetCustomerById(order.CustomerId);
                if (customer != null)
                {
                    var shippingAddress = _addressService.GetAddressById(order.ShippingAddressId ?? order.BillingAddressId);
                    var billingAddress  = _addressService.GetAddressById(order.BillingAddressId);

                    //prepare parameters
                    var screenOrderPara = new OrderPara();

                    //customer information
                    screenOrderPara.IPAddress    = customer.LastIpAddress ?? string.Empty;
                    screenOrderPara.FirstName    = ((billingAddress != null) ? billingAddress.FirstName : string.Empty) ?? string.Empty;
                    screenOrderPara.LastName     = ((billingAddress != null) ? billingAddress.LastName : string.Empty) ?? string.Empty;
                    screenOrderPara.UserPhone    = ((billingAddress != null) ? billingAddress.PhoneNumber : string.Empty) ?? string.Empty;
                    screenOrderPara.EmailAddress = ((billingAddress != null) ? billingAddress.Email : string.Empty) ?? string.Empty;
                    screenOrderPara.FLPCheckSum  = GetFLPCheckSum();

                    // Billing Information
                    if (billingAddress != null)
                    {
                        screenOrderPara.BillAddress = billingAddress.Address1 + " " + billingAddress.Address2;
                        screenOrderPara.BillCity    = billingAddress.City ?? string.Empty;
                        screenOrderPara.BillState   = _stateProvinceService.GetStateProvinceByAddress(billingAddress)?.Name ?? string.Empty;
                        screenOrderPara.BillCountry = _countryService.GetCountryByAddress(billingAddress)?.TwoLetterIsoCode ?? string.Empty;
                        screenOrderPara.BillZIPCode = billingAddress.ZipPostalCode ?? string.Empty;
                    }

                    // Shipping Information
                    if (shippingAddress != null)
                    {
                        screenOrderPara.ShippingAddress = shippingAddress.Address1 + " " + shippingAddress.Address2;
                        screenOrderPara.ShippingCity    = shippingAddress.City ?? string.Empty;
                        screenOrderPara.ShippingState   = _stateProvinceService.GetStateProvinceByAddress(shippingAddress)?.Name ?? string.Empty;
                        screenOrderPara.ShippingCountry = _countryService.GetCountryByAddress(shippingAddress)?.TwoLetterIsoCode ?? string.Empty;
                        screenOrderPara.ShippingZIPCode = shippingAddress.ZipPostalCode ?? string.Empty;
                    }

                    //Payment information
                    var cardNumber = _encryptionService.DecryptText(order.CardNumber);

                    if (!string.IsNullOrEmpty(cardNumber))
                    {
                        screenOrderPara.BinNo       = cardNumber.Substring(0, 6);
                        screenOrderPara.CardNumber  = cardNumber;
                        screenOrderPara.PaymentMode = Order.PaymentMethods.CREDIT_CARD;
                    }

                    // Order Information
                    screenOrderPara.Department    = _storeContext.CurrentStore.Name ?? string.Empty;
                    screenOrderPara.UserOrderID   = order.Id.ToString();
                    screenOrderPara.UserOrderMemo = order.OrderGuid.ToString();
                    screenOrderPara.Amount        = order.OrderTotal;
                    screenOrderPara.Quantity      = _orderService.GetOrderItems(order.Id).Sum(x => x.Quantity);
                    screenOrderPara.Currency      = order.CustomerCurrencyCode ?? string.Empty;

                    // ScreenOrder API
                    var screenOrder = new Order();
                    // Send order to FraudLabs Pro
                    var result = screenOrder.ScreenOrder(screenOrderPara);
                    _genericAttributeService.SaveAttribute(order, FraudLabsProDefaults.OrderResultAttribute, JsonConvert.SerializeObject(result));
                    _fraudLabsProSettings.Balance = result.FraudLabsProCredit;
                    _settingService.SaveSetting(_fraudLabsProSettings);

                    //save order status
                    _genericAttributeService.SaveAttribute(order, FraudLabsProDefaults.OrderStatusAttribute, result.FraudLabsProStatus);

                    UpdateOrerStatus(order, result.FraudLabsProStatus);

                    return(result);
                }
            }
            catch (Exception exception)
            {
                //log full error
                _logger.Error($"FraundLabs Pro ScreenOrder error: {exception.Message}.", exception, _workContext.CurrentCustomer);
            }
            return(null);
        }
示例#29
0
        public void OnActionExecuting(ActionExecutingContext context)
        {
            //Kontrol edilmesi gereken bir Action mı ? Mesela Login için bu işlem yapılmaz!
            if (HasIgnoreAttribute(context))
            {
                return;
            }

            bool.TryParse(context.HttpContext.Request.Headers["IsMobile"].FirstOrDefault(), out var isMobile);
            int.TryParse(context.HttpContext.Request.Headers["UserId"].FirstOrDefault(), out var userId);
            //Mobile için
            var unqDeviceId = context.HttpContext.Request.Headers["UnqDeviceId"].FirstOrDefault();

            //Tüm platformlar için gerekli kontrollerin yapılabilmesi için UserID şarttır.
            if (userId == 0)
            {
                context.Result = new UnauthorizedResult();
                return;
            }
            //Genel Kullanılacak değişkenler burada atanır.
            _workContext.CurrentUserId = userId;
            _workContext.IsMobile      = isMobile;
            //--------------------------------------

            string authHeader = context.HttpContext.Request.Headers["Authorization"];

            //Not: Bu durum sadece Web ortamı için geçerlidir. Mobilden her zaman Token gelmektedir.
            if (authHeader != null && authHeader.StartsWith("Bearer"))
            {
                //Extract credentials
                var token        = authHeader.Substring("Bearer ".Length).TrimStart();
                var decryptToken = _encryptionService.DecryptText(token);
                //Not: Bu durum sadece Web ortamı için geçerlidir. Mobilden her zaman Token gelmektedir. Hiçbir zaman timeout'a uğramaz. Tek fark 45 dakikadan büyük ise RefreshToken'da gönderilir.
                if (string.IsNullOrEmpty(decryptToken))// token yoksa UnauthorizedResult dönüyoruz. Bu sadece Web ortamı için geçerlidir. Mobilede her zaman Token dönülür. Gelmemiş ise ona da UnauthorizedResult dönülür.
                {
                    context.Result = new UnauthorizedResult();
                    return;
                }

                //İlgili UserID'ye ait Token Redis'den alınır.
                var cacheRedistoken = _redisCacheService.Get <string>(_redisCacheService.GetTokenKey(userId, isMobile, false, unqDeviceId));

                if (string.IsNullOrEmpty(cacheRedistoken) && isMobile) // Redis'de Token Key yok ise , bu durum SADECE MOBILE'DE BAKILMALIDIR.
                {
                    //Refresh Token kontrolü yapılır.
                    CreateTokensByCheckRefreshToken(context, true); //true'nun amacı  context.Result = new UnauthorizedResult() dönüşünün yapılmasının istenmesidir.
                    #region CreateTokensByCheckRefreshToken Methodu Altına Taşındı.
                    //if (context.HttpContext.Request.Headers["RefreshToken"].FirstOrDefault() != null) // client refresh token göndermiş.
                    //{
                    //    var clientRefreshToken = context.HttpContext.Request.Headers["RefreshToken"].FirstOrDefault();
                    //    var redisRefreshToken = _redisCacheService.Get<string>(_redisCacheService.GetTokenKey(userId, isMobile, true, unqDeviceId));

                    //    if (string.IsNullOrEmpty(redisRefreshToken))//rediste refresh token yok
                    //    {
                    //        context.Result = new UnauthorizedResult();
                    //        return;
                    //    }
                    //    var decClientRefreshToken = _encryptionService.DecryptText(clientRefreshToken);
                    //    if (decClientRefreshToken == redisRefreshToken)//Refresh Token doğru. Yeni token ve refresh token üretip dönelim.
                    //    {
                    //        UserModel user = _userService.GetById(userId).Entity;
                    //        var (encToken, decToken) = _encryptionService.GenerateToken(user.Email);
                    //        //Oluşturulsn Token Redis'e atılır.
                    //        var createTime = DateTime.Now;

                    //        //Token Oluşturulur. Mobilde ve Web'de 1 saattir. appsettings.json'a bakınız.
                    //        DateTime tokenExpireTime = createTime.AddMinutes(_coreContext.TokenExpireTime);
                    //        _redisCacheService.Set(_redisCacheService.GetTokenKey(userId, isMobile, false, unqDeviceId), decToken, tokenExpireTime);

                    //        //Geri dönülecek Encrypt Token ve Yaratılma zamanı Client'ın Header'ına atanır
                    //        context.HttpContext.Items["token"] = encToken;
                    //        context.HttpContext.Items["createdTokenTime"] = createTime.GetTotalMilliSeconds();

                    //        //RefreshToken Oluşturulur.
                    //        //Refresh Token Mobilde 1 Yıl, Web'de 1.5 saattir. appsettings.json'a bakınız.
                    //        var refreshToken = GenerateRefreshToken(user, context, unqDeviceId, isMobile);
                    //        if (!string.IsNullOrWhiteSpace(refreshToken))
                    //        {
                    //            //Oluşturulan RefreshToken Client'a dönülür.
                    //            context.HttpContext.Items["refreshToken"] = refreshToken;
                    //        }
                    //    }
                    //    else
                    //    {
                    //        context.Result = new UnauthorizedResult();
                    //        return;
                    //    }
                    //}
                    //else
                    //{
                    //    context.Result = new UnauthorizedResult();
                    //    return;
                    //}
                    #endregion
                }
                else if ((string.IsNullOrEmpty(cacheRedistoken)) || (!string.IsNullOrEmpty(cacheRedistoken) && cacheRedistoken.Trim() != decryptToken.Trim())) //Redis'de Token Yok Ya da Redis'de Token Var ama tokenlar eşit değil , geçerli bir oturum isteği değil.
                {
                    context.Result = new UnauthorizedResult();
                    return;
                }

                //Redis'in süresine bakılacak
                var tokenSession      = decryptToken.Split('ß')[2];
                var sessionCreateTime = DateTime.Parse(tokenSession);
                var remainingTime     = DateTime.Now - sessionCreateTime;

                //Tokenlar eşit , 45 ile 60'ıncı dakikalar arasındaysa token ve refresh token'ı yenileyip dönelim. Önemli Not: Redis Cache'de Token var ise!
                //if (remainingTime.TotalMinutes >= _coreContext.TokenExpireTime && remainingTime.TotalMinutes <= _coreContext.TokenExpireTime - 15)
                //if (remainingTime.TotalMinutes >= _coreContext.TokenExpireTime - 15 && remainingTime.TotalMinutes <= _coreContext.TokenExpireTime)
                if ((string.IsNullOrEmpty(cacheRedistoken) == false) && (remainingTime.TotalMinutes >= _coreContext.TokenExpireTime - 15 && remainingTime.TotalMinutes <= _coreContext.TokenExpireTime))
                {
                    CreateTokensByCheckRefreshToken(context);
                    #region CreateTokensByCheckRefreshToken Methodu Altına Taşındı.
                    //if (context.HttpContext.Request.Headers["RefreshToken"].FirstOrDefault() != null) // client refresh token göndermiş.
                    //{
                    //    var clientRefreshToken = context.HttpContext.Request.Headers["RefreshToken"].FirstOrDefault();
                    //    var redisRefreshToken = _redisCacheService.Get<string>(_redisCacheService.GetTokenKey(userId, isMobile, true, unqDeviceId));

                    //    if (string.IsNullOrEmpty(redisRefreshToken))//rediste refresh token yok
                    //    {
                    //        context.Result = new UnauthorizedResult();
                    //        return;
                    //    }
                    //    var decClientRefreshToken = _encryptionService.DecryptText(clientRefreshToken);
                    //    if (decClientRefreshToken == redisRefreshToken)//Refresh Token doğru. Yeni token ve refresh token üretip dönelim.
                    //    {
                    //        UserModel user = _userService.GetById(userId).Entity;
                    //        var (encToken, decToken) = _encryptionService.GenerateToken(user.Email);
                    //        //Oluşturulan Token Redis'e atılır.

                    //        var createTime = DateTime.Now;
                    //        DateTime tokenExpireTime = createTime.AddMinutes(_coreContext.TokenExpireTime);
                    //        _redisCacheService.Set(_redisCacheService.GetTokenKey(userId, isMobile, false, unqDeviceId), decToken, tokenExpireTime);

                    //        //Geri dönülecek Encrypt Token ve Yaratılma zamanı Client'ın Header'ına atanır
                    //        context.HttpContext.Items["token"] = encToken;
                    //        context.HttpContext.Items["createdTokenTime"] = createTime.GetTotalMilliSeconds();

                    //        //RefreshToken Oluşturulur.
                    //        //Refresh Token Mobilde 1 Yıl Web'de 1.5 saattir. appsettings.json'a bakınız.
                    //        var refreshToken = GenerateRefreshToken(user, context, unqDeviceId, isMobile);
                    //        if (!string.IsNullOrWhiteSpace(refreshToken))
                    //        {
                    //            //Oluşturulan RefreshToken Client'a dönülür.
                    //            context.HttpContext.Items["refreshToken"] = refreshToken;
                    //        }
                    //    }
                    //}
                    #endregion
                }
            }
            else
            {
                context.Result = new UnauthorizedResult();
                return;
            }

            //Log işlemleri
            if (HasLogAttribute(context))
            {
                string action     = (string)context.RouteData.Values["action"];
                string controller = (string)context.RouteData.Values["controller"];

                //Loglanacak Model Alınır
                foreach (ControllerParameterDescriptor param in context.ActionDescriptor.Parameters)
                {
                    if (param.ParameterInfo.CustomAttributes.Any(
                            attr => attr.AttributeType == typeof(FromBodyAttribute))
                        )
                    {
                        var entity = context.ActionArguments[param.Name];
                        context.HttpContext.Items[userId + "_" + controller + "_" + action] = entity;
                    }
                }
                //---------------------------------
            }
        }
        //protected virtual void PrintHeader(Document doc, Body body, string ReportName)
        //{
        //    var mainTable = new PdfPTable(new float[] { 80F, 30F })
        //    {
        //        RunDirection = PdfWriter.RUN_DIRECTION_LTR,
        //        WidthPercentage = 100f
        //    };
        //    mainTable.SpacingBefore = 4f;
        //    mainTable.HorizontalAlignment = Element.ALIGN_LEFT;

        //    #region Header Left
        //    PdfPCell leftTableCell = new PdfPCell();
        //    leftTableCell.Border = PdfPCell.NO_BORDER;
        //    //header
        //    var headerLeft = new PdfPTable(new float[] { 20F, 90F });
        //    headerLeft.WidthPercentage = 100f;
        //    headerLeft.SpacingAfter = 4f;
        //    headerLeft.DefaultCell.Border = Rectangle.NO_BORDER;

        //    headerLeft.AddCell(_pdfCommonSettings.GetLogoCell());
        //    //doc.Add(headerLeft);

        //    var cellHeader = _pdfCommonSettings.GetHeaderCell("Mobile Apheresis");
        //    cellHeader.MinimumHeight = 10;
        //    headerLeft.AddCell(cellHeader);

        //    var cellHeaderBody = _pdfCommonSettings.GetMainHeaderAddressCell("");
        //    cellHeaderBody.Border = Rectangle.NO_BORDER;

        //    headerLeft.AddCell(cellHeaderBody);

        //    leftTableCell.AddElement(headerLeft);
        //    mainTable.AddCell(leftTableCell);
        //    #endregion

        //    #region Header Right
        //    PdfPCell rightTableCell = new PdfPCell();
        //    rightTableCell.Border = PdfPCell.NO_BORDER;
        //    rightTableCell.HorizontalAlignment = Element.ALIGN_RIGHT;
        //    var headerRight = new PdfPTable(new float[] { 50F, 50F })
        //    {
        //        RunDirection = PdfWriter.RUN_DIRECTION_RTL,
        //        WidthPercentage = 100f
        //    };

        //    //headerRight.HorizontalAlignment = Element.ALIGN_RIGHT;
        //    //headerRight.DefaultCell.VerticalAlignment = Element.ALIGN_RIGHT;
        //    //headerRight.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;
        //    headerRight.DefaultCell.Border = Rectangle.NO_BORDER;
        //    var ReportNameCell = _pdfCommonSettings.GetReportHeaderCell(ReportName);
        //    ReportNameCell.MinimumHeight = 25;
        //    headerRight.AddCell(ReportNameCell);
        //    if (!string.IsNullOrEmpty(BarocdeID))
        //    {
        //        headerRight.AddCell(_pdfCommonSettings.GetBarcodeCell(BarocdeID, writer));
        //        headerRight.AddCell(_pdfCommonSettings.GetReportHeaderCell("    "));
        //        headerRight.AddCell(_pdfCommonSettings.GetBodyCell(text: BarocdeID, columnType: ColumnType.Text, RemoveBorder: true, IsHeader: true, IsTransparentBackground: true));
        //        headerRight.AddCell(_pdfCommonSettings.GetReportHeaderCell("    "));
        //    }

        //    rightTableCell.AddElement(headerRight);
        //    mainTable.AddCell(rightTableCell);
        //    #endregion
        //    doc.Add(mainTable);
        //}
        #endregion

        #region Treatment Record Word
        public void PrintTreatmentRecordToWord(Stream stream, TreatmentRecordsPaginationModel TreatmentReport)
        {
            using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document, true))
            {
                wordDoc.AddMainDocumentPart();
                // siga a ordem
                Document doc  = new Document();
                Body     body = new Body();

                TableWidth tableWidth = new TableWidth()
                {
                    Width = "5000", Type = TableWidthUnitValues.Pct
                };
                TableStyle tableStyle = new TableStyle()
                {
                    Val = "TableGrid",
                };
                Table table = new Table(tableStyle, tableWidth);
                // Make the table width 100% of the page width.



                table.AppendChild <TableProperties>(_wordDocCommonSetting.tableProperties());
                #region Table header
                //Header Table Row
                var headerTr = new TableRow();
                //Header Table column
                var Column1 = _wordDocCommonSetting.GetCell("Patient Name", "10");


                // Add cell shading.
                var shading = new Shading()
                {
                    Color = "auto",
                    Fill  = "ABCDEF",
                    Val   = ShadingPatternValues.Clear
                };

                Column1.Append(shading);
                headerTr.Append(Column1);

                var Column2 = _wordDocCommonSetting.GetCell("Nurse Name", "20");

                var shading1 = new Shading()
                {
                    Color = "auto",
                    Fill  = "ABCDEF",
                    Val   = ShadingPatternValues.Clear
                };

                Column2.Append(shading1);
                headerTr.Append(Column2);

                var Column3 = _wordDocCommonSetting.GetCell("Hospital Name", "30");

                var shading2 = new Shading()
                {
                    Color = "auto",
                    Fill  = "ABCDEF",
                    Val   = ShadingPatternValues.Clear
                };

                Column3.Append(shading2);
                headerTr.Append(Column3);

                var Column4 = _wordDocCommonSetting.GetCell("Contact Person", "40");

                var shading3 = new Shading()
                {
                    Color = "auto",
                    Fill  = "ABCDEF",
                    Val   = ShadingPatternValues.Clear
                };
                Column4.Append(shading3);
                headerTr.Append(Column4);

                var Column5 = _wordDocCommonSetting.GetCell("Doctor Name", "50");

                var shading5 = new Shading()
                {
                    Color = "auto",
                    Fill  = "ABCDEF",
                    Val   = ShadingPatternValues.Clear
                };
                Column5.Append(shading5);
                headerTr.Append(Column5);

                var Column6 = _wordDocCommonSetting.GetCell("Room", "10");

                var shading6 = new Shading()
                {
                    Color = "auto",
                    Fill  = "ABCDEF",
                    Val   = ShadingPatternValues.Clear
                };
                Column6.Append(shading6);
                headerTr.Append(Column6);

                var Column7 = _wordDocCommonSetting.GetCell("Equp Serial", "20");

                var shading7 = new Shading()
                {
                    Color = "auto",
                    Fill  = "ABCDEF",
                    Val   = ShadingPatternValues.Clear
                };
                Column7.Append(shading7);
                headerTr.Append(Column7);

                var Column8 = _wordDocCommonSetting.GetCell("Equp Name", "30");

                var shading8 = new Shading()
                {
                    Color = "auto",
                    Fill  = "ABCDEF",
                    Val   = ShadingPatternValues.Clear
                };
                Column8.Append(shading8);
                headerTr.Append(Column8);

                var Column9 = _wordDocCommonSetting.GetCell("PM Date", "40");

                var shading9 = new Shading()
                {
                    Color = "auto",
                    Fill  = "ABCDEF",
                    Val   = ShadingPatternValues.Clear
                };
                Column9.Append(shading9);
                headerTr.Append(Column9);

                var Column10 = _wordDocCommonSetting.GetCell("Treatment status", "50");

                var shading10 = new Shading()
                {
                    Color = "auto",
                    Fill  = "ABCDEF",
                    Val   = ShadingPatternValues.Clear
                };
                Column10.Append(shading10);
                headerTr.Append(Column10);

                table.Append(headerTr);
                #endregion

                #region Body


                foreach (var data in TreatmentReport.List)
                {
                    var BodyTr      = new TableRow();
                    var BodyColumn1 = new TableCell();
                    BodyColumn1.Append(new Paragraph(new Run(new Text((data.PateintName != null) ? _encryptionService.DecryptText(data.PateintName) : ""))));
                    // Assume you want BodyColumns that are automatically sized.
                    BodyColumn1.Append(new TableCellProperties(new TableCellWidth {
                        Type = TableWidthUnitValues.Auto
                    }));
                    BodyTr.Append(BodyColumn1);

                    var BodyColumn2 = new TableCell();
                    BodyColumn2.Append(new Paragraph(new Run(new Text(((data.NurseFirstName != null) ? _encryptionService.DecryptText(data.NurseFirstName) : "") + ((data.NurseLastName != null) ? _encryptionService.DecryptText(data.NurseLastName) : "")))));
                    // Assume you want BodyColumns that are automatically sized.
                    BodyColumn2.Append(new TableCellProperties(new TableCellWidth {
                        Type = TableWidthUnitValues.Auto
                    }));
                    BodyTr.Append(BodyColumn2);

                    var BodyColumn3 = new TableCell();
                    BodyColumn3.Append(new Paragraph(new Run(new Text((data.HospitalName != null) ? _encryptionService.DecryptText(data.HospitalName) : ""))));
                    // Assume you want BodyColumns that are automatically sized.
                    BodyColumn3.Append(new TableCellProperties(new TableCellWidth {
                        Type = TableWidthUnitValues.Auto
                    }));
                    BodyTr.Append(BodyColumn3);

                    var BodyColumn4 = new TableCell();
                    BodyColumn4.Append(new Paragraph(new Run(new Text((data.ContactPerson != null) ? _encryptionService.DecryptText(data.ContactPerson) : ""))));
                    // Assume you want BodyColumns that are automatically sized.
                    BodyColumn4.Append(new TableCellProperties(new TableCellWidth {
                        Type = TableWidthUnitValues.Auto
                    }));
                    BodyTr.Append(BodyColumn4);

                    var BodyColumn5 = new TableCell();
                    BodyColumn5.Append(new Paragraph(new Run(new Text((data.DoctorName != null) ? data.DoctorName : ""))));
                    // Assume you want BodyColumns that are automatically sized.
                    BodyColumn5.Append(new TableCellProperties(new TableCellWidth {
                        Type = TableWidthUnitValues.Auto
                    }));
                    BodyTr.Append(BodyColumn5);

                    var BodyColumn6 = new TableCell();
                    BodyColumn6.Append(new Paragraph(new Run(new Text((data.Room != null) ? data.Room : ""))));
                    // Assume you want BodyColumns that are automatically sized.
                    BodyColumn6.Append(new TableCellProperties(new TableCellWidth {
                        Type = TableWidthUnitValues.Auto
                    }));
                    BodyTr.Append(BodyColumn6);

                    var BodyColumn7 = new TableCell();
                    BodyColumn7.Append(new Paragraph(new Run(new Text((data.EquipSerial != null) ? _encryptionService.DecryptText(data.EquipSerial) : ""))));
                    // Assume you want BodyColumns that are automatically sized.
                    BodyColumn7.Append(new TableCellProperties(new TableCellWidth {
                        Type = TableWidthUnitValues.Auto
                    }));
                    BodyTr.Append(BodyColumn7);

                    var BodyColumn8 = new TableCell();
                    BodyColumn8.Append(new Paragraph(new Run(new Text((data.EquipmentName != null) ? data.EquipmentName : ""))));
                    // Assume you want BodyColumns that are automatically sized.
                    BodyColumn8.Append(new TableCellProperties(new TableCellWidth {
                        Type = TableWidthUnitValues.Auto
                    }));
                    BodyTr.Append(BodyColumn8);

                    var BodyColumn9 = new TableCell();
                    BodyColumn9.Append(new Paragraph(new Run(new Text((data.PMDate != null) ? Convert.ToDateTime(data.PMDate).ToShortDateString() : ""))));
                    // Assume you want BodyColumns that are automatically sized.
                    BodyColumn9.Append(new TableCellProperties(new TableCellWidth {
                        Type = TableWidthUnitValues.Auto
                    }));
                    BodyTr.Append(BodyColumn9);

                    var BodyColumn10 = new TableCell();
                    BodyColumn10.Append(new Paragraph(new Run(new Text((data.TreatmentStatusId != 0) ? ((TreatmentStatus)data.TreatmentStatusId).ToString() : ""))));
                    // Assume you want BodyColumns that are automatically sized.
                    BodyColumn10.Append(new TableCellProperties(new TableCellWidth {
                        Type = TableWidthUnitValues.Auto
                    }));

                    BodyTr.Append(BodyColumn10);
                    table.Append(BodyTr);
                }
                #endregion



                body.Append(table);

                doc.Append(body);


                wordDoc.MainDocumentPart.Document = doc;

                wordDoc.Close();
            }
        }