Ejemplo n.º 1
0
        public ActionResult Index()
        {
            IDictionary <string, string> crumbs = GetBreadCrumbs("details", UrlService.UserUrl("account"));
            string             password         = _cryptographyService.Decrypt(Owner.Password);
            AccountDetailsView view             = ModelFactory <AccountDetailsView>(new { password, Confirm = password });

            view.Populate(Owner);

            return(View(view, crumbs));
        }
Ejemplo n.º 2
0
        public AuthenticationCookieViewModel Get(HttpContext context)
        {
            var encryptedAuthCookie = context.Request.Cookies[_cookieName];

            if (string.IsNullOrWhiteSpace(encryptedAuthCookie))
            {
                return(null);
            }

            var authenticationCookie =
                _cryptographyService.Decrypt <AuthenticationCookieViewModel>(encryptedAuthCookie, _encryptionKey) ??
                _cryptographyService.Decrypt <AuthenticationCookieViewModel>(encryptedAuthCookie, _oldEncryptionKey);

            return(authenticationCookie);
        }
Ejemplo n.º 3
0
        public static void RegisterServices(ContainerBuilder builder)
        {
            // Common
            builder.RegisterType <CodereCryptographyService>().As <ICryptographyService>().SingleInstance();
            builder.RegisterType <UniqueKeyProvider>().As <IUniqueKeyProvider>().SingleInstance();
            builder.RegisterType <Logger>().As <ILogger>().SingleInstance();

            // Configuration
            //builder.RegisterType<CodereIdLicenseConfigProvider>().As<ILicenseConfigProvider>().InstancePerRequest();
            builder.RegisterType <LicenseConfig>().As <ILicenseConfig>().SingleInstance();

            // Dynamics
            builder
            .Register(x =>
            {
                var connectionString = ConfigurationManager.AppSettings["CrmConnectionString"];
                if (ConfigurationManager.AppSettings["CrmConnectionStringIsEncrypted"] == "true")
                {
                    ICryptographyService cryptographyService = x.Resolve <ICryptographyService>();
                    connectionString = cryptographyService.Decrypt(connectionString);
                }
                CrmConnection connection = CrmConnection.Parse(connectionString);
                return(new OrganizationService(connection));
            })
            .As <IOrganizationService>()
            .InstancePerRequest();
            builder.RegisterGeneric(typeof(BaseRepository <>)).As(typeof(IDynamicsRepository <>)).InstancePerRequest();

            // Services
            builder.RegisterType <ServiceTest>().As <IServiceTest>().InstancePerRequest();
        }
Ejemplo n.º 4
0
        public T Decrypt(string encryptedContent, string salt)
        {
            var decryptedContent = cryptoService.Decrypt(encryptedContent, salt);
            var content          = JsonConvert.DeserializeObject <T>(decryptedContent);

            return(content);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Retrieves the values.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns></returns>
        public string Get(string key)
        {
            string     val    = string.Empty;
            HttpCookie cookie = _contextBase.Request.Cookies[_cookieName];

            if (cookie != null)
            {
                if (!string.IsNullOrEmpty(cookie.Value))
                {
                    cookie = new HttpCookie(_cookieName, _cryptographyService.Decrypt(cookie.Value));
                    val    = cookie[key];
                }
            }

            return(val);
        }
Ejemplo n.º 6
0
        public async Task <UserInfo> GetCurrentUserInfo()
        {
            if (Connectivity.NetworkAccess == NetworkAccess.Internet)
            {
                var userInfo = await _client.InvokeApiAsync <UserInfo>(
                    "UserInfo/GetOrCreateUserInfo",
                    HttpMethod.Get,
                    null
                    ).ConfigureAwait(false);

                if (string.IsNullOrWhiteSpace(userInfo?.DevicePIN))
                {
                    return(userInfo);
                }

                userInfo.DevicePIN = _cryptographyService.Decrypt(
                    _pinCryptographicKey,
                    userInfo.DevicePIN
                    );

                return(userInfo);
            }
            else
            {
                throw new System.Exception("No Internet connectivity - avoid this operation");
            }
        }
Ejemplo n.º 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;
            }
        }
Ejemplo n.º 8
0
        public async Task <T> LoadAsync <T>(string filename)
        {
            var encryptedJson = await _ioService.LoadAsync(filename);

            var plainTextJson = _cryptographyService.Decrypt(encryptedJson);

            var model = JsonConvert.DeserializeObject <T>(plainTextJson);

            return(model);
        }
