Esempio n. 1
0
        public void TestInvalidArguments()
        {
            string     file          = _helloWorldAxxPath;
            IDataStore dataStore     = New <IDataStore>(file);
            IDataStore nullDataStore = null;

            IEnumerable <LogOnIdentity> keys     = new LogOnIdentity[] { new LogOnIdentity("a") };
            IEnumerable <LogOnIdentity> nullKeys = null;

            ProgressContext context     = new ProgressContext();
            ProgressContext nullContext = null;

            FileOperation fileOperation = new FileOperation(Resolve.FileSystemState, new SessionNotify());

            Assert.ThrowsAsync <ArgumentNullException>(async() => { await fileOperation.OpenAndLaunchApplication(keys, nullDataStore, context); }, "The data store is null.");
            Assert.ThrowsAsync <ArgumentNullException>(async() => { await fileOperation.OpenAndLaunchApplication(nullKeys, dataStore, context); }, "The keys are null.");
            Assert.ThrowsAsync <ArgumentNullException>(async() => { await fileOperation.OpenAndLaunchApplication(keys, dataStore, nullContext); }, "The context is null.");
        }
Esempio n. 2
0
        public void TestInvalidArguments()
        {
            IDataStore    nullFileInfo      = null;
            IDataStore    decryptedFileInfo = New <IDataStore>(_testTextPath);
            IDataStore    encryptedFileInfo = New <IDataStore>(_helloWorldAxxPath);
            LogOnIdentity key            = new LogOnIdentity("key");
            LogOnIdentity nullKey        = null;
            ActiveFile    nullActiveFile = null;

            ActiveFile originalActiveFile = new ActiveFile(encryptedFileInfo, decryptedFileInfo, key, ActiveFileStatus.None, new V1Aes128CryptoFactory().CryptoId);

            Assert.Throws <ArgumentNullException>(() => { if (new ActiveFile(nullActiveFile) == null)
                                                          {
                                                          }
                                                  });
            Assert.Throws <ArgumentNullException>(() => { if (new ActiveFile(nullActiveFile, key) == null)
                                                          {
                                                          }
                                                  });
            Assert.Throws <ArgumentNullException>(() => { if (new ActiveFile(originalActiveFile, nullKey) == null)
                                                          {
                                                          }
                                                  });
            Assert.Throws <ArgumentNullException>(() => { if (new ActiveFile(nullActiveFile, ActiveFileStatus.None) == null)
                                                          {
                                                          }
                                                  });
            Assert.Throws <ArgumentNullException>(() => { if (new ActiveFile(nullActiveFile, DateTime.MinValue, ActiveFileStatus.None) == null)
                                                          {
                                                          }
                                                  });
            Assert.Throws <ArgumentNullException>((TestDelegate)(() => { if (new ActiveFile(nullFileInfo, decryptedFileInfo, new LogOnIdentity("a"), ActiveFileStatus.None, (Guid) new V1Aes128CryptoFactory().CryptoId) == null)
                                                                         {
                                                                         }
                                                                 }));
            Assert.Throws <ArgumentNullException>((TestDelegate)(() => { if (new ActiveFile(encryptedFileInfo, nullFileInfo, new LogOnIdentity("b"), ActiveFileStatus.None, (Guid) new V1Aes128CryptoFactory().CryptoId) == null)
                                                                         {
                                                                         }
                                                                 }));
            Assert.Throws <ArgumentNullException>((TestDelegate)(() => { if (new ActiveFile(encryptedFileInfo, decryptedFileInfo, nullKey, ActiveFileStatus.None, (Guid) new V1Aes128CryptoFactory().CryptoId) == null)
                                                                         {
                                                                         }
                                                                 }));
        }
