コード例 #1
0
        public IHttpActionResult Post(EmailAccountEntityModel entityModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            //create a new email account
            var emailAccount = new EmailAccount()
            {
                Id       = entityModel.Id,
                Email    = entityModel.Email,
                UserName = entityModel.UserName,
                FromName = entityModel.FromName,
                Host     = entityModel.Host,
                UseSsl   = entityModel.UseSsl,
                Port     = entityModel.Port,
                UseDefaultCredentials = entityModel.UseDefaultCredentials,
                Password = _cryptographyService.Encrypt(entityModel.Password)
            };

            //if this is the first account, we'll set it as default
            emailAccount.IsDefault = _emailAccountService.Count() == 0;

            //save it
            _emailAccountService.Insert(emailAccount);

            VerboseReporter.ReportSuccess("Successfully saved email account", "post_emailaccount");
            return(RespondSuccess(new {
                EmailAccount = emailAccount.ToEntityModel()
            }));
        }
コード例 #2
0
        public IActionResult Post([FromBody] CredentialViewModel param)
        {
            User requestor = _context.Users.SingleOrDefault(u => u.ApiKey == Request.Headers["X-ApiKey"]);

            if (requestor.IsAdmin)
            {
                if (ModelState.IsValid)
                {
                    Credential cred = new Credential
                    {
                        UserName = param.UserName,
                        Password = _cryptoService.Encrypt(param.Password)
                    };
                    _context.Credentials.Add(cred);
                    _context.SaveChanges();
                    return(Ok(cred));
                }
                else
                {
                    return(BadRequest(ModelState));
                }
            }
            else
            {
                throw new Exception("Only administrator users can add new credentials.");
            }
        }
コード例 #3
0
        public async Task <bool> VerifyUserPasswordAsync(long userId, string password, string salt)
        {
            LinUserIdentity userIdentity = await this.GetFirstByUserIdAsync(userId);

            string encryptPassword = _cryptographyService.Encrypt(password, salt);

            return(userIdentity != null && userIdentity.Credential == encryptPassword);
        }
コード例 #4
0
        public async Task <IResult> Handler(CadastrarUsuarioCommand command)
        {
            command.Validate();

            if (!command.Valid)
            {
                return(command.ValidationResult);
            }

            var usuario = await _repository.Usuario.GetUsuarioByNomeAsync(command.Nome);

            if (usuario != null)
            {
                return(new CommandResult(false, "Já existe um usuário com mesmo nome cadastrado", command.Notifications));
            }

            usuario = await _repository.Usuario.GetUsuarioByLoginAsync(command.Login);

            if (usuario != null)
            {
                return(new CommandResult(false, "Login já cadastrado", command.Notifications));
            }

            usuario = await _repository.Usuario.GetUsuarioBySiglaAsync(command.Sigla);

            if (usuario != null)
            {
                return(new CommandResult(false, "Já existe um usuário com a mesma sigla cadastrada", command.Notifications));
            }

            var setor = await _repository.Setor.GetSetorByIdAsync(command.SetorId);

            if (setor == null)
            {
                return(new CommandResult(false, "Setor não encontrado", command.Notifications));
            }

            var usuarioEntity = _mapper.Map <Usuario>(command);

            var passwordEncrypted = _cryptographyService.Encrypt(usuarioEntity.Senha);

            usuarioEntity.Setor = setor;
            usuarioEntity.Senha = passwordEncrypted;

            _repository.Usuario.Create(usuarioEntity);

            await _repository.SaveAsync();

            return(new CommandResult("Usuário cadastrado com sucesso!"));
        }
コード例 #5
0
        /// <summary>
        /// Adds a new PatientRecordEntry
        /// </summary>
        /// <param name="newPatientRecordEntry"></param>
        /// <returns></returns>
        public async Task <PatientNoteDto> AddPatientRecordEntryAsync(PatientNoteDto newPatientRecordEntry)
        {
            if (newPatientRecordEntry == null)
            {
                throw new ArgumentNullException(nameof(newPatientRecordEntry));
            }

            var newPatientRecordEntryString = JsonSerializer.Serialize(newPatientRecordEntry);
            var encryptedContent            = _cryptoSvc.Encrypt(newPatientRecordEntryString);

            var newPatientNote = new PatientNote()
            {
                PatientId             = newPatientRecordEntry.PatientId,
                MedicalPractitionerId = newPatientRecordEntry.MedicalPractitionerId,
                Timestamp             = newPatientRecordEntry.Timestamp,
                Content = encryptedContent
            };

            var result = await _noteDal.AddAsync(newPatientNote);

            if (result == null)
            {
                return(null);
            }

            newPatientRecordEntry.Id = result.Id;
            return(newPatientRecordEntry);
        }