Ejemplo n.º 9
0
        public void Encrypt_Decrypt()
        {
            const string value = nameof(SecurityTests);

            var crypt = _cryptographyService.Encrypt(value);

            var decrypt = _cryptographyService.Decrypt(crypt);

            Assert.AreEqual(value, decrypt);
        }
Ejemplo n.º 10
0
        private async Task OnRefresh(object arg)
        {
            foreach (var mailAccount in await UnitOfWork.MailAccountRepository.GetAllQuery().ToListAsync())
            {
                using (var client = new ImapClient())
                {
                    //TODO use secure socket options
                    await client.ConnectAsync(mailAccount.Host, mailAccount.Port, true);

                    await client.AuthenticateAsync(mailAccount.Username, _cryptographyService.Decrypt(mailAccount.Password));

                    var inbox = client.Inbox;
                    await inbox.OpenAsync(FolderAccess.ReadOnly);

                    var query = SearchQuery.DeliveredAfter(DateTime.Now - TimeSpan.FromDays(30));
                    var i     = 0;
                    foreach (var uid in inbox.Search(query))
                    {
                        var message     = inbox.GetMessage(uid);
                        var mailMessage = UnitOfWork.MailMessageRepository.GetAllQuery().FirstOrDefault(x => x.MessageId == message.MessageId);
                        if (mailMessage == null)
                        {
                            mailMessage = UnitOfWork.MailMessageRepository.CreateNew();
                            _mailMessageService.MapMimeMessageToMailMessage(message, mailMessage);
                            mailMessage.MailContact = _mailContactService.GetMailContactBy(message);
                            UnitOfWork.MailMessageRepository.Add(mailMessage);
                        }
                        else
                        {
                            if (mailMessage.MailContact == null)
                            {
                                mailMessage.MailContact = _mailContactService.GetMailContactBy(message);
                                UnitOfWork.MailMessageRepository.Update(mailMessage);
                            }
                        }

                        if (i++ % 50 == 0 && UnitOfWork.HasChanges())
                        {
                            await UnitOfWork.SaveChangesAsync();
                        }
                    }

                    await client.DisconnectAsync(true);
                }

                if (UnitOfWork.HasChanges())
                {
                    await UnitOfWork.SaveChangesAsync();
                }
            }

            Items.Clear();
            await OnLoadedAsync(null);
        }
Ejemplo n.º 11
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);
    }
