Inheritance: Crystalbyte.Equinox.Security.SecureClient
示例#1
0
        public void Authenticate(ImapClient client, NetworkCredential credential, Account account)
        {
            if (!client.ServerCapability.Items.Contains("AUTH=XOAUTH")) {
                return;
            }

            if (string.IsNullOrEmpty(account.XOAuthKey)) {
                // in this case the username is the email address;
                var email = credential.UserName;

                var token = new OAuthRequest().WithAnonymousConsumer().WithEndpoint("https://www.google.com/accounts/OAuthGetRequestToken").WithParameter("scope", "https://mail.google.com/") // gmail specific
                    .WithParameter(OAuthParameters.OAuthCallback, "oob").WithParameter("xoauth_displayname", "Crystalbyte Equinox") // xoauth protocol specific
                    .WithSignatureMethod(OAuthSignatureMethods.HmacSha1).Sign().RequestToken();

                var authUrl = new OAuthRequest().WithEndpoint("https://www.google.com/accounts/OAuthAuthorizeToken").WithToken(token).GetAuthorizationUri();

                Process.Start(authUrl.AbsoluteUri);

                string verificationCode;
                using (var form = new OAuthVerificationForm()) {
                    var result = form.ShowDialog();
                    if (result == DialogResult.Cancel) {
                        return;
                    }
                    verificationCode = form.VerificationCode;
                }

                var accessToken = new OAuthRequest().WithAnonymousConsumer().WithEndpoint("https://www.google.com/accounts/OAuthGetAccessToken").WithParameter(OAuthParameters.OAuthVerifier, verificationCode).WithSignatureMethod(OAuthSignatureMethods.HmacSha1).WithToken(token).Sign().RequestToken();

                var xOUrl = string.Format("https://mail.google.com/mail/b/{0}/imap/", email);
                account.XOAuthKey = new OAuthRequest().WithAnonymousConsumer().WithEndpoint(xOUrl).WithSignatureMethod(OAuthSignatureMethods.HmacSha1).WithToken(accessToken).Sign().CreateXOAuthKey();
            }

            client.AuthenticateXOAuth(account.XOAuthKey);
        }
示例#2
0
 public void AuthHandler(ImapClient client, NetworkCredential credential, ImapAccountInfo account)
 {
     if (null != oAuthProvider)
     {
         oAuthProvider.OAuthHandler(client, credential, account);
     }
 }
示例#3
0
        // needed as a callback if IMAP uses OAuth (not necessary if username/pwd will be provided)
        public void OAuthHandler(ImapClient client,
                 NetworkCredential credential,
                 ImapAccountInfo account)
        {
            if (!client.ServerCapability.Items.Contains("AUTH=XOAUTH"))
            {
                return;
            }

            if (string.IsNullOrEmpty(account.XOAuthKey))
            {
                // in this case the username is the email address;
                var email = credential.UserName;

                var token = new OAuthRequest().
                    WithAnonymousConsumer().
                    WithEndpoint(XOAuthRequestTokenEndPoint).
                    WithParameter("scope", XOAuthRequestScope).
                    WithParameter(OAuthParameters.OAuthCallback, "oob").
                    WithParameter("xoauth_displayname", account.XOAuthAppDisplayName).
                    WithSignatureMethod(OAuthSignatureMethods.HmacSha1).
                    Sign().
                    RequestToken();

                var authUrl = new OAuthRequest().
                    WithEndpoint(XOAuthAuthTokenEndPoint).
                    WithToken(token).
                    GetAuthorizationUri();

                // TODO: change this to (a) redirect the user to the authUri,
                // (b) get back the verification code in a callback from the authUri
                //
                // Probably means we have to break this method into at least two different methods
                // with some sort of flow between them.
                //
                account.XOAuthSecret = GetXOAuthSecret(authUrl);

                var accessToken = new OAuthRequest().
                    WithAnonymousConsumer().
                    WithEndpoint(XOAuthAccessTokenEndPoint).
                    WithParameter(OAuthParameters.OAuthVerifier, account.XOAuthSecret).
                    WithSignatureMethod(OAuthSignatureMethods.HmacSha1).
                    WithToken(token).
                    Sign().
                    RequestToken();

                var authUri = String.Format(XOAuthUrlFormat, email);
                account.XOAuthKey = new OAuthRequest().
                    WithAnonymousConsumer().
                    WithEndpoint(authUri).
                    WithSignatureMethod(OAuthSignatureMethods.HmacSha1).
                    WithToken(accessToken).
                    Sign().
                    CreateXOAuthKey();
            }

            client.AuthenticateXOAuth(account.XOAuthKey);
        }