コード例 #6
0
        public void CryptographyServiceEncrypt()
        {
            string guid            = Guid.NewGuid().ToString();
            string encrptypassword = _cryptographyService.Encrypt("123qwe", guid);

            _testOutputHelper.WriteLine($"guid:{guid},passowrd:{encrptypassword}");
        }
コード例 #7
0
        public async Task InvokeAsync(HttpContext context)
        {
            if (string.IsNullOrWhiteSpace(context.Request.ContentType))
            {
                //context.Response.StatusCode = (int) HttpStatusCode.BadRequest;
                //context.GetEndpoint();

                context.Request.ContentType = "text/plain";
                await _next(context);

                return;
            }

            var secureHeader = _configuration.GetValue <string>("AppSetting:SecureHeader"); // default is ft-ejson

            if (context.Request.ContentType != secureHeader)
            {
                await _next(context);

                return;
            }

            var encryptionKey = _configuration.GetValue <string>("AppSetting:ApiEncryptionKey");

            if (context.Response.ContentLength.GetValueOrDefault(0) == 0) // Input Request
            {
                using (var reader = new StreamReader(context.Request.Body, Encoding.UTF8))
                {
                    var cipherBody = reader.ReadToEnd();

                    var body = _securityService.Decrypt(cipherBody, encryptionKey);

                    context.Request.Body.Flush();

                    context.Request.Body.Write(Encoding.UTF8.GetBytes(body), 0, body.Length);
                }

                await _next(context);

                return;
            }
            else // Output Response
            {
                using (var reader = new StreamReader(context.Response.Body, Encoding.UTF8))
                {
                    var body       = reader.ReadToEnd();
                    var cipherBody = _securityService.Encrypt(body, encryptionKey);

                    context.Response.Body.Flush();

                    context.Response.Body.Write(Encoding.UTF8.GetBytes(cipherBody), 0, cipherBody.Length);
                    context.Response.ContentType = "ft-ejson";
                }

                await _next(context);

                return;
            }
        }
コード例 #8
0
        public void Set(HttpContext context, AuthenticationSessionViewModel sessionViewModel)
        {
            var cipherSession = _cryptographyService.Encrypt(sessionViewModel, _encryptionKey);

            var session = Encoding.UTF8.GetBytes(cipherSession);

            context.Session.Set(_sessionName, session);
        }
コード例 #9
0
        public async Task <Usuario> GetUsuarioAsync(string login, string password)
        {
            var passwordEncrypted = _cryptographyService.Encrypt(password);

            var usuario = await _repository.Usuario.GetUsuarioAsync(login, passwordEncrypted);

            return(usuario);
        }
コード例 #10
0
        public async Task SaveAsync <T>(string filename, T model)
        {
            var json = JsonConvert.SerializeObject(model);

            var encryptedJson = _cryptographyService.Encrypt(json);

            await _ioService.SaveAsync(filename, encryptedJson);
        }
コード例 #11
0
        public void Encrypt_Decrypt()
        {
            const string value = nameof(SecurityTests);

            var crypt = _cryptographyService.Encrypt(value);

            var decrypt = _cryptographyService.Decrypt(crypt);

            Assert.AreEqual(value, decrypt);
        }