Ejemplo n.º 12
0
        /// <summary>
        /// Retrieves the patient records for a medical practitioner was the author
        /// </summary>
        /// <param name="patientId"></param>
        /// <param name="medicalPractitionerId"></param>
        /// <returns></returns>
        public List <PatientNoteDto> RetrievePatientRecords(int patientId, int medicalPractitionerId)
        {
            if (patientId <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(patientId));
            }

            if (medicalPractitionerId <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(medicalPractitionerId));
            }

            // Get only the patient notes authored by the incoming medicalPractitionerId
            var result = _noteDal.Filter(x => x.PatientId == patientId &&
                                         x.MedicalPractitionerId == medicalPractitionerId);

            // Decrypt and deserialize the content of the patient notes
            var decryptedNoteStrings = result.Select(x => _cryptoSvc.Decrypt(x.Content));

            var deserializedNotes = decryptedNoteStrings.Select(y => JsonSerializer.Deserialize <PatientNoteDto>(y));

            return(deserializedNotes.OrderByDescending(x => x?.Timestamp).ToList());
        }
        public AuthenticationSessionViewModel Get(HttpContext context)
        {
            try
            {
                if (!context.Session.TryGetValue(_sessionName, out var sessionBytes))
                {
                    return(null);
                }

                var encryptedAuthSession = Encoding.UTF8.GetString(sessionBytes);

                var session =
                    _cryptographyService.Decrypt <AuthenticationSessionViewModel>(encryptedAuthSession, _encryptionKey) ??
                    _cryptographyService.Decrypt <AuthenticationSessionViewModel>(encryptedAuthSession, _oldEncryptionKey);

                return(session);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Ejemplo n.º 14
0
        public Credential Get([FromRoute] Guid Id)
        {
            User requestor = _context.Users.SingleOrDefault(u => u.ApiKey == Request.Headers["X-ApiKey"]);

            if (requestor.IsAdmin)
            {
                Credential cred = _context.Credentials.SingleOrDefault(c => c.Id == Id);
                cred.Password = _cryptoService.Decrypt(cred.Password);
                return(cred);
            }
            else
            {
                throw new Exception("Only administrator users can enumerate credentials.");
            }
        }
Ejemplo n.º 15
0
        private void KickOffCim(Computer computer, Credential credential, string commandline, CimSessionOptions options)
        {
            // Convert stored password to a secure string
            SecureString securePwd = new SecureString();

            foreach (char c in _cryptoService.Decrypt(credential.Password))
            {
                Console.WriteLine("[char]: {0}", c);
                securePwd.AppendChar(c);
            }

            CimCredential cimCreds = null;

            if (credential.UserName.Contains('\\'))
            {
                // Create a CimCredential object
                cimCreds = new CimCredential(PasswordAuthenticationMechanism.Kerberos, credential.UserName.Split('\\')[0], credential.UserName.Split('\\')[1], securePwd);
            }
            else
            {
                // Create a CimCredential object
                cimCreds = new CimCredential(PasswordAuthenticationMechanism.Default, null, credential.UserName, securePwd);
            }

            // Create a CimSession with the remote system
            options.AddDestinationCredentials(cimCreds);
            CimSession session = CimSession.Create(computer.ComputerName, options);

            // Create a CimMethodParametersCollection to pass to method invocation
            CimMethodParametersCollection collection = new CimMethodParametersCollection
            {
                CimMethodParameter.Create("CommandLine", commandline, CimFlags.None)
            };

            CimMethodResult result = session.InvokeMethod("root/cimv2", "Win32_Process", "Create", collection);

            if (result.ReturnValue.ToString() == "0")
            {
            }
            else
            {
            }

            session.Dispose();
        }
Ejemplo n.º 16
0
        public IEnumerable <Credential> Get()
        {
            User requestor = _context.Users.SingleOrDefault(u => u.ApiKey == Request.Headers["X-ApiKey"]);

            if (requestor.IsAdmin)
            {
                foreach (Credential cred in _context.Credentials)
                {
                    Console.WriteLine(_cryptoService.Decrypt(cred.Password));
                }

                return(_context.Credentials);
            }
            else
            {
                throw new Exception("Only administrator users can enumerate credentials.");
            }
        }
Ejemplo n.º 17
0
        public async Task <EncryptedValue> Handle(GetEncryptedResourceCommand request, CancellationToken cancellationToken)
        {
            var collection = await _repository.GetbyId(request.CollectionId);

            if (collection != null)
            {
                var resource       = collection.ReadResource(request.ResourceId, request.UserId, request.DisplayName);
                var decryptedvalue = await _service.Decrypt(request.ResourceId, resource.EncryptedResource);

                await _repository.UpdateAsync(collection);

                return(new EncryptedValue()
                {
                    Value = decryptedvalue
                });
            }
            return(new EncryptedValue()
            {
                Value = String.Empty
            });
        }
        public async Task <DownloadDocumentResponse> Handle(DownloadDocumentByIdQuery query, CancellationToken cancellationToken)
        {
            Document document = await _documentRepository.FindByIdWithFileAsync(query.Id);

            if (document == null)
            {
                throw new ApiProblemDetailsException($"Record with id: {query.Id} does not exist.", StatusCodes.Status404NotFound);
            }
            if (document.CreatedBy != _authenticatedUser.UserId)
            {
                throw new ApiProblemDetailsException($"You are not authorized to access this resource.", StatusCodes.Status403Forbidden);
            }

            // data
            DocumentFile documentFile = document.File;
            FileInfo     fileInfo     = new FileInfo(_settings.BuildFilePath(documentFile.Path));

            // check if document is still valid
            if (documentFile == null || !fileInfo.Exists)
            {
                throw new ApiProblemDetailsException($"Record with id: {query.Id} does contain file.", StatusCodes.Status404NotFound);
            }

            // decrypt
            string iv = documentFile.IV;

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

            // response
            return(new DownloadDocumentResponse
            {
                Id = query.Id,
                Name = documentFile.OriginalName,
                ContentType = documentFile.MimeType,
                FileContent = decrypted,
            });
        }
Ejemplo n.º 19
0
        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}");
        }
