Home > front end >  After querying an SQL database, and finding invalid login details, how can I display an error messag
After querying an SQL database, and finding invalid login details, how can I display an error messag

Time:02-05

I am developing a login system using ASP.NET 7.0. I have created the login and signup system, by connecting to an SQL database and inserting or querying it for information. Currently, the backend code is able to create accounts, and check to make sure that while making an account, that their is no user with matching email or username. I would like to be able to display some sort of message saying "An account with those details has already been created, Login?". How would I go about this?

Here is my current code:

public void OnPostSignup()
{

    System.Diagnostics.Debug.WriteLine("Post Request Received");


    // Creating Credentials //

    string InputUser = Request.Form["signup-user"];
    string InputPassword = Request.Form["signup-pwd"];
    string InputEmail = Request.Form["signup-email"];

    // Creates a new SQL Connection using the connection string provided - Then runs an SQL Command: NOTHING HAS BEEN RUN YET, ONLY INSTANCIATED //


    using (SqlConnection conn = new SqlConnection("Valid Server String Here"))
    using (SqlCommand cmd = new SqlCommand("INSERT INTO AccountData ([User], [Password], [Email]) VALUES (@1, @2, @3);", conn))
    {

        // The Placeholder Values are replaced with the string variables created above containing our account registration data //
        cmd.Parameters.AddWithValue("@1", InputUser);
        cmd.Parameters.AddWithValue("@2", InputPassword);
        cmd.Parameters.AddWithValue("@3", InputEmail);

        // Instanciates a new SQL Command that will cehck the database to ensure an account with that infomation hasnt been created already //
        using (SqlCommand UserCheck = new SqlCommand("SELECT * FROM AccountData WHERE [User] = @1 AND [Email] = @2", conn))
        {
            // Adds the inputted data into the UserCheck SQL Command //
            UserCheck.Parameters.AddWithValue("@1", InputUser);
            UserCheck.Parameters.AddWithValue("@2", InputEmail);

            // A connection to our SQL Databasse is opened //
            conn.Open();

            // Executes a data reader on our SQL Server
            SqlDataReader reader= UserCheck.ExecuteReader();
            
            // This logic gate checks if the reader returns any rows with the given infomation - if yes, no account is created, and the connection is closed - if no, the account creation is started //
            if(reader.HasRows)
            {
                // We already have an account with the same email or username //
                reader.Close();
                conn.Close();

                // Display some sort of message to the user saying that their email or username is already in use. // 

                

            }
            else
            {
                // We do not have an account with that information - An account can now be created //

                

                // Closes the reader, because we cannot query our SQL databse twice at the same time //
                reader.Close();

                // Executes the 'cmd' SQL command against our SQL Databse //
                cmd.ExecuteNonQuery();

                // Closes the connection to our SQL Databse for security - and cost //
                conn.Close();
            }
        }

    }

    
}

// This will run when the user clicks the "Login button, after filling out all the required fourm felids //
public void OnPostLogin()
{

    // Takes the data inputted by the user, and stores them as variables to be ran against the SQL Database //
    string LoginUser = Request.Form["login-user"];
    string LoginPass = Request.Form["login-passwrd"];

    // Defines an SQL Connection with our SQL Connection String //
    using (SqlConnection conn = new SqlConnection("Valid Connection String Here"))

    // Creates a new SQL command that checks the database for a account; notice that '@1' amd '@2' are placeholders //
    using (SqlCommand cmd = new SqlCommand("SELECT * FROM AccountData WHERE [User] = @1 AND [Password] = @2", conn))
    {
        // Replaces the placeholder values in the SQL command with our varaibles that were created from the users input
        cmd.Parameters.AddWithValue("@1", LoginUser);
        cmd.Parameters.AddWithValue("@2", LoginPass);

        // A connection is opened to our SQL Database //
        conn.Open();

        // Executes the SQL Database reader with the paramaters defined in our SQL Command 'cmd' //
        SqlDataReader reader = cmd.ExecuteReader();

        // Checks if the SQL reader returned any rows //
        if (reader.HasRows)
        {
            // User Exists //
            reader.Close();
            System.Diagnostics.Debug.WriteLine("We have found an account");

            // Log in the user //
            
        }
        else
        {
            // User Doesnt Exist //
            reader.Close();
            System.Diagnostics.Debug.WriteLine("No Account Found");

        }

        // Closes the connection to our SQL Database //
        conn.Close();
    }
}

I am aware that the code may be vunrable to SQL injection attacks! the website has not been published yet, and security will be added before launch.

I appreciate any help that I receive, if there is anything that doesn't make sense, please let me know!

CodePudding user response:

Thanks for the help everybody! However, i have found a solution to the problem. Inside of the if statement where login details are verified, i added this onto the 'invalid login' return.

ModelState.AddModelError("InvalidLogin", "Invalid login details");

And then, directly below my login form i added the following code

@if (Model.ModelState.ContainsKey("InvalidLogin"))
            {
                <div >@Model.ModelState["InvalidLogin"].Errors[0].ErrorMessage</div>
                System.Diagnostics.Debug.WriteLine("Error message displayed in view");
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("No error message to display in view");
            }

If you are viewing this post late, looking for an answer, this worked well for me. If you would like help setting this up for your code feel free to @ me

  • Related