コード例 #12
0
ファイル: GdprService.cs プロジェクト: iamravikumar/evencart
        public void SetUserConsents(int userId, Dictionary <int, ConsentStatus> consentPairs)
        {
            var allConsents = _consentService.Get(x => x.Published).ToList();

            var savedConsents       = GetUserConsents(userId);
            var user                = _userService.Get(userId);
            IList <ConsentLog> logs = new List <ConsentLog>();

            foreach (var(consentId, consentStatus) in consentPairs)
            {
                var consent = allConsents.FirstOrDefault(x => x.Id == consentId);
                if (consent == null || (consent.IsRequired && consentStatus != ConsentStatus.Accepted))
                {
                    continue;
                }
                var savedConsent = savedConsents.FirstOrDefault(x => x.ConsentId == consentId);
                var log          = false;
                if (savedConsent == null)
                {
                    savedConsent = new UserConsent()
                    {
                        ConsentId     = consentId,
                        UserId        = userId,
                        ConsentStatus = consentStatus
                    };
                    EntitySet <UserConsent> .Insert(savedConsent);

                    log = true;
                }
                else if (savedConsent.ConsentStatus != consentStatus)
                {
                    savedConsent.ConsentStatus = consentStatus;
                    EntitySet <UserConsent> .Update(savedConsent);

                    log = true;
                }

                if (consent.EnableLogging && log)
                {
                    //add to log
                    logs.Add(new ConsentLog()
                    {
                        ActivityType      = consentStatus == ConsentStatus.Accepted ? ActivityType.ConsentAccepted : ActivityType.ConsentDenied,
                        ConsentId         = consentId,
                        UserId            = userId,
                        CreatedOn         = DateTime.UtcNow,
                        EncryptedUserInfo = _cryptographyService.Encrypt(user.Email)
                    });
                }
            }

            //commit the logs to db
            _consentLogService.Insert(logs.ToArray());
        }
コード例 #13
0
    public void CryptographyService()
    {
        const string value = nameof(SecurityTests);

        var salt = Guid.NewGuid().ToString();

        var crypt = _cryptographyService.Encrypt(value, salt);

        var decrypt = _cryptographyService.Decrypt(crypt, salt);

        Assert.AreEqual(value, decrypt);
    }
コード例 #14
0
ファイル: HeroViewModel.cs プロジェクト: sthiakos/General
 internal HeroViewModel(Hero hero, ICryptographyService cryptographyService)
 {
     Id = cryptographyService.Encrypt(hero.Id);
     Name = hero.Name;
     FreeToPlayPeriods = hero
         .FreeToPlayPeriods
         .Select(ftpp => new FreeToPlayPeriodViewModel(ftpp, cryptographyService))
         .ToArray();
     Type = new HeroTypeViewModel(hero.Type, cryptographyService);
     State = new HeroStateViewModel(hero.State, cryptographyService);
     Created = hero.Created;
     Price = hero.Price;
 }
コード例 #15
0
        /// <summary>
        /// Gets the user.
        /// </summary>
        /// <returns></returns>
        public Domain.Model.User GetUser()
        {
            Domain.Model.User user = new Domain.Model.User
            {
                DisplayName = DisplayName,
                Email       = Email,
                FirstName   = FirstName,
                LastName    = LastName,
                Password    = _cryptographyService.Encrypt(Password),
                Username    = Username
            };

            return(user);
        }
コード例 #16
0
        public IActionResult SaveEmailAccount(EmailAccountModel model)
        {
            var emailAccount = model.Id > 0 ? _emailAccountService.Get(model.Id) : new EmailAccount();

            if (emailAccount == null)
            {
                return(NotFound());
            }

            _modelMapper.Map(model, emailAccount, nameof(EmailAccount.Id), nameof(EmailAccount.Password));
            if (!model.Password.IsNullEmptyOrWhiteSpace())
            {
                emailAccount.Password = _cryptographyService.Encrypt(model.Password);
            }
            _emailAccountService.InsertOrUpdate(emailAccount);
            if (model.IsDefault)
            {
                //mark all the others as non default
                _emailSenderSettings.DefaultEmailAccountId = emailAccount.Id;
                _settingService.Save(_emailSenderSettings, CurrentStore.Id);
            }
            return(R.Success.Result);
        }
コード例 #17
0
        public async Task <Unit> Handle(AddResourceCommand request, CancellationToken cancellationToken)
        {
            var collection = await _repository.GetbyId(request.CollectionId);

            if (collection != null)
            {
                var source = await _service.Encrypt(request.Id, request.Resource);

                collection.AddResource(request.Id, request.OwnerId, request.OwnerName,
                                       source, request.Name);
                await _repository.UpdateAsync(collection);
            }
            return(Unit.Value);
        }