Ejemplo n.º 20
0
        public IActionResult ConsentLogsList(int userId, ConsentLogSearchModel searchModel)
        {
            if (userId == 0)
            {
                return(R.Fail.WithError(ErrorCodes.ParentEntityMustBeNonZero).Result);
            }

            //is the user valid?
            var user = userId > 0 ? _userService.Get(userId) : null;

            if (user == null)
            {
                return(NotFound());
            }
            var consentLogs = _consentLogService.Get(out int totalResults, x => x.UserId == userId, x => x.Id, RowOrder.Ascending,
                                                     searchModel.Current, searchModel.RowCount);
            var models = consentLogs.Select(_gdprModelFactory.Create).ToList();
            //We'll need to make sure that current admin can actually view the email
            var withUserInfo = false;

            if (CurrentUser.Can(CapabilitySystemNames.ManageGdprPrivate))
            {
                withUserInfo = true;
                foreach (var model in models)
                {
                    if (!model.UserInfo.IsNullEmptyOrWhiteSpace())
                    {
                        model.UserInfo = _cryptographyService.Decrypt(model.UserInfo);
                    }
                }
            }
            return(R.Success.With("consentLogs", models)
                   .With("withUserInfo", withUserInfo)
                   .WithGridResponse(totalResults, searchModel.Current, searchModel.RowCount)
                   .Result);
        }
Ejemplo n.º 21
0
        public Guid Sweep(SweepExecutionViewModel param)
        {
            Guid Id = Guid.NewGuid();

            _context.Sweeps.Add(new Sweep
            {
                Id            = Id,
                Status        = "Running",
                StartTime     = DateTime.UtcNow,
                ScanCount     = param.ComputerId.Length,
                CompleteCount = 0
            });
            _context.SaveChanges();

            List <Task> tasks = new List <Task>();

            /*
             * List<Scan> scans = new List<Scan>();
             *
             * foreach (Guid compId in param.ComputerId)
             * {
             *  // Create scan object
             *  Guid scanId = Guid.NewGuid();
             *  scans.Add(new Scan
             *  {
             *      Id = scanId,
             *      Status = "Running",
             *      StartTime = DateTime.UtcNow,
             *      ComputerId = compId,
             *      SweepIdentifier = Id
             *  });
             * }
             *
             * _context.Scans.AddRange(scans);
             */

            _context.SaveChanges();

            // Get Script object
            Script script = _context.Scripts.Single(s => s.Id == param.ScriptId);

            // Create Routing Key
            string RoutingKey = string.Format("{0}{1}", script.Enrichment, script.Output);

            // Get Thumbprint
            string thumbprint = null;

            string[] lines = System.IO.File.ReadAllLines(@"C:\inetpub\ACEWebService\appsettings.Production.json");
            foreach (string l in lines)
            {
                if (l.Contains("Thumbprint"))
                {
                    thumbprint = l.Split('"')[3];
                }
            }

            foreach (Guid compid in param.ComputerId)
            {
                Guid scanId = Guid.NewGuid();

                // Retreive Computer and Credential objects from DB
                Computer   computer   = _context.Computers.Single(c => c.Id == compid);
                Credential credential = _context.Credentials.Single(c => c.Id == computer.CredentialId);

                // Kick off scan
                if (computer.WinRM)
                {
                    Console.WriteLine("==== WINRM ====");

                    // Create a PowerShell script to run PSInvestigate
                    string executionArgs = string.Format(@"-Uri {0} -SweepId {1} -ScanId {2} -RoutingKey {3} -Thumbprint {4}", param.Uri, Id, scanId, RoutingKey, thumbprint);

                    Console.WriteLine(executionArgs);

                    string psScript = string.Format(@"iex (New-Object System.Net.WebClient).DownloadString('{0}{1}'); Start-AceScript {2}", param.Uri, script.Uri, executionArgs);

                    // Base64 Encode the PowerShell script
                    string psScriptEnc = Convert.ToBase64String(Encoding.Unicode.GetBytes(psScript));

                    // Build full powershell command line to be run
                    string commandline = string.Format(@"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -EncodedCommand {0}", psScriptEnc);

                    Console.WriteLine(commandline);

                    tasks.Add(Task.Run(() => { KickOffCimAsync(computer, credential, commandline, new WSManSessionOptions()); }));
                }
                else if (computer.RPC)
                {
                    Console.WriteLine("==== RPC ====");

                    // Create a PowerShell script to run PSInvestigate
                    string executionArgs = string.Format(@"-Uri {0} -SweepId {1} -ScanId {2} -RoutingKey {3} -Thumbprint {4}", param.Uri, Id, scanId, RoutingKey, thumbprint);
                    string psScript      = string.Format(@"iex (New-Object System.Net.WebClient).DownloadString('{0}{1}'); Start-AceScript {2}", param.Uri, script.Uri, executionArgs);

                    // Base64 Encode the PowerShell script
                    string psScriptEnc = Convert.ToBase64String(Encoding.Unicode.GetBytes(psScript));

                    // Build full powershell command line to be run
                    string commandline = string.Format(@"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle Hidden -EncodedCommand {0}", psScriptEnc);

                    Console.WriteLine(commandline);

                    tasks.Add(Task.Run(() => { KickOffCimAsync(computer, credential, commandline, new DComSessionOptions()); }));
                }
                else if (computer.SSH)
                {
                    Console.WriteLine("==== SSH ====");

                    // Build command line to be run over SSH
                    string commandline = string.Format(@"curl -k {0}{1} | sudo python /dev/stdin --Server {0} --SweepId {2} --ScanId {3} --RoutingKey {4}", param.Uri, script.Uri, Id, scanId, RoutingKey);
                    //tasks.Add(Task.Run(() => { KickOffSSHAsync(computer, credential, commandline); }));
                    using (var client = new SshClient(computer.ComputerName, credential.UserName, _cryptoService.Decrypt(credential.Password)))
                    {
                        client.Connect();
                        client.RunCommand(commandline);
                        client.Disconnect();
                    }
                }
                else if (computer.SMB)
                {
                    throw new NotImplementedException();
                }
                else
                {
                    throw new Exception(string.Format("No valid protocols available for {0}", computer.ComputerName));
                }
            }

            Task.WaitAll(tasks.ToArray());

            IQueryable <Scan> scansCompleted = _context.Set <Scan>().Where(s => s.SweepIdentifier == Id && s.Status != "Running");
            IQueryable <Scan> scansFailed    = _context.Set <Scan>().Where(s => s.SweepIdentifier == Id && s.Status == "Failed");
            Sweep             sweep          = _context.Sweeps.Single(s => s.Id == Id);

            sweep.CompleteCount = scansCompleted.ToArray().Length;
            sweep.ErrorCount    = scansFailed.ToArray().Length;
            sweep.Status        = "Completed";
            _context.Sweeps.Update(sweep);
            _context.SaveChanges();

            return(Id);
        }
