public async Task <ActionResult> GAuth(CancellationToken cancellationToken, string uid)
        {
            Session["uid"] = uid;
            var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).
                         AuthorizeAsync(cancellationToken);

            if (result.Credential != null)
            {
                var oauthSerivce = new Google.Apis.Oauth2.v2.Oauth2Service(
                    new BaseClientService.Initializer()
                {
                    HttpClientInitializer = result.Credential,
                    ApplicationName       = "Punnel",
                });

                var profile = await oauthSerivce.Userinfo.Get().ExecuteAsync();

                ViewData["email"] = profile.Email;
                ViewData["uid"]   = uid;
                return(View());
            }
            else
            {
                _log.Error(result.RedirectUri);
                return(new RedirectResult(result.RedirectUri));
            }
        }
Ejemplo n.º 2
0
        private async Task <Userinfoplus> GetUserInfo(string authCode, CancellationToken cancellationToken)
        {
            var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = new ClientSecrets
                {
                    ClientId     = clientId,
                    ClientSecret = clientSecret
                },
                Scopes = new[] { "profile", "email" },
            });

            var tokenRequest = new AuthorizationCodeTokenRequest();

            tokenRequest.ClientId     = clientId;
            tokenRequest.ClientSecret = clientSecret;
            tokenRequest.Code         = authCode;
            tokenRequest.RedirectUri  = "http://localhost:4200";
            var tokenResponse = await tokenRequest.ExecuteAsync(flow.HttpClient, flow.TokenServerUrl, cancellationToken, flow.Clock);

            var cred         = new UserCredential(flow, "user", tokenResponse);
            var oauthSerivce = new Google.Apis.Oauth2.v2.Oauth2Service(new BaseClientService.Initializer()
            {
                HttpClientInitializer = cred,
                ApplicationName       = "App Name",
            });

            return(await oauthSerivce.Userinfo.Get().ExecuteAsync());
        }
        public async Task <ActionResult> GSheetAuth(CancellationToken cancellationToken, string uid)
        {
            Session["uid"] = uid;
            var result = await new AuthorizationCodeMvcApp(this, new AppSheetFlowMetadata()).
                         AuthorizeAsync(cancellationToken);

            if (result.Credential != null)
            {
                var oauthSerivce = new Google.Apis.Oauth2.v2.Oauth2Service(
                    new BaseClientService.Initializer()
                {
                    HttpClientInitializer = result.Credential,
                    ApplicationName       = "Punnel",
                });

                var userInfo = await oauthSerivce.Userinfo.Get().ExecuteAsync();

                ViewData["email"] = userInfo.Email;
                ViewData["uid"]   = uid;
                //ChangeFileName("GOOGLE_SHEET_TOKENS", userInfo.Email);
                return(View());
            }
            else
            {
                return(new RedirectResult(result.RedirectUri));
            }
        }
Ejemplo n.º 4
0
        public async Task <string> Google()
        {
            UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                new ClientSecrets { ClientId = "863315472625-892gs2lqq92v3ehmmb2t4vugictbdbbc.apps.googleusercontent.com", ClientSecret = "YOGZRVQb3ju8qBWurkHDpEtL" },
                new[] { "openid", "email" }, "user", CancellationToken.None);

            if (credential != null)
            {
                var oauthSerivce =
                    new Google.Apis.Oauth2.v2.Oauth2Service(new BaseClientService.Initializer {
                    HttpClientInitializer = credential
                });
                var UserInfo = await oauthSerivce.Userinfo.Get().ExecuteAsync();

                Console.WriteLine(UserInfo.Email + "qweqwe");
                return(getToken(getClaims(UserInfo.Email, "user")));
            }
            else
            {
                Console.WriteLine("null credential");
            }
            return("");
        }
Ejemplo n.º 5
0
        public async Task <string> Auth()
        {
            UserCredential tempCreditinal = await getCredential();

            var oauthSerivce =
                new Google.Apis.Oauth2.v2.Oauth2Service(new BaseClientService.Initializer {
                HttpClientInitializer = tempCreditinal,
                ApplicationName       = ApplicationName
            });
            var UserInfo = await oauthSerivce.Userinfo.Get().ExecuteAsync();

            var userData = new UserData();

            if (!creditinalStorage.ContainsKey(UserInfo.Email))
            {
                userData.credential = tempCreditinal;
                creditinalStorage.Add(UserInfo.Email, userData);
            }
            else
            {
                creditinalStorage[UserInfo.Email].credential = tempCreditinal;
            }
            return(UserInfo.Email);
        }