コード例 #18
0
        /// <summary>
        /// Handles the PreSendRequestHeaders event of the context control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        public void ContextPreSendRequestHeaders(object sender, EventArgs e)
        {
            HttpCookie cookie = _context.Context.Items[SiteCookie.CookieName] as HttpCookie;

            if (cookie != null && !string.IsNullOrEmpty(cookie.Value))
            {
                HttpCookie calEmaCookie = new HttpCookie(SiteCookie.CookieName)
                {
                    Value = _cryptographyService.Encrypt(cookie.Value)
                };

                _context.Response.Cookies.Remove(SiteCookie.CookieName);
                _context.Response.Cookies.Add(calEmaCookie);
            }
        }
コード例 #19
0
ファイル: AccountService.cs プロジェクト: thayalan2k/SSO_App
        public bool Login(UserAuthenticate model)
        {
            if (model == null)
            {
                throw new Exception("User cannot be empty.");
            }

            if (string.IsNullOrEmpty(model.Username) ||
                string.IsNullOrEmpty(model.Password))
            {
                throw new Exception("Username or password cannot be empty.");
            }

            model.Password = _cryptographyService.Encrypt(model.Password);
            return(_accountRepository.VerifyUser(model));
        }
コード例 #20
0
        /// <summary>
        /// Sets the value.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="val">The val.</param>
        public void Set(string key, string val)
        {
            HttpCookie cookie = _contextBase.Items[_cookieName] as HttpCookie ??
                                (_contextBase.Request.Cookies[_cookieName] ??
                                 new HttpCookie(_cookieName));

            if (!string.IsNullOrEmpty(cookie.Value))
            {
                cookie = new HttpCookie(_cookieName, _cryptographyService.Decrypt(cookie.Value));
            }

            cookie.Values.Remove(key);
            cookie.Values[key] = val;

            _contextBase.Response.Cookies[_cookieName].Value = _cryptographyService.Encrypt(cookie.Value);
            _contextBase.Items[_cookieName] = _contextBase.Response.Cookies[_cookieName];
        }
コード例 #21
0
        public void Set(HttpContext context, AuthenticationCookieViewModel cookieViewModel, CookieOptions options)
        {
            var cipherAuthenticationCookie =
                _cryptographyService.Encrypt(cookieViewModel, _encryptionKey);


            if (!options.Expires.HasValue)
            {
                var timeSpan = cookieViewModel.RememberMe ? TimeSpan.FromDays(30) : TimeSpan.FromHours(1);
                options.Expires = DateTimeOffset.Now.Add(timeSpan);
            }

            if (!options.MaxAge.HasValue)
            {
                var maxAge = cookieViewModel.RememberMe ? TimeSpan.FromDays(180) : TimeSpan.FromDays(1);
                options.MaxAge = maxAge;
            }

            context.Response.Cookies.Append(cipherAuthenticationCookie, _cookieName, options);
        }
        private async Task <DocumentFile> BuildFromFileAsync(IFormFile file)
        {
            // detect image dimensions
            string dimensions = null;

            try
            {
                using (Stream fileStream = file.OpenReadStream())
                    using (Image image = Image.FromStream(fileStream, false, true))
                        dimensions = $"{image.Width},{image.Height}";
            }
            catch { }

            // copy file
            FileInfo fileInfo = new FileInfo(_settings.BuildFilePath(GenerateUniqueFileName()));

            // copy in resources folder
            using (var stream = new FileStream(fileInfo.FullName, FileMode.Create))
                await file.CopyToAsync(stream);

            // encrypt file
            string iv = Guid.NewGuid().ToString().AsSpan(0, 16).ToString();

            byte[] cipher = _cryptographyService.Encrypt(await File.ReadAllBytesAsync(fileInfo.FullName), Encoding.UTF8.GetBytes(_settings.EncryptKey), Encoding.UTF8.GetBytes(iv));
            await File.WriteAllBytesAsync(fileInfo.FullName, cipher);

            // create document file
            DocumentFile result = new DocumentFile
            {
                OriginalName = file.FileName,
                Path         = fileInfo.Name,
                Encryption   = _cryptographyService.Name,
                IV           = iv,
                Size         = fileInfo.Length,
                Dimensions   = dimensions,
                MimeType     = file.ContentType,
            };

            return(result);
        }