Ejemplo n.º 22
0
 public string Decrypt(string text)
 {
     return(_cryptographyService.Decrypt(text, configuration["Authentication:SecretKey"]));
 }
Ejemplo n.º 23
0
        private bool GetMailObjects(EmailMessage emailMessage, out MailMessage mailMessage, out SmtpClient smtpClient)
        {
            mailMessage = null;
            smtpClient  = null;
            //we need an email account
            var emailAccount = emailMessage.EmailAccount ??
                               _emailAccountService.Get(_emailSenderSettings.DefaultEmailAccountId) ??
                               _emailAccountService.FirstOrDefault(x => true);

            if (emailAccount == null)
            {
                _logger.Log <EmailService>(LogLevel.Error, $"Failed to send email. No default email account could be loaded.");
                return(false); //can't send email without account
            }

            var message = new MailMessage();

            //from, to, reply to
            message.From = new MailAddress(emailAccount.Email, emailAccount.FromName);

            if (emailMessage.Tos == null && emailMessage.Ccs == null && emailMessage.Bccs == null)
            {
                throw new EvenCartException("At least one of Tos, CCs or BCCs must be specified to send email");
            }

            if (emailMessage.Tos != null)
            {
                foreach (var userInfo in emailMessage.Tos)
                {
                    message.To.Add(new MailAddress(userInfo.Email, userInfo.Name));
                }
            }

            if (emailMessage.ReplyTos != null)
            {
                foreach (var userInfo in emailMessage.ReplyTos)
                {
                    message.ReplyToList.Add(new MailAddress(userInfo.Email, userInfo.Name));
                }
            }

            if (emailMessage.Bccs != null)
            {
                foreach (var userInfo in emailMessage.Bccs)
                {
                    message.Bcc.Add(new MailAddress(userInfo.Email, userInfo.Name));
                }
            }

            if (emailMessage.Ccs != null)
            {
                foreach (var userInfo in emailMessage.Ccs)
                {
                    message.Bcc.Add(new MailAddress(userInfo.Email, userInfo.Name));
                }
            }

            //content
            message.Subject    = emailMessage.Subject;
            message.Body       = emailMessage.EmailBody;
            message.IsBodyHtml = emailMessage.IsEmailBodyHtml;

            //headers
            if (emailMessage.Headers != null)
            {
                foreach (var header in emailMessage.Headers)
                {
                    message.Headers.Add(header.Key, header.Value);
                }
            }

            if (emailMessage.Attachments != null)
            {
                foreach (var attachment in emailMessage.Attachments)
                {
                    message.Attachments.Add(attachment);
                }
            }

            //send email

            var password = _cryptographyService.Decrypt(emailAccount.Password);

            smtpClient = new SmtpClient
            {
                UseDefaultCredentials = emailAccount.UseDefaultCredentials,
                Host        = emailAccount.Host,
                Port        = emailAccount.Port,
                EnableSsl   = emailAccount.UseSsl,
                Credentials = emailAccount.UseDefaultCredentials
                    ? CredentialCache.DefaultNetworkCredentials
                    : new NetworkCredential(emailAccount.UserName, password)
            };
            mailMessage = message;
            return(true);
        }