Esempio n. 3
0
        public async Task TestCheckActiveFilesUpdateButWithTargetLockedForSharing()
        {
            DateTime utcNow = New <INow>().Utc;

            FakeDataStore.AddFile(_anAxxPath, utcNow, utcNow, utcNow, FakeDataStore.ExpandableMemoryStream(Resources.helloworld_key_a_txt));
            LogOnIdentity passphrase = new LogOnIdentity("a");

            New <AxCryptFile>().Decrypt(New <IDataStore>(_anAxxPath), New <IDataStore>(_decryptedFile1), passphrase, AxCryptOptions.None, new ProgressContext());

            ActiveFile activeFile = new ActiveFile(New <IDataStore>(_anAxxPath), New <IDataStore>(_decryptedFile1), passphrase, ActiveFileStatus.AssumedOpenAndDecrypted, new V1Aes128CryptoFactory().CryptoId);

            Resolve.FileSystemState.Add(activeFile);

            IDataStore decryptedFileInfo = New <IDataStore>(_decryptedFile1);

            decryptedFileInfo.SetFileTimes(utcNow.AddSeconds(30), utcNow.AddSeconds(30), utcNow.AddSeconds(30));

            ((FakeNow)New <INow>()).TimeFunction = (() => { return(utcNow.AddMinutes(1)); });

            await Resolve.KnownIdentities.AddAsync(passphrase);

            bool changedWasRaised = false;

            Resolve.SessionNotify.AddCommand((SessionNotification notification) =>
            {
                changedWasRaised = notification.NotificationType == SessionNotificationType.ActiveFileChange;
                return(Constant.CompletedTask);
            });

            try
            {
                FakeDataStore.IsLockedFunc = (fds) => fds.FullName == _decryptedFile1;

                await New <ActiveFileAction>().CheckActiveFiles(new ProgressContext());
            }
            finally
            {
                FakeDataStore.IsLockedFunc = (fds) => false;
            }

            Assert.That(changedWasRaised, Is.True, "The ActiveFile should be modified because it should now be marked as not shareable.");
            activeFile = Resolve.FileSystemState.FindActiveFileFromEncryptedPath(_anAxxPath);
            Assert.That(activeFile.Status.HasMask(ActiveFileStatus.NotShareable), Is.True, "The ActiveFile should be marked as not shareable after the checking of active files.");
        }
        public async Task AskForLogOnPassphraseActionWithCancel()
        {
            LogOnIdentity key = new LogOnIdentity("ppp");

            LogOnIdentity id = key;

            IdentityViewModel ivm = new IdentityViewModel(Resolve.FileSystemState, Resolve.KnownIdentities, Resolve.UserSettings, Resolve.SessionNotify);

            ivm.LoggingOnAsync = (e) =>
            {
                e.Cancel = true;
                return(Task.FromResult <object>(null));
            };

            await ivm.AskForLogOnPassphrase.ExecuteAsync(id);

            Assert.That(ivm.LogOnIdentity == LogOnIdentity.Empty);
            Assert.That(Resolve.KnownIdentities.DefaultEncryptionIdentity == LogOnIdentity.Empty);
        }
Esempio n. 5
0
        public async Task TestClear()
        {
            KnownIdentities knownIdentities = new KnownIdentities(Resolve.FileSystemState, Resolve.SessionNotify);
            LogOnIdentity   key1            = new LogOnIdentity("key1");
            await knownIdentities.AddAsync(key1);

            LogOnIdentity key2 = new LogOnIdentity("key2");
            await knownIdentities.AddAsync(key2);

            Assert.That(knownIdentities.Identities.Count(), Is.EqualTo(2), "There should be two keys in the collection.");

            await knownIdentities.SetDefaultEncryptionIdentity(LogOnIdentity.Empty);

            Assert.That(knownIdentities.Identities.Count(), Is.EqualTo(0), "There should be zero keys in the collection after Clear().");

            await knownIdentities.SetDefaultEncryptionIdentity(LogOnIdentity.Empty);

            Assert.That(knownIdentities.Identities.Count(), Is.EqualTo(0), "There should be zero keys in the collection after Clear() with zero keys to start with.");
        }