コード例 #23
0
        public async Task CreateAsync(LinUser user, List <long> groupIds, string password)
        {
            if (!string.IsNullOrEmpty(user.Username))
            {
                bool isRepeatName = await _userRepository.Select.AnyAsync(r => r.Username == user.Username);

                if (isRepeatName)
                {
                    throw new LinCmsException("用户名重复,请重新输入", ErrorCode.RepeatField);
                }
            }

            if (!string.IsNullOrEmpty(user.Email.Trim()))
            {
                var isRepeatEmail = await _userRepository.Select.AnyAsync(r => r.Email == user.Email.Trim());

                if (isRepeatEmail)
                {
                    throw new LinCmsException("注册邮箱重复,请重新输入", ErrorCode.RepeatField);
                }
            }
            user.Salt = Guid.NewGuid().ToString();
            string encryptPassword = _cryptographyService.Encrypt(password, user.Salt);

            user.LinUserGroups = new List <LinUserGroup>();
            groupIds?.ForEach(groupId =>
            {
                user.LinUserGroups.Add(new LinUserGroup()
                {
                    GroupId = groupId
                });
            });
            user.LinUserIdentitys = new List <LinUserIdentity>()
            {
                new LinUserIdentity(LinUserIdentity.Password, user.Username, encryptPassword, DateTime.Now)
            };
            await _userRepository.InsertAsync(user);
        }
コード例 #24
0
ファイル: Program.cs プロジェクト: tqhuy1811/Samples
        private async static Task RunAsync()
        {
            Console.WriteLine($"Plain Text: {PlainText}");

            OneWayEncrpytionService = new MD5CryptographyService();
            var hash = OneWayEncrpytionService.Encrypt(PlainText);
            Console.WriteLine($"MD5 Hashed: {hash}");

            OneWayEncrpytionService = new HashCryptographyService(new SHA1Managed());
            hash = OneWayEncrpytionService.Encrypt(PlainText);
            Console.WriteLine($"SHA1 Hashed: {hash}");

            var symmetricAlgorithmCryptographyService =
            new SymmetricAlgorithmCryptographyService(
                new AesCryptoServiceProvider
                {
                    Mode = CipherMode.CBC,
                    KeySize = 128,
                    Key = Encoding.UTF8.GetBytes("1234567890123456"),
                    IV = Encoding.UTF8.GetBytes("0234567890123456")
                });

            CryptographyService = symmetricAlgorithmCryptographyService;
            var encryptedText = CryptographyService.Encrypt(PlainText);
            Console.WriteLine($"AES Encrypted: {encryptedText}");

            var decryptedText = CryptographyService.Decrypt(encryptedText).Trim();
            Console.WriteLine($"AES Decrypted: {decryptedText}");

            const string filename = "Credentials.txt";
            var encryptedPersister = new EncryptedPersister(CryptographyService, new FileIOService());
            await encryptedPersister.SaveAsync(filename, new Credentials { Username = "******", Password = "******" });
            var credentials = await encryptedPersister.LoadAsync<Credentials>(filename);

            Console.WriteLine($"AES Encrypted File: {await File.ReadAllTextAsync(filename)}");
            Console.WriteLine($"AES Decrypted Credentials Username: {credentials.Username} Password: {credentials.Password}");
        }
コード例 #25
0
        public ActionResult Index(string username, AccountDetailsView detailsView)
        {
            IDictionary <string, string> crumbs = GetBreadCrumbs("details", UrlService.UserUrl("account"));

            if (ModelState.IsValid)
            {
                detailsView.Password = _cryptographyService.Encrypt(detailsView.Password);
                Domain.Model.User savedUser = detailsView.GetUser();
                savedUser.Settings = Owner.Settings;
                savedUser.Id       = Owner.Id;
                _userRepository.Save(savedUser);

                detailsView.UIMessage           = "Account details saved.";
                detailsView.Password            = _cryptographyService.Decrypt(savedUser.Password);
                detailsView                     = SetAuthorizationAndUrlService(detailsView);
                detailsView.Authorization.Owner = savedUser;
            }
            else
            {
                ValidationHelper.ValidationHackRemoveNameAndBlankKey(ModelState);
            }

            return(View(detailsView, crumbs));
        }