Ejemplo n.º 24
0
        public IActionResult ConfirmSave()
        {
            if (!CanCheckout(out Cart cart))
            {
                return(R.Fail.With("error", T("An error occurred while checking out")).Result);
            }
            var shippingRequired = CartHelper.IsShippingRequired(cart);

            if (cart.BillingAddressId == 0 || cart.ShippingAddressId == 0 && shippingRequired)
            {
                return(R.Fail.With("error", T("The address details were not provided")).Result);
            }

            if (cart.ShippingMethodName.IsNullEmptyOrWhiteSpace() && shippingRequired)
            {
                return(R.Fail.With("error", T("The shipping details were not provided.")).Result);
            }

            if (CartHelper.IsPaymentRequired(cart) && cart.PaymentMethodName.IsNullEmptyOrWhiteSpace() && !cart.UseStoreCredits)
            {
                return(R.Fail.With("error", T("The payment method was not provided")).Result);
            }

            if (shippingRequired)
            {
                //validate shipping method
                var shippingHandler = PluginHelper.GetShipmentHandler(cart.ShippingMethodName);
                if (shippingHandler == null || !shippingHandler.IsMethodAvailable(cart))
                {
                    return(R.Fail.With("error", T("Shipping method unavailable")).Result);
                }
            }


            var currentUser = ApplicationEngine.CurrentUser;
            var order       = new Order()
            {
                PaymentMethodName         = cart.PaymentMethodName,
                PaymentMethodDisplayName  = cart.PaymentMethodDisplayName,
                ShippingMethodName        = cart.ShippingMethodName,
                ShippingMethodDisplayName = cart.ShippingMethodDisplayName,
                SelectedShippingOption    = cart.SelectedShippingOption,
                CreatedOn         = DateTime.UtcNow,
                DiscountId        = cart.DiscountCouponId,
                Guid              = Guid.NewGuid().ToString(),
                UserId            = cart.UserId,
                PaymentStatus     = PaymentStatus.Pending,
                OrderStatus       = OrderStatus.New,
                DiscountCoupon    = cart.DiscountCoupon?.CouponCode,
                Discount          = cart.Discount + cart.CartItems.Sum(x => x.Discount),
                PaymentMethodFee  = cart.PaymentMethodFee,
                ShippingMethodFee = cart.ShippingFee,
                Tax            = cart.CartItems.Sum(x => x.Tax),
                UserIpAddress  = WebHelper.GetClientIpAddress(),
                CurrencyCode   = ApplicationEngine.BaseCurrency.IsoCode,
                Subtotal       = cart.FinalAmount - cart.CartItems.Sum(x => x.Tax),
                ExchangeRate   = ApplicationEngine.BaseCurrency.ExchangeRate,
                DisableReturns = cart.CartItems.All(x => !x.Product.AllowReturns),
                User           = currentUser,
                IsSubscription = CartHelper.IsSubscriptionCart(cart),
                StoreId        = CurrentStore.Id
            };

            order.OrderTotal = order.Subtotal + order.Tax + (order.PaymentMethodFee ?? 0) + (order.ShippingMethodFee ?? 0) - order.Discount;
            //load the addresses
            var addressIds = new List <int>()
            {
                cart.BillingAddressId, cart.ShippingAddressId
            };
            var addresses       = _addressService.Get(x => addressIds.Contains(x.Id)).ToList();
            var billingAddress  = addresses.First(x => x.Id == cart.BillingAddressId);
            var shippingAddress = addresses.FirstOrDefault(x => x.Id == cart.ShippingAddressId);

            order.BillingAddressSerialized  = _dataSerializer.Serialize(billingAddress);
            order.ShippingAddressSerialized =
                shippingAddress == null ? null : _dataSerializer.Serialize(shippingAddress);

            //get all the products
            var distinctProductIds = cart.CartItems.Select(x => x.ProductId).ToList();
            var products           = _productService.Get(x => distinctProductIds.Contains(x.Id)).ToList();

            order.OrderItems = new List <OrderItem>();
            foreach (var cartItem in cart.CartItems)
            {
                var orderItem = new OrderItem()
                {
                    AttributeJson    = cartItem.AttributeJson,
                    OrderId          = order.Id,
                    Price            = cartItem.Price,
                    ProductId        = cartItem.ProductId,
                    Quantity         = cartItem.Quantity,
                    Tax              = cartItem.Tax,
                    TaxPercent       = cartItem.TaxPercent,
                    TaxName          = cartItem.TaxName,
                    ProductVariantId = cartItem.ProductVariantId,
                    IsDownloadable   = cartItem.IsDownloadable,
                    Product          = products.First(x => x.Id == cartItem.ProductId),
                };
                orderItem.SubscriptionCycle = orderItem.Product.SubscriptionCycle;
                orderItem.CycleCount        = orderItem.Product.CycleCount;
                orderItem.TrialDays         = orderItem.Product.TrialDays;
                order.OrderItems.Add(orderItem);
            }
            var creditAmount = 0m;

            if (cart.UseStoreCredits)
            {
                GetAvailableStoreCredits(out var credits, out creditAmount, ApplicationEngine.BaseCurrency, cart);
                if (credits > 0 && _affiliateSettings.MinimumStoreCreditsToAllowPurchases <= credits)
                {
                    order.UsedStoreCredits  = true;
                    order.StoreCredits      = credits;
                    order.StoreCreditAmount = creditAmount;
                }
            }

            //insert complete order
            _orderAccountant.InsertCompleteOrder(order);

            //process payment
            var paymentMethodData = cart.PaymentMethodData.IsNullEmptyOrWhiteSpace()
                ? null
                : _dataSerializer.DeserializeAs <Dictionary <string, object> >(
                _cryptographyService.Decrypt(cart.PaymentMethodData));

            CustomResponse response = null;

            if (cart.PaymentMethodName != ApplicationConfig.UnavailableMethodName && !ProcessPayment(order, creditAmount, paymentMethodData, out response))
            {
                return(response.With("orderGuid", order.Guid).Result);
            }

            //clear the user's cart
            _cartService.ClearCart(currentUser.Id);

            if (currentUser.IsVisitor())
            {
                //if current user is visitor, change the email to billing address and change it to registered user
                currentUser.Email = billingAddress.Email;
                _userService.Update(currentUser);

                var roleId = _roleService.Get(x => x.SystemName == SystemRoleNames.Registered).First().Id;
                //assign registered role to the user
                _roleService.SetUserRoles(currentUser.Id, new[] { roleId });

                ApplicationEngine.SignIn(currentUser.Email, null, false);
            }

            response = response ?? R.Success;
            return(response.With("orderGuid", order.Guid).Result);
        }
