Esempio n. 1
0
        protected void alterarDados(object sender, EventArgs e)
        {
            if (txtSenha.Text != txtConfirmarSenha.Text)
            {
                Label1.Text = "A senha e confirmação de senha não conferem";
                return;
            }
            if (Session["userID"] != null)
            {
                string     URL           = $"https://localhost:44323/api/ClienteOnline/" + Session["userID"];
                string     urlParameters = "";
                HttpClient client        = new HttpClient();
                client.BaseAddress = new Uri(URL);
                ClienteOnline cli;
                if ((String.IsNullOrWhiteSpace(txtSenha.Text) || String.IsNullOrWhiteSpace(txtConfirmarSenha.Text)) && !String.IsNullOrWhiteSpace(TextBox1.Text) && !String.IsNullOrWhiteSpace(TextBox2.Text))
                {
                    cli = new ClienteOnline(TextBox1.Text, TextBox2.Text, null, null);
                }
                else if (!String.IsNullOrWhiteSpace(TextBox1.Text) && !String.IsNullOrWhiteSpace(TextBox2.Text))
                {
                    cli = new ClienteOnline(TextBox1.Text, TextBox2.Text, null, txtSenha.Text);
                }
                else
                {
                    Label1.Text = "Digite um nome e sobrenome";
                    return;
                }

                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue((string)Session["userToken"]);
                // Add an Accept header for JSON format.
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));

                // List data response.
                JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                HttpResponseMessage  response   = client.PostAsync(urlParameters, new StringContent(serializer.Serialize(cli), Encoding.UTF8, "application/json")).Result;
                if (response.IsSuccessStatusCode)
                {
                    Label1.Text = "Dados alterados com sucesso!";
                    textboxs    = false;
                }
                else
                {
                    Label1.Text = "Erro";
                }
            }
            else
            {
                Response.Redirect("Index2.aspx");
            }
        }
        protected void btnRedefinir_Click(object sender, EventArgs e)
        {
            if (txtSenha.Text != txtConfirmarSenha.Text)
            {
                lblAvisoSenha.Text = "A senha e confirmação de senha não conferem";
                return;
            }
            if (id != null && !String.IsNullOrWhiteSpace(txtSenha.Text) && !String.IsNullOrWhiteSpace(txtConfirmarSenha.Text))
            {
                string     URL           = $"https://localhost:44323/api/ClienteOnline/" + id;
                string     urlParameters = "";
                HttpClient client        = new HttpClient();
                client.BaseAddress = new Uri(URL);
                ClienteOnline cli;
                cli = new ClienteOnline(null, null, null, txtSenha.Text);

                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(token);
                // Add an Accept header for JSON format.
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));

                // List data response.
                JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                HttpResponseMessage  response   = client.PostAsync(urlParameters, new StringContent(serializer.Serialize(cli), Encoding.UTF8, "application/json")).Result;
                if (response.IsSuccessStatusCode)
                {
                    lblAvisoSenha.Text = "Dados alterados com sucesso!";
                }
                else
                {
                    lblAvisoSenha.Text = "Erro";
                }
            }
            else
            {
                Response.Redirect("Index2.aspx");
            }
        }
        public Dictionary <string, object> Put([FromBody] ClienteOnline newClient)
        {
            if (newClient.Login == null || newClient.Password == null || newClient.Nome == null || newClient.Sobrenome == null)
            {
                Response.StatusCode = StatusCodes.Status400BadRequest;
                return(new Dictionary <string, object> {
                    { "error", "MALFORMED_REQUEST_ERROR" },
                });
            }

            if (!EmailChecker.IsValidEmail(newClient.Login))
            {
                Response.StatusCode = StatusCodes.Status400BadRequest;
                return(new Dictionary <string, object> {
                    { "error", "EMAIL_INVALID_ERROR" },
                });
            }

            else if (newClient.Password.Length < 1)
            {
                return(new Dictionary <string, object> {
                    { "error", "PASS_TOO_SHORT_ERROR" },
                });
            }

            else if (newClient.Nome.Length < 1)
            {
                return(new Dictionary <string, object> {
                    { "error", "NAME_TOO_SHORT_ERROR" },
                });
            }

            else if (newClient.Sobrenome.Length < 1)
            {
                return(new Dictionary <string, object> {
                    { "error", "SURNAME_TOO_SHORT_ERROR" },
                });
            }

            else
            {
                using (
                    SqlConnection connection = new SqlConnection(string.Format("User ID={0}; Password={1}; Initial Catalog={2}; Persist Security Info=True;Data Source={3}", Program.dbLogin, Program.dbPass, "dbSblenders", Program.dbEnv))
                    )
                    using (
                        SqlCommand insertAgentCommand = new SqlCommand("INSERT INTO tbAgente(tipoAgenteID, agenteLogin, agenteSenha, agenteSalt) VALUES(1, @login, @pass, @salt) SELECT CAST(SCOPE_IDENTITY() AS INT)", connection)
                        )
                    {
                        string salt = RandomGenerator.GenerateHexString(32);
                        insertAgentCommand.Parameters.Add(new SqlParameter("@salt", salt));
                        insertAgentCommand.Parameters.Add(new SqlParameter("@login", newClient.Login));
                        insertAgentCommand.Parameters.Add(new SqlParameter("@pass", PasswordHasher.Hash(newClient.Password, salt)));
                        connection.Open();
                        int agentID;
                        try
                        {
                            agentID = (int)insertAgentCommand.ExecuteScalar();
                        }

                        catch (SqlException ex)
                        {
                            if (ex.Number == 2601 || ex.Number == 2627) //ver se é unique violation
                            {
                                Response.StatusCode = StatusCodes.Status400BadRequest;
                                return(new Dictionary <string, object> {
                                    { "error", "LOGIN_ALREADY_EXISTS_ERROR" }
                                });
                            }
                            else
                            {
                                Response.StatusCode = StatusCodes.Status500InternalServerError;
                                return(new Dictionary <string, object> {
                                    { "error", "INTERNAL_ERROR" }
                                });
                            }
                        }

                        using (
                            SqlCommand insertClientCommand = new SqlCommand("INSERT INTO tbClienteOnline(clienteOnlineNome, clienteOnlineSobrenome, clienteOnlineUrlVerifica, clienteOnlineVerificadoFlag, agenteID) VALUES(@name, @surname, @url, 0, @id)", connection)
                            )
                        {
                            string url = RandomGenerator.GenerateHexString(16);

                            insertClientCommand.Parameters.Add(new SqlParameter("@name", newClient.Nome));
                            insertClientCommand.Parameters.Add(new SqlParameter("@surname", newClient.Sobrenome));
                            insertClientCommand.Parameters.Add(new SqlParameter("@url", url));
                            insertClientCommand.Parameters.Add(new SqlParameter("@id", agentID));

                            int rowsAffected = insertClientCommand.ExecuteNonQuery();
                            if (rowsAffected < 1)
                            {
                                Response.StatusCode = StatusCodes.Status500InternalServerError;
                                return(new Dictionary <string, object> {
                                    { "error", "INTERNAL_ERROR" }
                                });
                            }
                            else
                            {
                                //mandar email aqui [email protected] wbBA6rgyGLQ5dPZ
                                string      htmlString = string.Format("<h1>Clique neste link para verificar sua conta, {0}:</h1><br/><a href='http://*****:*****@gmail.com");
                                message.To.Add(new MailAddress(newClient.Login));
                                message.Subject            = "Verifique sua conta SBLENDERS";
                                message.IsBodyHtml         = true;
                                message.Body               = htmlString;
                                smtp.Port                  = 587;
                                smtp.Host                  = "smtp.gmail.com";
                                smtp.EnableSsl             = true;
                                smtp.UseDefaultCredentials = false;
                                smtp.Credentials           = new NetworkCredential("*****@*****.**", "wbBA6rgyGLQ5dPZ");
                                smtp.DeliveryMethod        = SmtpDeliveryMethod.Network;
                                smtp.Send(message);
                                return(new Dictionary <string, object> {
                                    { "message", "SUCCESS" }
                                });
                            }
                        }
                    }
            }
        }
        public void Post([FromBody] ClienteOnline new_info, int id)
        {
            string token = Request.Headers["Authorization"];

            using (
                SqlConnection connection = new SqlConnection(string.Format(
                                                                 "User ID={0}; Password={1}; Initial Catalog={2}; Persist Security Info=True;Data Source={3}"
                                                                 , Program.dbLogin, Program.dbPass, "dbSblenders", Program.dbEnv))
                )

                using (
                    SqlCommand userQueryCommand = new SqlCommand(
                        "SELECT agenteID, tipoAgenteID, agenteSalt FROM tbAgente WHERE agenteID= @id AND agenteToken = @token;"
                        , connection)
                    ){
                    userQueryCommand.Parameters.Add(new SqlParameter("@id", id));
                    userQueryCommand.Parameters.Add(new SqlParameter("@token", token));
                    using (SqlDataAdapter sqlAdapter = new SqlDataAdapter(userQueryCommand)){
                        var authTable = new DataTable();
                        sqlAdapter.Fill(authTable);
                        if (authTable.Rows.Count != 1)
                        {
                            Response.StatusCode = 403;
                            return;
                        }
                        else if ((int)authTable.Rows[0]["tipoAgenteID"] != 1)
                        {
                            Response.StatusCode = 403;
                            return;
                        }
                        else
                        {
                            using (SqlCommand changeInfoCommand = new SqlCommand()){
                                List <string> updateCommands = new List <string>();
                                bool          updateData     = false;
                                bool          updatePass     = false;
                                if (new_info.Nome != null)
                                {
                                    updateData = true;
                                    updateCommands.Add("clienteOnlineNome = @nome");
                                    changeInfoCommand.Parameters.Add(new SqlParameter("@nome", new_info.Nome));
                                }
                                if (new_info.Sobrenome != null)
                                {
                                    updateData = true;
                                    updateCommands.Add("tbClienteOnline.clienteOnlineSobrenome = @sbnome");
                                    changeInfoCommand.Parameters.Add(new SqlParameter("@sbnome", new_info.Sobrenome));
                                }
                                if (new_info.Password != null)
                                {
                                    updatePass = true;
                                    changeInfoCommand.Parameters.Add(new SqlParameter("@pass", PasswordHasher.Hash(new_info.Password, authTable.Rows[0]["agenteSalt"].ToString())));
                                }
                                changeInfoCommand.Parameters.Add(new SqlParameter("@id", id));

                                changeInfoCommand.Connection = connection;

                                if (updateData)
                                {
                                    connection.Open();
                                    changeInfoCommand.CommandText = $"UPDATE tbClienteOnline SET {String.Join(",",updateCommands.ToArray())} WHERE agenteID = @id";
                                    changeInfoCommand.ExecuteNonQuery();
                                    connection.Close();
                                }
                                if (updatePass)
                                {
                                    connection.Open();
                                    changeInfoCommand.CommandText = $"UPDATE tbAgente SET agenteSenha=@pass WHERE agenteID = @id";
                                    changeInfoCommand.ExecuteNonQuery();
                                    connection.Close();
                                }
                                connection.Close();
                            }
                        }
                    }
                }
        }