Esempio n. 6
0
        public async Task TestWatchedFoldersWhenLoggedOn()
        {
            Passphrase      key1            = new Passphrase("a");
            LogOnIdentity   key2            = new LogOnIdentity("b");
            KnownIdentities knownIdentities = new KnownIdentities(Resolve.FileSystemState, Resolve.SessionNotify);

            FakeDataStore.AddFolder(@"C:\WatchedFolder1\");
            FakeDataStore.AddFolder(@"C:\WatchedFolder2\");
            await Resolve.FileSystemState.AddWatchedFolderAsync(new WatchedFolder(@"C:\WatchedFolder1\", new LogOnIdentity(key1).Tag));

            await Resolve.FileSystemState.AddWatchedFolderAsync(new WatchedFolder(@"C:\WatchedFolder2\", key2.Tag));

            await knownIdentities.SetDefaultEncryptionIdentity(key2);

            IEnumerable <WatchedFolder> watchedFolders = knownIdentities.LoggedOnWatchedFolders;

            Assert.That(watchedFolders.Count(), Is.EqualTo(1), "Only one of the two watched folders should be shown.");
            Assert.That(watchedFolders.First().Tag.Matches(key2.Tag), "The returned watched folder should be number 2.");
        }
        public async Task ChangeEncryptionAsync(IEnumerable <IDataStore> files, LogOnIdentity identity, EncryptionParameters encryptionParameters, IProgressContext progress)
        {
            if (progress == null)
            {
                throw new ArgumentNullException(nameof(progress));
            }
            if (files == null)
            {
                throw new ArgumentNullException(nameof(files));
            }

            progress.AddTotal(files.Count());
            foreach (IDataStore file in files)
            {
                await ChangeEncryptionAsync(file, identity, encryptionParameters, progress);

                progress.AddCount(1);
            }
        }
        public async Task TestAddAndRemoveWatchedFolderState()
        {
            var fileSystemStateMock = new Mock <FileSystemState>()
            {
                CallBase = true
            };

            fileSystemStateMock.Setup(x => x.Save()).Returns(Constant.CompletedTask);

            TypeMap.Register.Singleton <FileSystemState>(() => fileSystemStateMock.Object);
            using (MainViewModel mvm = New <MainViewModel>())
            {
                Assert.ThrowsAsync <InvalidOperationException>(async() => await mvm.DecryptWatchedFolders.ExecuteAsync(new string[] { }));

                LogOnIdentity id = new LogOnIdentity("passphrase");
                fileSystemStateMock.Object.KnownPassphrases.Add(id.Passphrase);
                await Resolve.KnownIdentities.SetDefaultEncryptionIdentity(id);

                fileSystemStateMock.ResetCalls();

                await mvm.DecryptWatchedFolders.ExecuteAsync(new string[] { });

                fileSystemStateMock.Verify(x => x.RemoveAndDecryptWatchedFolder(It.IsAny <IDataContainer>()), Times.Never);
                fileSystemStateMock.Verify(x => x.Save(), Times.Never);

                fileSystemStateMock.ResetCalls();
                await mvm.AddWatchedFolders.ExecuteAsync(new string[] { });

                fileSystemStateMock.Verify(x => x.AddWatchedFolderAsync(It.IsAny <WatchedFolder>()), Times.Never);
                fileSystemStateMock.Verify(x => x.Save(), Times.Never);

                await mvm.AddWatchedFolders.ExecuteAsync(new string[] { @"C:\Folder1\", @"C:\Folder2\" });

                fileSystemStateMock.Verify(x => x.AddWatchedFolderAsync(It.IsAny <WatchedFolder>()), Times.Exactly(2));
                fileSystemStateMock.Verify(x => x.Save(), Times.Once);

                fileSystemStateMock.ResetCalls();
                await mvm.DecryptWatchedFolders.ExecuteAsync(new string[] { @"C:\Folder1\" });
            }

            fileSystemStateMock.Verify(x => x.RemoveAndDecryptWatchedFolder(It.IsAny <IDataContainer>()), Times.Exactly(1));
            fileSystemStateMock.Verify(x => x.Save(), Times.Once);
        }
        public async Task TestSetDefaultEncryptionKeyWithoutIdentity()
        {
            var fileSystemStateMock = new Mock <FileSystemState>()
            {
                CallBase = true
            };

            fileSystemStateMock.Setup(x => x.Save());

            TypeMap.Register.Singleton <FileSystemState>(() => fileSystemStateMock.Object);
            using (MainViewModel mvm = New <MainViewModel>())
            {
                LogOnIdentity identity = new LogOnIdentity("passphrase");
                Assert.That(!Resolve.FileSystemState.KnownPassphrases.Any(kp => kp.Thumbprint == identity.Passphrase.Thumbprint));
                await Resolve.KnownIdentities.SetDefaultEncryptionIdentity(new LogOnIdentity("passphrase"));

                Assert.That(Resolve.FileSystemState.KnownPassphrases.Any(kp => kp.Thumbprint == identity.Passphrase.Thumbprint));
            }
        }
Esempio n. 10
0
        private async Task <LogOnIdentity> AskForDecryptPassphraseActionAsync(string encryptedFileFullName)
        {
            LogOnEventArgs logOnArgs = new LogOnEventArgs()
            {
                DisplayPassphrase     = _userSettings.DisplayEncryptPassphrase,
                Identity              = LogOnIdentity.Empty,
                EncryptedFileFullName = encryptedFileFullName,
            };

            await OnLoggingOnAsync(logOnArgs);

            LogOnIdentity identy = await AddKnownIdentityFromEventAsync(logOnArgs);

            if (!_knownIdentities.IsLoggedOn && identy.UserEmail != EmailAddress.Empty)
            {
                await _knownIdentities.SetDefaultEncryptionIdentity(identy);
            }
            return(identy);
        }
        public async Task AskForLogOnPassphraseAction()
        {
            LogOnIdentity key = new LogOnIdentity("ppp");

            LogOnIdentity id = key;

            IdentityViewModel ivm = new IdentityViewModel(Resolve.FileSystemState, Resolve.KnownIdentities, Resolve.UserSettings, Resolve.SessionNotify);

            ivm.LoggingOnAsync = (e) =>
            {
                e.Passphrase = new Passphrase("ppp");
                e.IsAskingForPreviouslyUnknownPassphrase = true;
                return(Task.FromResult <object>(null));
            };

            await ivm.AskForLogOnPassphrase.ExecuteAsync(id);

            Assert.That(ivm.LogOnIdentity.Passphrase.Text, Is.EqualTo("ppp"));
            Assert.That(Resolve.KnownIdentities.DefaultEncryptionIdentity.Passphrase.Thumbprint, Is.EqualTo(id.Passphrase.Thumbprint));
        }
Esempio n. 12
0
        public static EncryptedProperties Create(IDataStore encrypted, LogOnIdentity identity)
        {
            if (encrypted == null)
            {
                throw new ArgumentNullException("encrypted");
            }

            try
            {
                using (Stream stream = encrypted.OpenRead())
                {
                    return(Create(stream, identity));
                }
            }
            catch (FileNotFoundException fnfex)
            {
                New <IReport>().Exception(fnfex);
                return(Invalid);
            }
        }
Esempio n. 13
0
        public async Task TestDecryptFilesUniqueWithWipeOfOriginal()
        {
            TypeMap.Register.Singleton <ParallelFileOperation>(() => new ParallelFileOperation());
            TypeMap.Register.Singleton <IProgressBackground>(() => new FakeProgressBackground());
            IDataStore     sourceFileInfo   = New <IDataStore>(_helloWorldAxxPath);
            IDataContainer sourceFolderInfo = New <IDataContainer>(Path.GetDirectoryName(sourceFileInfo.FullName));

            IDataStore    destinationFileInfo = New <IDataStore>(Path.Combine(Path.GetDirectoryName(_helloWorldAxxPath), "HelloWorld-Key-a.txt"));
            LogOnIdentity passphrase          = new LogOnIdentity("a");

            Mock <IStatusChecker> mockStatusChecker = new Mock <IStatusChecker>();

            Assert.That(sourceFileInfo.IsAvailable, Is.True, "The source should exist.");
            Assert.That(destinationFileInfo.IsAvailable, Is.False, "The source should not exist yet.");

            await New <AxCryptFile>().DecryptFilesInsideFolderUniqueWithWipeOfOriginalAsync(sourceFolderInfo, passphrase, mockStatusChecker.Object, new ProgressContext());

            Assert.That(sourceFileInfo.IsAvailable, Is.False, "The source should be wiped.");
            Assert.That(destinationFileInfo.IsAvailable, Is.True, "The destination should be created and exist now.");
        }
Esempio n. 14
0
        public async Task TestChangedEvent()
        {
            bool            wasChanged          = false;
            SessionNotify   notificationMonitor = new SessionNotify();
            KnownIdentities knownIdentities     = new KnownIdentities(Resolve.FileSystemState, notificationMonitor);

            notificationMonitor.AddCommand((SessionNotification notification) =>
            {
                wasChanged |= notification.NotificationType == SessionNotificationType.KnownKeyChange;
                return(Constant.CompletedTask);
            });
            LogOnIdentity key1 = new LogOnIdentity("abc");
            await knownIdentities.AddAsync(key1);

            Assert.That(wasChanged, Is.True, "A new key should trigger the Changed event.");
            wasChanged = false;
            await knownIdentities.AddAsync(key1);

            Assert.That(wasChanged, Is.False, "Re-adding an existing key should not trigger the Changed event.");
        }
Esempio n. 15
0
        public async Task TestRemoveRecentFileWhenFileDoesNotExist()
        {
            IDataStore    encryptedFileInfo = New <IDataStore>(_anAxxPath);
            IDataStore    decryptedFileInfo = New <IDataStore>(_decryptedFile1);
            LogOnIdentity key        = new LogOnIdentity("passphrase");
            ActiveFile    activeFile = new ActiveFile(encryptedFileInfo, decryptedFileInfo, key, ActiveFileStatus.AssumedOpenAndDecrypted | ActiveFileStatus.NotShareable, new V2Aes256CryptoFactory().CryptoId);

            Resolve.FileSystemState.Add(activeFile);
            await Resolve.FileSystemState.Save();

            ActiveFile beforeRemoval = Resolve.FileSystemState.FindActiveFileFromEncryptedPath(encryptedFileInfo.FullName);

            Assert.That(beforeRemoval, Is.Not.Null, "Before being removed, the ActiveFile should be possible to find.");

            Assert.DoesNotThrowAsync(async() => { await New <ActiveFileAction>().RemoveRecentFiles(new IDataStore[] { New <IDataStore>(encryptedFileInfo.FullName + ".notfound") }, new ProgressContext()); });

            ActiveFile afterFailedRemoval = Resolve.FileSystemState.FindActiveFileFromEncryptedPath(encryptedFileInfo.FullName);

            Assert.That(afterFailedRemoval, Is.Not.Null, "After failed removal, the ActiveFile should still be possible to find.");
        }
Esempio n. 16
0
        public async Task TestSimpleOpenAndLaunch()
        {
            IDataStore dataStore = New <IDataStore>(_helloWorldAxxPath);

            IEnumerable <LogOnIdentity> keys = new LogOnIdentity[] { new LogOnIdentity("a") };

            var mock = new Mock <ILauncher>()
            {
                CallBase = true
            };
            string launcherPath = null;

            mock.Setup(x => x.Launch(It.IsAny <string>())).Callback((string path) => launcherPath = path);
            TypeMap.Register.New <ILauncher>(() => mock.Object);

            FileOperation        fileOperation = new FileOperation(Resolve.FileSystemState, new SessionNotify());
            FileOperationContext status        = await fileOperation.OpenAndLaunchApplication(keys, dataStore, new ProgressContext());

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.Success), "The launch should succeed.");
            Assert.DoesNotThrow(() => mock.Verify(x => x.Launch(launcherPath)));
        }
Esempio n. 17
0
        private bool AddInternal(LogOnIdentity identity)
        {
            if (identity == LogOnIdentity.Empty)
            {
                return(false);
            }

            bool changed = false;

            lock (_logOnIdentities)
            {
                int i = _logOnIdentities.IndexOf(identity);
                if (i < 0)
                {
                    _logOnIdentities.Insert(0, identity);
                    changed = true;
                }
            }
            changed |= AddKnownThumbprint(identity);
            return(changed);
        }
Esempio n. 18
0
        private void DoAuthentication()
        {
            ITicket ticket;

            string logonName = InternalGetLogOnName(out ticket);

            if (logonName.IsNotEmpty())
            {
                logonName = ImpersonateSettings.GetConfig().Impersonation[logonName];

                LogOnIdentity loi = new LogOnIdentity(logonName);

                if (ticket != null)
                {
                    ticket.SignInInfo.UserID = loi.LogOnNameWithDomain;
                }

                SetTenantContext(ticket);
                SetPrincipal(loi.LogOnNameWithDomain, ticket);
            }
        }
Esempio n. 19
0
        public static bool IsAnyFileKeyKnown(this IEnumerable <IDataStore> files)
        {
            foreach (IDataStore fileInfo in files)
            {
                try
                {
                    Guid          cryptoId;
                    LogOnIdentity logOnIdentity = fileInfo.TryFindPassphrase(out cryptoId);
                    if (logOnIdentity != null)
                    {
                        return(true);
                    }
                }
                catch (FileOperationException)
                {
                    continue;
                }
            }

            return(false);
        }
Esempio n. 20
0
        private async Task ImportFileActionAsync()
        {
            IDataStore  privateKeyData = New <IDataStore>(PrivateKeyFileName);
            Passphrase  passphrase     = new Passphrase(PasswordText);
            UserKeyPair keyPair;

            if (!UserKeyPair.TryLoad(privateKeyData.ToArray(), passphrase, out keyPair))
            {
                ImportSuccessful = false;
                return;
            }

            LogOnIdentity  identity = new LogOnIdentity(keyPair.UserEmail, passphrase);
            AccountStorage store    = new AccountStorage(New <LogOnIdentity, IAccountService>(identity));
            await store.ImportAsync(keyPair);

            ImportSuccessful = true;

            _userSettings.UserEmail = keyPair.UserEmail.Address;
            await _knownIdentities.SetDefaultEncryptionIdentity(new LogOnIdentity(await store.AllKeyPairsAsync(), passphrase));
        }
        private bool AuthenticateAlternativeUserIDs(IEnumerable <string> alternativeUserIDs, string password, Dictionary <string, object> context)
        {
            bool result = false;

            if (alternativeUserIDs != null)
            {
                foreach (string userID in alternativeUserIDs)
                {
                    LogOnIdentity loi = new LogOnIdentity(userID, password);

                    result = AuthenticateUser(loi);

                    if (result)
                    {
                        break;
                    }
                }
            }

            return(result);
        }
        public async Task TestHandleSessionEventWatchedFolderAdded(CryptoImplementation cryptoImplementation)
        {
            SetupAssembly.AssemblySetupCrypto(cryptoImplementation);

            MockAxCryptFile mock   = new MockAxCryptFile();
            bool            called = false;

            mock.EncryptFilesUniqueWithBackupAndWipeMockAsync = async(IEnumerable <IDataContainer> folderInfos, EncryptionParameters encryptionParameters, IProgressContext progress) => { await Task.Delay(0); called = folderInfos.First().FullName == @"C:\My Documents\".NormalizeFilePath(); };

            Mock <IStatusChecker> mockStatusChecker = new Mock <IStatusChecker>();

            SessionNotificationHandler handler = new SessionNotificationHandler(Resolve.FileSystemState, Resolve.KnownIdentities, New <ActiveFileAction>(), mock, mockStatusChecker.Object);

            FakeDataStore.AddFolder(@"C:\My Documents");
            LogOnIdentity key = new LogOnIdentity("passphrase");
            await Resolve.FileSystemState.AddWatchedFolderAsync(new WatchedFolder(@"C:\My Documents", key.Tag));

            await handler.HandleNotificationAsync(new SessionNotification(SessionNotificationType.WatchedFolderAdded, new LogOnIdentity("passphrase"), @"C:\My Documents\"));

            Assert.That(called, Is.True);
        }
Esempio n. 23
0
        public static void RestoreRandomRename(this IDataStore dataStore, LogOnIdentity identity)
        {
            EncryptedProperties encryptedProperties = EncryptedProperties.Create(dataStore, identity);

            if (!encryptedProperties.IsValid)
            {
                return;
            }

            string destinationFilePath = Resolve.Portable.Path().Combine(Resolve.Portable.Path().GetDirectoryName(dataStore.FullName), encryptedProperties.FileMetaData.FileName.CreateEncryptedName());

            if (string.Equals(dataStore.FullName, destinationFilePath, StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            using (FileLock lockedSave = destinationFilePath.CreateUniqueFile())
            {
                dataStore.MoveTo(lockedSave.DataStore.FullName);
            }
        }
Esempio n. 24
0
        private static IPrincipal SetPrincipal(string userID, ITicket ticket)
        {
            IPrincipal principal = GetPrincipalInSession(userID);

            if (principal == null)
            {
                LogOnIdentity loi = new LogOnIdentity(userID);

                string identityID = string.Empty;

                if (PassportClientSettings.GetConfig().IdentityWithoutDomainName)
                {
                    identityID = loi.LogOnNameWithoutDomain;
                }
                else
                {
                    identityID = loi.LogOnName;
                }

                principal = PrincipalSettings.GetConfig().GetPrincipalBuilder().CreatePrincipal(identityID, ticket);

                HttpCookie cookie = new HttpCookie(Common.GetPrincipalSessionKey());
                cookie.Expires = DateTime.MinValue;

                CookieCacheDependency cookieDependency = new CookieCacheDependency(cookie);

                SlidingTimeDependency slidingDependency =
                    new SlidingTimeDependency(Common.GetSessionTimeOut());

                PrincipalCache.Instance.Add(
                    Common.GetPrincipalSessionKey(),
                    principal,
                    new MixedDependency(cookieDependency, slidingDependency));
            }

            PrincipaContextAccessor.SetPrincipal(principal);

            return(principal);
        }
        protected override async Task <PlanState> TryPremium(LogOnIdentity identity, PlanInformation planInformation, NameOf startTrialMessage)
        {
            if (planInformation.PlanState != PlanState.CanTryPremium)
            {
                return(planInformation.PlanState);
            }

            string messageText = Texts.MessageAskAboutStartTrial + Environment.NewLine + Environment.NewLine + Texts.ResourceManager.GetString(startTrialMessage.Name);
            string result      = await New <IPopup>().ShowAsync(new string[] { Texts.ButtonStartTrial, Texts.ButtonNotNow }, Texts.WelcomeMailSubject, messageText, DoNotShowAgainOptions.TryPremium);

            if (result != Texts.ButtonStartTrial)
            {
                return(planInformation.PlanState);
            }

            if (!await StartTrial(identity))
            {
                return(PlanState.CanTryPremium);
            }

            return(PlanState.HasPremium);
        }
Esempio n. 26
0
        /// <summary>
        /// 调用认证接口
        /// </summary>
        /// <param name="strSignInName">登录名</param>
        /// <param name="strPasspord">密码</param>
        /// <returns>用户认证的结果</returns>
        private ISignInUserInfo DefaultAuthenticate(string strSignInName, string strPasspord)
        {
            LogOnIdentity loi = new LogOnIdentity(strSignInName, strPasspord);

            OnBeforeAuthenticate(loi);

            ISignInUserInfo result = null;

            IAuthenticator2 auth2 = this.GetAuthenticator2();

            if (auth2 != null)
            {
                SignInPerformanceCounters.DoAction(() => result = auth2.Authenticate(loi.LogOnName, loi.Password, loi.Context));
            }
            else
            {
                IAuthenticator auth = GetAuthenticator();
                SignInPerformanceCounters.DoAction(() => result = auth.Authenticate(loi.LogOnName, loi.Password));
            }

            return(result);
        }
Esempio n. 27
0
        public async Task TestUpdateActiveFileWithEventRaisedSinceItAppearsAProcessHasExited()
        {
            IDataStore    encryptedFileInfo = New <IDataStore>(_anAxxPath);
            IDataStore    decryptedFileInfo = New <IDataStore>(_decryptedFile1);
            LogOnIdentity key        = new LogOnIdentity("passphrase");
            ActiveFile    activeFile = new ActiveFile(encryptedFileInfo, decryptedFileInfo, key, ActiveFileStatus.NotShareable, new V1Aes128CryptoFactory().CryptoId);

            Resolve.FileSystemState.Add(activeFile);

            ((FakeNow)New <INow>()).TimeFunction = (() => { return(DateTime.UtcNow.AddMinutes(1)); });

            bool changedWasRaised = false;

            Resolve.SessionNotify.AddCommand((SessionNotification notification) =>
            {
                changedWasRaised = notification.NotificationType == SessionNotificationType.ActiveFileChange;
                return(Constant.CompletedTask);
            });
            await New <ActiveFileAction>().CheckActiveFiles(new ProgressContext());

            Assert.That(changedWasRaised, Is.True, "An event should be raised, because status was NotShareable, but no process is active.");
        }
Esempio n. 28
0
        private async Task <LogOnIdentity> AddKnownIdentityFromEventAsync(LogOnEventArgs logOnArgs)
        {
            if (logOnArgs.Cancel || logOnArgs.Passphrase == Passphrase.Empty)
            {
                return(LogOnIdentity.Empty);
            }

            _userSettings.DisplayEncryptPassphrase = logOnArgs.DisplayPassphrase;

            Passphrase    passphrase = logOnArgs.Passphrase;
            LogOnIdentity identity   = await LogOnIdentityFromCredentialsAsync(EmailAddress.Parse(logOnArgs.UserEmail), passphrase);

            if (identity == LogOnIdentity.Empty)
            {
                identity = new LogOnIdentity(passphrase);
                _fileSystemState.KnownPassphrases.Add(passphrase);
                await _fileSystemState.Save();
            }
            await _knownIdentities.AddAsync(identity);

            return(identity);
        }
Esempio n. 29
0
        public async Task TestUpdateActiveFileButWithNoChangeDueToIrrelevantStatus()
        {
            IDataStore    encryptedFileInfo = New <IDataStore>(_anAxxPath);
            IDataStore    decryptedFileInfo = New <IDataStore>(_decryptedFile1);
            LogOnIdentity key        = new LogOnIdentity("passphrase");
            ActiveFile    activeFile = new ActiveFile(encryptedFileInfo, decryptedFileInfo, key, ActiveFileStatus.None, new V1Aes128CryptoFactory().CryptoId);

            Resolve.FileSystemState.Add(activeFile);

            ((FakeNow)New <INow>()).TimeFunction = (() => { return(DateTime.UtcNow.AddMinutes(1)); });

            bool changedWasRaised = false;

            Resolve.SessionNotify.AddCommand((SessionNotification notification) =>
            {
                changedWasRaised = notification.NotificationType == SessionNotificationType.ActiveFileChange;
                return(Constant.CompletedTask);
            });
            await New <ActiveFileAction>().CheckActiveFiles(new ProgressContext());

            Assert.That(changedWasRaised, Is.False, "No event should be raised, because nothing should change.");
        }
Esempio n. 30
0
        public async Task TestRemoveRecentFile()
        {
            IDataStore    encryptedFileInfo = New <IDataStore>(_anAxxPath);
            IDataStore    decryptedFileInfo = New <IDataStore>(_decryptedFile1);
            LogOnIdentity key        = new LogOnIdentity("passphrase");
            ActiveFile    activeFile = new ActiveFile(encryptedFileInfo, decryptedFileInfo, key, ActiveFileStatus.AssumedOpenAndDecrypted | ActiveFileStatus.NotShareable, new V1Aes128CryptoFactory().CryptoId);

            Resolve.FileSystemState.Add(activeFile);
            await Resolve.FileSystemState.Save();

            ActiveFile beforeRemoval = Resolve.FileSystemState.FindActiveFileFromEncryptedPath(encryptedFileInfo.FullName);

            Assert.That(beforeRemoval, Is.Not.Null, "Before being removed, the ActiveFile should be possible to find.");

            activeFile = new ActiveFile(activeFile, ActiveFileStatus.NotDecrypted);
            Resolve.FileSystemState.Add(activeFile);

            await New <ActiveFileAction>().RemoveRecentFiles(new IDataStore[] { New <IDataStore>(encryptedFileInfo.FullName) }, new ProgressContext());

            ActiveFile afterRemoval = Resolve.FileSystemState.FindActiveFileFromEncryptedPath(encryptedFileInfo.FullName);

            Assert.That(afterRemoval, Is.Null, "After being removed, the ActiveFile should not be possible to find.");
        }