Ejemplo n.º 25
0
        public bool SendEmail(EmailMessage emailMessage, bool verboseErrorOnFailure = false)
        {
            //we need an email account
            var emailAccount = emailMessage.EmailAccount ?? _emailAccountService.FirstOrDefault(x => x.IsDefault);

            if (emailAccount == null)
            {
                return(false); //can't send email without account
            }
            var message = new MailMessage();

            //from, to, reply to
            message.From = new MailAddress(emailAccount.Email, emailAccount.FromName);

            if (emailMessage.Tos == null && emailMessage.Ccs == null && emailMessage.Bccs == null)
            {
                throw new mobSocialException("At least one of Tos, CCs or BCCs must be specified to send email");
            }

            if (emailMessage.Tos != null)
            {
                foreach (var userInfo in emailMessage.Tos)
                {
                    message.To.Add(new MailAddress(userInfo.Email, userInfo.Name));
                }
            }

            if (emailMessage.ReplyTos != null)
            {
                foreach (var userInfo in emailMessage.ReplyTos)
                {
                    message.ReplyToList.Add(new MailAddress(userInfo.Email, userInfo.Name));
                }
            }

            if (emailMessage.Bccs != null)
            {
                foreach (var userInfo in emailMessage.Bccs)
                {
                    message.Bcc.Add(new MailAddress(userInfo.Email, userInfo.Name));
                }
            }

            if (emailMessage.Ccs != null)
            {
                foreach (var userInfo in emailMessage.Ccs)
                {
                    message.Bcc.Add(new MailAddress(userInfo.Email, userInfo.Name));
                }
            }

            //content
            message.Subject    = emailMessage.Subject;
            message.Body       = emailMessage.EmailBody;
            message.IsBodyHtml = emailMessage.IsEmailBodyHtml;

            //headers
            if (emailMessage.Headers != null)
            {
                foreach (var header in emailMessage.Headers)
                {
                    message.Headers.Add(header.Key, header.Value);
                }
            }

            if (emailMessage.Attachments != null)
            {
                foreach (var attachment in emailMessage.Attachments)
                {
                    message.Attachments.Add(attachment);
                }
            }

            //send email

            var password = _cryptographyService.Decrypt(emailAccount.Password);

            using (var smtpClient = new SmtpClient())
            {
                smtpClient.UseDefaultCredentials = emailAccount.UseDefaultCredentials;
                smtpClient.Host        = emailAccount.Host;
                smtpClient.Port        = emailAccount.Port;
                smtpClient.EnableSsl   = emailAccount.UseSsl;
                smtpClient.Credentials = emailAccount.UseDefaultCredentials ?
                                         CredentialCache.DefaultNetworkCredentials :
                                         new NetworkCredential(emailAccount.UserName, password);
                try
                {
                    smtpClient.Send(message);
                    //update the send status
                    emailMessage.IsSent = true;
                    Update(emailMessage);
                    return(true);
                }
                catch (Exception ex)
                {
                    if (verboseErrorOnFailure)
                    {
                        var verboseReporterService = mobSocialEngine.ActiveEngine.Resolve <IVerboseReporterService>();
                        verboseReporterService.ReportError(ex.Message, "send_email");
                    }
                    return(false);
                }
            }
        }