示例#4
0
        public void ThreadStart()
        {
            _clientIdle = AccountController.CreateClientByAccount(AccountController.Account);
            Thread.Sleep(1000);

            _clientIdle.StatusUpdateReceived += OnStatusUpdateReceived;
            _clientIdle.Select("INBOX");
            _clientIdle.StartIdle();
        }
        public void FindFetchExpressionTest()
        {
            using (var client = new ImapClient()) {
                var query = client.Messages.Where(x => x.SequenceNumber > 0 && x.SequenceNumber < 20).Select(x => new SampleContainer {MySubject = x.Subject});

                var expression = new ExpressionCrawler().FindFetchLamda(query.Expression);
                Assert.IsNotNull(expression);
            }
        }
示例#6
0
        public Imap(Account acct)
        {
            Client = AccountController.CreateClientByAccount(acct);

            App.Log.Info("User authentication finished (IMAP)");

            /*var obj = new ImapIdle();
            ImapController.IdleThread = new Thread(obj.ThreadStart);
            ImapController.IdleThread.Name = "IMAP IDLE Thread";
            ImapController.IdleThread.Start();*/
        }
        public void TranslateFromAndToQuery()
        {
            using (var client = new ImapClient()) {
                var translator = new ImapQueryTranslator();
                var expression = client.Messages.Where(x => x.From.Contains("Foo") && x.To.Contains("Bar")).Expression;

                const string expected = "SEARCH FROM \"Foo\" TO \"Bar\"";

                var result = translator.Translate(expression);
                Assert.IsFalse(result.IsUid);
                Assert.AreEqual(expected, result.SearchCommand);
            }
        }
        public void TranslateFetchRecursiveBodyPartsTest()
        {
            using (var client = new ImapClient()) {
                var query = client.Messages.Where(x => x.SequenceNumber == 1).Select(x => new SampleContainer {MyText = (string) x.Parts("1.Text"), MyPart = (string) x.Parts("1.2")});

                ResponseProcessor projector;
                var translator = new ImapFetchQueryTranslator();
                var expression = new ExpressionCrawler().FindFetchLamda(query.Expression);
                var actual = translator.Translate(expression, "1:10", out projector);
                const string expected = "FETCH 1:10 (BODY[1.TEXT] BODY[1.2])";
                Assert.AreEqual(expected, actual);
            }
        }
        public static ImapClient CreateClientByAccount(Account account)
        {
            try
            {
                var client = new ImapClient { Security = account.Security };
                //client.ManualSaslAuthenticationRequired += (sender, e) => AuthenticateManually(e, account);
                var port = client.Security == SecurityPolicies.Explicit ? ImapPorts.Ssl : ImapPorts.Default;
                client.Connect(account.Host, port);
                //Thread.Sleep(100);
                client.Authenticate(account.Credential, SaslMechanics.Login);
                //Thread.Sleep(500);

                return client;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
        }
示例#10
0
        public ImapClient InitClient(ImapAccountInfo account)
        {
            Debug.Assert(null != account);

            ImapClient imapClient = new Crystalbyte.Equinox.Imap.ImapClient();
            imapClient.Security = SecurityPolicies.Explicit;

            imapClient.Connect(this.Host, this.Port);

            if ((null != account.UserName) && (null != account.UserPwd))
            {
                // doesn't need OAuth --- try regular LOGIN
                imapClient.Authenticate(account.UserName, account.UserPwd, SaslMechanics.Login);
            }
            else
            {
                imapClient.ManualSaslAuthenticationRequired += (sender, e) => this.AuthHandler(e.Client, e.UserCredentials, account);
                imapClient.Authenticate(account.UserName, account.UserPwd);
            }
            return imapClient;
        }
示例#11
0
 /// This method creates a mail client that connects to a well-defined IMAP server and SMTP server. 
 public MailClient(ImapAccountInfo ImapAccount, SmtpAccountInfo SmtpAccount)
 {
     imapClient = ImapAccount.Provider.InitClient(ImapAccount);
     smtpClient = SmtpAccount.Provider.InitClient(SmtpAccount);
 }
示例#12
0
        /// <summary>
        ///   Attempt to notify the application that automatic sasl authentication is not possible.
        ///   The ManualSaslAuthenticationRequired event will be thrown.
        /// </summary>
        /// <param name = "credential">The credentials provided by the user.</param>
        /// <param name = "client">The current instance of the client, responsible for the connection.</param>
        internal bool InvokeManualSaslAuthenticationRequired(NetworkCredential credential, ImapClient client)
        {
            var handler = ManualSaslAuthenticationRequired;

            if (handler != null)
            {
                var e = new ManualSaslAuthenticationRequiredEventArgs(credential, client);
                handler(this, e);
                return(e.IsAuthenticated);
            }
            return(false);
        }
示例#13
0
 public ImapAuthenticator(ImapClient client)
 {
     _client = client;
 }
示例#14
0
 internal ImapResponseReader(ImapClient client)
 {
     _client = client;
 }
示例#15
0
 public static ImapClient CreateSaslClient()
 {
     var client = new ImapClient() { Security = SecurityPolicies.Explicit };
     client.RemoteCertificateValidationFailed += (sender, e) => e.IsCancelled = false;
     return client;
 }
示例#16
0
        public ImapReader(ImapClient client, string folder, MessageCallbackDelegate cb)
        {
            callbackFn = cb;
            folderName = folder;
            imapClient = client;

            // Step 1: add delegate to the
            imapClient.StatusUpdateReceived += onStatusUpdateReceived;
            Crystalbyte.Equinox.Imap.Responses.SelectExamineImapResponse selectResponse = imapClient.Select("INBOX");

            // record the next uid to read ---- this ensures that we will only read new messages
            uidNext = selectResponse.MailboxInfo.UidNext;

            /***
            // let's just check that we can get messages
            var query = client.Messages;
            foreach (var msg in query)
            {
                if (msg.Subject.Contains("bot"))
                {
                    callbackFn(msg.Text);
                }
            }
             * ***/

            IdlerDelegate asyncIdleMethod = startIdle;

            asyncIdleMethod.BeginInvoke(startIdleAsyncCallback, asyncIdleMethod);
        }
 public void TranslateNegativeOperatorSeenFlags()
 {
     using (var client = new ImapClient()) {
         var translator = new ImapQueryTranslator();
         var expression = client.Messages.Where(x => x.Flags == MessageFlags.Seen).Expression;
         SearchTranslationResult result = null;
         try {
             result = translator.Translate(expression);
             Assert.Fail("This call must throw a NotSupportedException.");
         }
         catch (NotSupportedException) {
             Assert.IsTrue(true);
             if (result != null) {
                 Assert.IsFalse(result.IsUid);
             }
         }
     }
 }
        public void TranslateHasHeaderField()
        {
            ImapQueryTranslator target;
            Expression expression;

            using (var client = new ImapClient()) {
                target = new ImapQueryTranslator();
                expression = client.Messages.Where(x => x.Headers.Any(y => y.Name.Contains("Foo") && y.Value.Contains("Bar"))).Expression;
            }

            const string expected = "SEARCH HEADER \"Foo\" \"Bar\"";

            var result = target.Translate(expression);
            Assert.AreEqual(expected, result.SearchCommand);
        }
        public void TranslateSeperatedUidQueriesOpenEnd()
        {
            ImapQueryTranslator target;
            Expression expression;

            using (var client = new ImapClient()) {
                target = new ImapQueryTranslator();
                expression = client.Messages.Where(x => x.Uid >= 1).Expression;
            }

            const string expected = "UID SEARCH UID 1:*";

            var resuult = target.Translate(expression);
            Assert.AreEqual(expected, resuult.SearchCommand);
        }
 public ImapAuthenticator(ImapClient client)
 {
     _client = client;
 }
        public void TranslateSingleSequenceNumberQuery()
        {
            using (var client = new ImapClient()) {
                var translator = new ImapQueryTranslator();
                var expression = client.Messages.Where(x => x.SequenceNumber == 5).Expression;

                const string expected = "SEARCH 5";

                var result = translator.Translate(expression);
                Assert.IsFalse(result.IsUid);
                Assert.AreEqual(expected, result.SearchCommand);
            }
        }
示例#22
0
 private ImapClient CreateClientByAccount(Account account)
 {
     try {
         var client = new ImapClient {Security = account.Security};
         client.ManualSaslAuthenticationRequired += (sender, e) => AuthenticateManually(e, account);
         var port = client.Security == SecurityPolicies.Explicit ? ImapPorts.Ssl : ImapPorts.Default;
         client.Connect(account.Host, port);
         client.Authenticate(account.Credential);
         return client;
     }
     catch (Exception ex) {
         LogSafely(ex.Message);
         throw;
     }
 }
        public void TranslateSingleUidQuery()
        {
            using (var client = new ImapClient()) {
                var translator = new ImapQueryTranslator();
                var expression = client.Messages.Where(x => x.Uid == 5).Expression;

                const string expected = "UID SEARCH UID 5";

                var result = translator.Translate(expression);
                Assert.IsTrue(result.IsUid);
                Assert.AreEqual(expected, result.SearchCommand);
            }
        }
示例#24
0
 public ManualSaslAuthenticationRequiredEventArgs(NetworkCredential credential, ImapClient client)
 {
     Client          = client;
     UserCredentials = credential;
 }
        public void TranslateTestSearchDateSinceSeenOrAnswered()
        {
            ImapQueryTranslator target;
            Expression expression;

            using (var client = new ImapClient()) {
                var date = DateTime.Parse("1-Feb-1994");
                target = new ImapQueryTranslator();

                expression = client.Messages.Where(x => x.Date < date && (x.Flags.HasFlag(MessageFlags.Seen) || x.Flags.HasFlag(MessageFlags.Answered))).Expression;

                // we need to evaluate the field date into a constant.
                expression = Evaluator.PartialEval(expression);
            }

            const string expected = "SEARCH SENTBEFORE 1-Feb-1994 OR SEEN ANSWERED";

            var result = target.Translate(expression);
            Assert.IsFalse(result.IsUid);
            Assert.AreEqual(expected, result.SearchCommand);
        }
示例#26
0
 /// <summary>
 ///   Attempt to notify the application that automatic sasl authentication is not possible.
 ///   The ManualSaslAuthenticationRequired event will be thrown.
 /// </summary>
 /// <param name = "credential">The credentials provided by the user.</param>
 /// <param name = "client">The current instance of the client, responsible for the connection.</param>
 internal bool InvokeManualSaslAuthenticationRequired(NetworkCredential credential, ImapClient client)
 {
     var handler = ManualSaslAuthenticationRequired;
     if (handler != null) {
         var e = new ManualSaslAuthenticationRequiredEventArgs(credential, client);
         handler(this, e);
         return e.IsAuthenticated;
     }
     return false;
 }
        public void TranslateTestSearchIsOldAndNotIsNew()
        {
            ImapQueryTranslator target;
            Expression expression;

            using (var client = new ImapClient()) {
                target = new ImapQueryTranslator();
                expression = client.Messages.Where(x => x.IsNew && !x.IsOld).Expression;
            }

            const string expected = "SEARCH (RECENT UNSEEN) NOT NOT RECENT";

            var result = target.Translate(expression);
            Assert.IsFalse(result.IsUid);
            Assert.AreEqual(expected, result.SearchCommand);
        }
示例#28
0
 internal ImapResponseReader(ImapClient client)
 {
     _client = client;
 }
        public void TranslateTestSearchSeenOperator()
        {
            try {
                using (var client = new ImapClient()) {
                    var target = new ImapQueryTranslator();
                    var expression = client.Messages.Where(x => x.Flags == MessageFlags.Seen).Expression;

                    target.Translate(expression);
                }
                Assert.Fail();
            }
            catch (NotSupportedException) {
                Assert.IsTrue(true);
            }
        }
 public void TranslateFetchSelectTest()
 {
     using (var client = new ImapClient()) {
         var query = client.Messages.Where(x => x.SequenceNumber == 1).Select(x => new SampleContainer {MySubject = x.Subject});
         ResponseProcessor projector;
         var translator = new ImapFetchQueryTranslator();
         var expression = new ExpressionCrawler().FindFetchLamda(query.Expression);
         var actual = translator.Translate(expression, "1:10", out projector);
         const string expected = "FETCH 1:10 (BODY[HEADER.FIELDS (Subject)])";
         Assert.AreEqual(expected, actual);
     }
 }
        public void TranslateTestSearchUnseen()
        {
            ImapQueryTranslator target;
            Expression expression;

            using (var client = new ImapClient()) {
                target = new ImapQueryTranslator();
                expression = client.Messages.Where(x => !x.Flags.HasFlag(MessageFlags.Seen)).Expression;
            }

            const string expected = "SEARCH NOT SEEN";

            var result = target.Translate(expression);
            Assert.IsFalse(result.IsUid);
            Assert.AreEqual(expected, result.SearchCommand);
        }
        public void TranslateTestSearchUnseenTextKeyword()
        {
            ImapQueryTranslator target;
            Expression expression;

            using (var client = new ImapClient()) {
                target = new ImapQueryTranslator();
                expression = client.Messages.Where(x => !x.Flags.HasFlag(MessageFlags.Seen)
                                                        && x.Text.Contains("Peter File")
                                                        && x.Keywords.Contains("Cheers")
                                                        && !x.Keywords.Contains("Cheerio")).Expression;
            }

            const string expected = "SEARCH NOT SEEN TEXT \"Peter File\" KEYWORD Cheers NOT KEYWORD Cheerio";

            var result = target.Translate(expression);
            Assert.IsFalse(result.IsUid);
            Assert.AreEqual(expected, result.SearchCommand);
        }
 public ManualSaslAuthenticationRequiredEventArgs(NetworkCredential credential, ImapClient client)
 {
     Client = client;
     UserCredentials = credential;
 }