コード例 #26
0
ファイル: HeroTypeViewModel.cs プロジェクト: sthiakos/General
 internal HeroTypeViewModel(HeroType heroType, ICryptographyService cryptographyService)
 {
     Id = cryptographyService.Encrypt(heroType.Id);
     Name = heroType.Name;
 }
コード例 #27
0
 internal FreeToPlayPeriodViewModel(FreeToPlayPeriod freeToPlayPeriod, ICryptographyService cryptographyService)
 {
     Id = cryptographyService.Encrypt(freeToPlayPeriod.Id);
     Begin = freeToPlayPeriod.Begin;
     End = freeToPlayPeriod.End;
 }
コード例 #28
0
        public IActionResult PaymentInfoSave(PaymentMethodModel requestModel)
        {
            Order order = null;
            Cart  cart  = null;

            if (!requestModel.OrderGuid.IsNullEmptyOrWhiteSpace())
            {
                order = _orderService.GetByGuid(requestModel.OrderGuid);
                if (order == null || order.PaymentStatus != PaymentStatus.Pending)
                {
                    return(R.Fail.With("error", T("The order has been already paid")).Result);
                }
            }
            else
            {
                if (!CanCheckout(out cart))
                {
                    return(R.Fail.Result);
                }
            }

            if (order == null && cart == null)
            {
                return(R.Fail.Result);
            }
            var paymentMethodRequired = true;

            //can we use store credits
            if (_affiliateSettings.AllowStoreCreditsForPurchases && requestModel.UseStoreCredits)
            {
                //get the balance
                var balance = _storeCreditService.GetBalance(CurrentUser.Id);
                paymentMethodRequired = _affiliateSettings.MinimumStoreCreditsToAllowPurchases > balance || balance < (order?.OrderTotal ?? cart.FinalAmount);
            }

            IPaymentHandlerPlugin paymentHandler = null;
            var formAsDictionary =
                requestModel.FormCollection.Keys.ToDictionary(x => x, x => requestModel.FormCollection[x].ToString());

            if (paymentMethodRequired)
            {
                //check if payment method is valid
                paymentHandler = PluginHelper.GetPaymentHandler(requestModel.SystemName);
                if (paymentHandler == null)
                {
                    return(R.Fail.With("error", T("Payment method unavailable")).Result);
                }

                if (!paymentHandler.ValidatePaymentInfo(formAsDictionary, out string error))
                {
                    return(R.Fail.With("error", error).Result);
                }
            }


            CustomResponse response;

            if (order != null)
            {
                order.PaymentMethodName = requestModel.SystemName;
                order.PaymentMethodFee  = paymentMethodRequired ? paymentHandler.GetPaymentHandlerFee(order) : 0;
                order.OrderTotal        = order.Subtotal + order.Tax + (order.PaymentMethodFee ?? 0) + (order.ShippingMethodFee ?? 0);
                //check if discount is available
                if (order.DiscountId.HasValue)
                {
                    if (_priceAccountant.CanApplyDiscount(order.DiscountId.Value, order.UserId, out _))
                    {
                        order.OrderTotal -= order.Discount;
                    }
                }
                _orderService.Update(order);
                var creditAmount = 0m;
                if (requestModel.UseStoreCredits)
                {
                    //do we have available credit
                    GetAvailableStoreCredits(out _, out creditAmount, ApplicationEngine.BaseCurrency, null);
                }
                //process the payment immediately
                ProcessPayment(order, creditAmount, formAsDictionary.ToDictionary(x => x.Key, x => (object)x.Value), out response);
                return(response.Result);
            }
            else
            {
                //if we are here, the payment method can be saved
                cart.PaymentMethodName = paymentMethodRequired ? requestModel.SystemName : "";
                //always store encrypted information about payment data
                cart.PaymentMethodData        = _cryptographyService.Encrypt(_dataSerializer.Serialize(formAsDictionary));
                cart.PaymentMethodDisplayName = paymentMethodRequired ? paymentHandler.PluginInfo.Name : "Store Credits";
                cart.UseStoreCredits          = requestModel.UseStoreCredits;
                _cartService.Update(cart);

                RaiseEvent(NamedEvent.OrderPaymentInfoSaved, cart);
            }

            response = R.Success;
            if (!requestModel.OrderGuid.IsNullEmptyOrWhiteSpace())
            {
                response.With("orderGuid", requestModel.OrderGuid);
            }
            return(response.Result);
        }