Ejemplo n.º 6
0
        public void AccediAPI()
        {
            UserCredential credential;

            using (var stream =
                       new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart.json");
                MessageBox.Show(credPath);
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
            }

            if (credential.Token.IsExpired(credential.Flow.Clock))
            {
            }

            // Create Gmail API service.
            var service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            Google.Apis.Oauth2.v2.Oauth2Service oauthService = new Google.Apis.Oauth2.v2.Oauth2Service(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential
            });
            Google.Apis.Oauth2.v2.Data.Userinfoplus userInfo = oauthService.Userinfo.Get().ExecuteAsync().Result;
            string userMail = userInfo.Email;
            string userName = userInfo.Name;
            //var userinfo = service.Users.GetProfile("me");

            // Define parameters of request.
            //UsersResource.LabelsResource.ListRequest request = service.Users.Labels.List("me");


            // List labels.
            //IList<Google.Apis.Gmail.v1.Data.Label> labels = request.Execute().Labels;
            //Console.WriteLine("Labels:");
            //if (labels != null && labels.Count > 0)
            //{
            //    foreach (var labelItem in labels)
            //    {
            //       // MessageBox.Show(labelItem.Name);
            //    }
            //}
            //else
            //{
            //    MessageBox.Show("no alabel found");
            //}

            //var msg = new AE.Net.Mail.MailMessage
            //{
            //    Subject = "test invio api",
            //    Body = "Prova di invio",
            //    From = new MailAddress("*****@*****.**")
            //};

            //msg.To.Add(new MailAddress("*****@*****.**"));
            //msg.ReplyTo.Add(msg.From);
            //var msgStr = new StringWriter();
            //msg.Save(msgStr);
            //service.Users.Messages.Send(new Google.Apis.Gmail.v1.Data.Message { Raw = Base64UrlEncode(msgStr.ToString()) }, "me").Execute();



            MailMessage mail = new MailMessage();

            mail.From = new MailAddress(userMail, userName);
            mail.To.Add("*****@*****.**");
            mail.Subject = "prova";



            string         htmlBody = "<html><body><img src=\"cid:logo\"><br><br><br><p>" + "test" + "</p><br></body></html>";
            AlternateView  avHtml   = AlternateView.CreateAlternateViewFromString(htmlBody, null, "text/html");
            LinkedResource logo     = new LinkedResource("intestazione.jpg", System.Net.Mime.MediaTypeNames.Image.Jpeg);

            logo.ContentId = "logo";
            avHtml.LinkedResources.Add(logo);
            mail.AlternateViews.Add(avHtml);

            MimeMessage message = MimeMessage.CreateFromMailMessage(mail);

            var result = service.Users.Messages.Send(new Google.Apis.Gmail.v1.Data.Message {
                Raw = Base64UrlEncode(message.ToString())
            }, "me").Execute();

            MessageBox.Show("message id" + result.Id);
        }
Ejemplo n.º 7
0
        private void Invio_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            int contaInviati = 1;

            info.Text = "Richiesta autorizzazione Gmail...";
            try
            {
                UserCredential credential;

                using (var stream =
                           new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
                {
                    string credPath = System.Environment.GetFolderPath(
                        System.Environment.SpecialFolder.Personal);
                    credPath   = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart.json");
                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        Scopes,
                        "user",
                        CancellationToken.None,
                        new FileDataStore(credPath, true)).Result;
                }

                if (credential.Token.IsExpired(credential.Flow.Clock))
                {
                    if (credential.RefreshTokenAsync(CancellationToken.None).Result)
                    {
                        info.Text = "Accesso a Gmail ottenuto";
                    }
                    else
                    {
                        info.Text = "Accesso a Gmail negato";
                        return;
                    }
                }

                else
                {
                    info.Text = "Accesso a Gmail ottenuto";
                }

                var service = new GmailService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = ApplicationName,
                });

                Google.Apis.Oauth2.v2.Oauth2Service oauthService = new Google.Apis.Oauth2.v2.Oauth2Service(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential
                });
                Google.Apis.Oauth2.v2.Data.Userinfoplus userInfo = oauthService.Userinfo.Get().ExecuteAsync().Result;
                string userMail = userInfo.Email;
                string userName = userInfo.Name;

                info.Text = "Invio email in corso...";

                for (int i = 0; i < destinatari.Count; i++)
                {
                    MailMessage mail = new MailMessage();
                    mail.From = new MailAddress(userMail, userName);
                    mail.To.Add(destinatari[i]);
                    mail.Subject = txtOggetto.Text;
                    string tmpMEX = txtMessaggio.Text;
                    tmpMEX = tmpMEX.Replace("<NOME>", nomi[i]);
                    tmpMEX = tmpMEX.Replace("<COGNOME>", cognomi[i]);
                    tmpMEX = tmpMEX.Replace("<TESSERA>", tessere[i]);
                    tmpMEX = tmpMEX.Replace("<CODICE>", codici[i]);
                    tmpMEX = tmpMEX.Replace("\r\n", "<br>");


                    string         htmlBody = "<html><body><img src=\"cid:logo\"><br><br><br><p>" + tmpMEX + "</p><br><h6>" + txtPivacy.Text + "</h6></body></html>";
                    AlternateView  avHtml   = AlternateView.CreateAlternateViewFromString(htmlBody, null, "text/html");
                    LinkedResource logo     = new LinkedResource("intestazione.jpg", System.Net.Mime.MediaTypeNames.Image.Jpeg);
                    logo.ContentId = "logo";
                    avHtml.LinkedResources.Add(logo);
                    mail.AlternateViews.Add(avHtml);

                    MimeMessage message = MimeMessage.CreateFromMailMessage(mail);

                    var result = service.Users.Messages.Send(new Google.Apis.Gmail.v1.Data.Message {
                        Raw = Base64UrlEncode(message.ToString())
                    }, "me").Execute();
                    info.Text = "Inviate " + contaInviati.ToString() + " di " + destinatari.Count + " ID " + result.Id;
                    contaInviati++;
                }
                MessageBox.Show("Email inviate correttamente");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Errore durante l'invio " + ex.InnerException);
                info.Text = "";
            }
        }