Ejemplo n.º 26
0
        private SearchResultCollection GetDomainComputers(string domain, Credential credential)
        {
            List <SearchResult> results = new List <SearchResult>();

            Console.WriteLine("=========================");
            Console.WriteLine("Pre Directory Search: {0}", domain);
            Console.WriteLine("=========================");

            //using (DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", domain), credential.UserName, Cryptography.Decrypt(credential.Password, _configuration["EncryptionPassphrase"].ToString())))
            using (DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", domain), credential.UserName, _cryptoService.Decrypt(credential.Password)))
            {
                Console.WriteLine("=========================");
                Console.WriteLine("Post Directory Search: {0}", domain);
                Console.WriteLine("=========================");

                using (DirectorySearcher mySearcher = new DirectorySearcher(entry))
                {
                    mySearcher.Filter = ("(objectCategory=computer)");

                    // No size limit, reads all objects
                    mySearcher.SizeLimit = 0;

                    // Read data in pages of 250 objects. Make sure this value is below the limit configured in your AD domain (if there is a limit)
                    mySearcher.PageSize = 0;

                    // Let searcher know which properties are going to be used, and only load those
                    mySearcher.PropertiesToLoad.Add("dnshostname");
                    //mySearcher.PropertiesToLoad.Add("operatingsystem");

                    return(mySearcher.FindAll());
                }
            }
        }