コード例 #29
0
        public string Encrypt(T content, string salt)
        {
            var serializedContent = JsonConvert.SerializeObject(content);

            return(cryptoService.Encrypt(serializedContent, salt));
        }
コード例 #30
0
        public IHttpActionResult ProcessPayment(FormCollection parameters)
        {
            //first get the payment processor
            var paymentMethodName = parameters.Get(PaymentParameterNames.PaymentMethodTypeName);

            if (string.IsNullOrEmpty(paymentMethodName))
            {
                VerboseReporter.ReportError("Invalid payment method", "process_payment");
                return(RespondFailure());
            }

            //the transaction amount
            decimal amount;
            var     amountString = parameters.Get(PaymentParameterNames.Amount) ?? "0";

            decimal.TryParse(amountString, out amount);

            PaymentMethodType methodType;

            if (System.Enum.TryParse(paymentMethodName, out methodType))
            {
                methodType = PaymentMethodType.CreditCard;
            }

            //get the payment processor now
            var paymentProcessor = _paymentProcessingService.GetPaymentProcessorPlugin(amount, methodType);

            if (paymentProcessor == null)
            {
                VerboseReporter.ReportError("Invalid payment method", "process_payment");
                return(RespondFailure());
            }

            //convert form collection to dictionary to check if parameters are valid
            var formCollectionDictionary = parameters.ToDictionary(pair => pair.Key, pair => (object)pair.Value);

            var isValid = paymentProcessor.AreParametersValid(formCollectionDictionary);

            UserPaymentMethod paymentMethod = null;

            if (!isValid)
            {
                //the parameters are not valid. but that may also mean that the user is selecting an already saved payment method
                //and so he wouldn't have sent that data again
                var savedPaymentMethodIdString = parameters.Get(PaymentParameterNames.UserSavedPaymentMethodId);
                int savedPaymentMethodId;
                if (int.TryParse(savedPaymentMethodIdString, out savedPaymentMethodId))
                {
                    var userPaymentMethods =
                        _paymentMethodService.Get(x => x.UserId == ApplicationContext.Current.CurrentUser.Id && x.Id == savedPaymentMethodId, null);

                    if (userPaymentMethods.Any())
                    {
                        paymentMethod = userPaymentMethods.First();
                        isValid       = true;
                    }
                }
                //still invalid? something is not right then.
                if (!isValid)
                {
                    VerboseReporter.ReportError("Invalid parameters to process payment", "process_payment");
                    return(RespondFailure());
                }
            }

            //we save the payment method in our database if it's CreditCard
            if (paymentProcessor.Supports(PaymentMethodType.CreditCard))
            {
                if (paymentMethod == null)
                {
                    #region saving payment method to database
                    var creditCardNumber = parameters.Get(PaymentParameterNames.CardNumber);
                    //let's validate the card for level 1 check (luhn's test) first before storing
                    var isCardValid = PaymentCardHelper.IsCardNumberValid(creditCardNumber);
                    //card number
                    if (!isCardValid)
                    {
                        VerboseReporter.ReportError("Invalid card number", "process_payment");
                        return(RespondFailure());
                    }
                    //expiration date
                    var expireMonth = parameters.Get(PaymentParameterNames.ExpireMonth);
                    var expireYear  = parameters.Get(PaymentParameterNames.ExpireYear);
                    if (!expireYear.IsInteger() || !expireMonth.IsInteger())
                    {
                        VerboseReporter.ReportError("Invalid expiration month or year", "process_payment");
                        return(RespondFailure());
                    }
                    //card issuer
                    var cardIssuer = PaymentCardHelper.GetCardTypeFromNumber(creditCardNumber);
                    if (!cardIssuer.HasValue)
                    {
                        VerboseReporter.ReportError("Unsupported card provider", "process_payment");
                        return(RespondFailure());
                    }


                    var nameOnCard = parameters.Get(PaymentParameterNames.NameOnCard);
                    //encrypt credit card info to store in db
                    var key  = ConfigurationManager.AppSettings.Get("EncryptionKey");
                    var salt = ConfigurationManager.AppSettings.Get("Salt");

                    var cardNumber = _cryptographyService.Encrypt(creditCardNumber, key, salt); //encrypt the card info
                    //fine if the card is valid, but is the card number already in our record, then not possible to save the same again
                    if (_paymentMethodService.DoesCardNumberExist(cardNumber))
                    {
                        VerboseReporter.ReportError("The card number is already saved in records", "process_payment");
                        return(RespondFailure());
                    }

                    paymentMethod = new UserPaymentMethod()
                    {
                        UserId            = ApplicationContext.Current.CurrentUser.Id,
                        IsVerified        = false,
                        PaymentMethodType = PaymentMethodType.CreditCard,
                        CardIssuerType    = cardIssuer.ToString().ToLowerInvariant(),
                        CardNumber        = creditCardNumber,
                        CardNumberMasked  = PaymentCardHelper.MaskCardNumber(creditCardNumber),
                        NameOnCard        = nameOnCard,
                    };
                    //save this payment method
                    _paymentMethodService.Insert(paymentMethod);
                    #endregion
                }
            }


            //we need to see if we should only authorize or capture as well
            //the idea is if it's a sponsorship context, it's better to authorize the payment transaction and capture later when
            //the sponsorship is accepted //we thought of initially only authorizing sponsorship transactions and capture when it's accepted.
            //but that flow doesn't seem to work quite well, thoughts?
            var authorizeOnly = false; // (parameters.Get(PaymentParameterNames.PaymentContext) ?? string.Empty) == "sponsor";

            //so we are ready for payment processing, let's create a paymenttrasaction for storing in our db
            var paymentTransaction = new PaymentTransaction()
            {
                IsLocalTransaction = true,
                PaymentStatus      = PaymentStatus.Pending,
                TransactionAmount  = amount,
                TransactionGuid    = Guid.NewGuid(),
                CreatedOn          = DateTime.UtcNow,
                UserIpAddress      = WebHelper.GetClientIpAddress()
            };
            _paymentTransactionService.Insert(paymentTransaction);

            //now proceed further with the payment
            //create the transaction request
            var transactionRequest = new TransactionRequest()
            {
                Amount                     = amount,
                CurrencyIsoCode            = "USD",//TODO: SET CURRENCY AS SELECTED BY USER
                PaymentProcessorSystemName = paymentProcessor.PluginInfo.SystemName,
                UserId                     = ApplicationContext.Current.CurrentUser.Id,
                Parameters                 = formCollectionDictionary,
                TransactionUniqueId        = paymentTransaction.TransactionGuid.ToString()
            };


            var response = paymentProcessor.Process(transactionRequest, authorizeOnly);
            //update values of transaction parameters for future reference
            paymentTransaction.TransactionCodes = response.ResponseParameters;
            //update payment transaction
            _paymentTransactionService.Update(paymentTransaction);

            if (response.Success)
            {
                //let's verify the payment method first if it's not
                if (paymentMethod != null && !paymentMethod.IsVerified)
                {
                    paymentMethod.IsVerified = true;
                    _paymentMethodService.Update(paymentMethod);
                }

                //now since the response was success, we can actually assign some credits to the user
                var creditCount = amount * (1 / _paymentSettings.CreditExchangeRate);
                var credit      = new Credit()
                {
                    PaymentTransactionId = paymentTransaction.Id,
                    CreatedOnUtc         = DateTime.UtcNow,
                    CreditCount          = creditCount,
                    CreditExchangeRate   = _paymentSettings.CreditExchangeRate,
                    //if it's authorize only transaction, we assign the credits, but they won't be usable before they are approved by capture
                    CreditTransactionType = CreditTransactionType.Issued,
                    CreditType            = CreditType.Transactional,
                    IsExpired             = false
                };

                //save credit
                _creditService.Insert(credit);

                //get total available credits of user
                var usableCreditCount = _creditService.GetUsableCreditsCount(ApplicationContext.Current.CurrentUser.Id);
                return(RespondSuccess(new {
                    UsableCreditCount = usableCreditCount
                }));
            }
            VerboseReporter.ReportError("An error occured while processing payment", "process_payment");
            return(RespondFailure());
        }
コード例 #31
0
 public string Encrypt(string text)
 {
     return(_cryptographyService.Encrypt(text, configuration["Authentication:SecretKey"]));
 }