Ejemplo n.º 8
0
        private void Invio_DoWork(object sender, DoWorkEventArgs e)
        {
            string       utente, passwordUtente, id;
            string       cartella = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
            StreamReader sr       = new StreamReader(cartella + "\\LibroSoci\\sms.ini");

            try
            {
                string tmp = sr.ReadLine();
                sr.Close();
                string[] parti = tmp.Split(';');
                id             = parti[0];
                utente         = parti[1];
                passwordUtente = parti[2];

                int contaInviati = 1;
                info.Text = "Richiesta autorizzazione Gmail...";

                UserCredential credential;

                using (var stream =
                           new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
                {
                    string credPath = System.Environment.GetFolderPath(
                        System.Environment.SpecialFolder.Personal);
                    credPath   = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart.json");
                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        Scopes,
                        "user",
                        CancellationToken.None,
                        new FileDataStore(credPath, true)).Result;
                }

                if (credential.Token.IsExpired(credential.Flow.Clock))
                {
                    if (credential.RefreshTokenAsync(CancellationToken.None).Result)
                    {
                        info.Text = "Accesso a Gmail ottenuto";
                    }
                    else
                    {
                        info.Text = "Accesso a Gmail negato";
                    }
                }

                else
                {
                    info.Text = "Accesso a Gmail ottenuto";
                }

                var service = new GmailService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = ApplicationName,
                });

                Google.Apis.Oauth2.v2.Oauth2Service oauthService = new Google.Apis.Oauth2.v2.Oauth2Service(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential
                });
                Google.Apis.Oauth2.v2.Data.Userinfoplus userInfo = oauthService.Userinfo.Get().ExecuteAsync().Result;
                string userMail = userInfo.Email;
                string userName = userInfo.Name;

                info.Text = "Invio sms in corso...";
                try
                {
                    MailMessage mail = new MailMessage();
                    mail.From = new MailAddress(userMail);
                    mail.To.Add("*****@*****.**");
                    StringBuilder st = new StringBuilder();
                    st.AppendLine("api_id:" + id);
                    st.AppendLine("user:"******"password:"******"to:+39" + cellulari[i]);
                    }
                    st.AppendLine("text:" + txtMessaggio.Text);
                    st.AppendLine("reply:" + userMail);

                    mail.Body = st.ToString();

                    MimeMessage message = MimeMessage.CreateFromMailMessage(mail);

                    var result = service.Users.Messages.Send(new Google.Apis.Gmail.v1.Data.Message {
                        Raw = Base64UrlEncode(message.ToString())
                    }, "me").Execute();
                    info.Text = "SMS inviati";
                    contaInviati++;

                    MessageBox.Show("SMS inviati correttamente");
                }
                catch
                {
                    MessageBox.Show("Errore durante l'invio");
                    info.Text = "";
                }
            }

            catch (Exception ex) { MessageBox.Show("Errore " + ex.Message + ex.Data, "Errore invio", MessageBoxButtons.OK, MessageBoxIcon.Error); };
        }