Hỏi đáp

Chia sẻ kiến thức, cùng nhau phát triển

Giữ đăng nhập và đổi mật khẩu với tài khoản mình đã đăng nhập c# winform kết nối tới sql

2 năm trước 1.620 lượt xem 1 bình luận

Xin chào các anh/chị ạ, em đang có 1 project, nma search google mãi mà kh thấy thứ mình cần tìm, nên em lên đây xin hỏi là làm cách nào để mình có thể giữ đăng nhập và đổi mật khẩu với tài khoản mình đã đăng nhập c# winform kết nối tới sql ạ

Bình luận

Để bình luận, bạn cần đăng nhập bằng tài khoản Howkteam.

Đăng nhập
phucprotein đã bình luận 2 năm trước

authentication và authorization thì có khá nhiều nhiều đó. Tuỳ nhu cầu project và trình độ của bạn sẽ có những cách khác nhau xử lý nha.

Cách sau có thể không đáp ứng yêu cầu bảo mật nhưng mình thường thấy các sinh viên sử dụng trong dự án winform và sql vì nó tương đối đơn giản nha:

  1. Sau khi người dùng nhập tài khoản và mật khẩu sẽ có một query tới server database để kiểm tra nếu thành công thì lấy ra được mã định danh (identity) và các thông tin cần thiết (tên, role, ...) của user và lưu nó vào đâu đó của chương trình, có thể tạo ra một class để chứa những thông tin này và tạo ra một đối tượng trong form.
  2. Khi có yêu cầu thay đổi database thì có thể sử dụng đối tượng đó kết hợp với việc truy vấn để kiểm tra các logic rồi thực hiện thay đổi.
  3. Các ứng dụng thường không giống như game, đối với game thì dữ liệu sẽ liên tục được trao đổi giữa server và client và bất cứ bên nào gửi yêu cầu thì bên còn lại sẽ nhận được, còn các ứng dụng thường client thường chỉ cần các dữ liệu cần thiết cho một yêu cầu rồi phàn hồi lại là được

Một ví dụ đơn giản với một cơ sở dữ liệu có bản Users như sau

UserID: int (primary key, identity)
Username: nvarchar(50)
Password: nvarchar(50)

Lớp lưu thông tin

public class User
{
    public int Id { get; set; }
    public string Username { get; set; }
}

Code behind form

private User currentUser;

private void btnLogin_Click(object sender, EventArgs e)
{
    string connectionString = "Data Source=localhost;Initial Catalog=YourDatabase;Integrated Security=True";
    string query = "SELECT * FROM Users WHERE Username = @username AND Password = @password";
    using (SqlConnection connection = new SqlConnection(connectionString))
    using (SqlCommand command = new SqlCommand(query, connection))
    {
        command.Parameters.AddWithValue("@username", txtUsername.Text);
        command.Parameters.AddWithValue("@password", txtPassword.Text);
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        if (reader.Read())
        {
            currentUser = new User
            {
                Id = (int)reader["UserId"],
                Username = (string)reader["Username"]
            };
            MessageBox.Show("Đăng nhập thành công!");
        }
        else
        {
            MessageBox.Show("Tên đăng nhập hoặc mật khẩu không đúng!");
        }
    }
}
private void btnChangePassword_Click(object sender, EventArgs e)
{
    if (currentUser != null)
    {
        string connectionString = "Data Source=localhost;Initial Catalog=YourDatabase;Integrated Security=True";
        string query = "UPDATE Users SET Password = @newPassword WHERE UserId = @userId AND Password = @oldPassword";
        using (SqlConnection connection = new SqlConnection(connectionString))
        using (SqlCommand command = new SqlCommand(query, connection))
        {
            string oldPassword = ShowOldPasswordDialog();
            string newPassword = ShowNewPasswordDialog();
            if (oldPassword != null && newPassword != null)
            {
                command.Parameters.AddWithValue("@userId", currentUser.Id);
                command.Parameters.AddWithValue("@oldPassword", oldPassword);
                command.Parameters.AddWithValue("@newPassword", newPassword);
                connection.Open();
                int rowsAffected = command.ExecuteNonQuery();
                if (rowsAffected > 0)
                {
                    MessageBox.Show("Đổi mật khẩu thành công!");
                }
                else
                {
                    MessageBox.Show("Mật khẩu cũ không đúng hoặc đổi mật khẩu thất bại!");
                }
            }
        }
    }
}
private string ShowOldPasswordDialog()
{
    using (PasswordDialog dialog = new PasswordDialog("Nhập mật khẩu cũ"))
    {
        if (dialog.ShowDialog() == DialogResult.OK)
        {
            return dialog.Password;
        }
        else
        {
            return null;
        }
    }
}

private string ShowNewPasswordDialog()
{
    using (PasswordDialog dialog = new PasswordDialog("Nhập mật khẩu mới"))
    {
        if (dialog.ShowDialog() == DialogResult.OK)
        {
            return dialog.Password;
        }
        else
        {
            return null;
        }
    }
}
public partial class PasswordDialog : Form
{
    public string Password { get; private set; }

    public PasswordDialog(string title)
    {
        InitializeComponent();
        this.Text = title;
        this.Password = null;
    }

    private void btnOK_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(txtPassword.Text))
        {
            MessageBox.Show("Vui lòng nhập mật khẩu.");
        }
        else
        {
            this.Password = txtPassword.Text;
            this.DialogResult = DialogResult.OK;
            this.Close();
        }
    }
}

Trên chỉ là một ví dụ mình đã lượt bỏ khá nhiều nên chưa thể ứng dụng được, làm những cái này thường sẽ khá là mất thời gian đó nên bạn chịu khó bỏ thời gian và xử lý nha.

Câu hỏi mới nhất