Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using Microsoft.AspNetCore.Authentication.Cookies;
- using Microsoft.AspNetCore.Authentication;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.AspNetCore.Mvc.RazorPages;
- using System.Data.SqlClient;
- using System.Security.Claims;
- namespace IKIMINA_CYACU.Pages.Users
- {
- public class LoginModel : PageModel
- {
- string conString = "Data Source=JN-JUSTE\\SQLEXPRESS;Initial Catalog=IKIMINACYACUProject;Integrated Security=True;Encrypt=False";
- public string message = "";
- public void OnGet()
- {
- }
- private bool AuthenticateUser(string username, string password, out string userRole)
- {
- userRole = null;
- try
- {
- using (SqlConnection con = new SqlConnection(conString))
- {
- string qry = "SELECT UserName, Role FROM USERS WHERE UserName = @username AND Password = @password";
- con.Open();
- using (SqlCommand cmd = new SqlCommand(qry, con))
- {
- cmd.Parameters.AddWithValue("@username", username);
- cmd.Parameters.AddWithValue("@password", password);
- using (SqlDataReader reader = cmd.ExecuteReader())
- {
- if (reader.Read())
- {
- userRole = reader.GetString(reader.GetOrdinal("Role"));
- return true; // Authentication successful
- }
- else
- {
- return false; // Authentication failed
- }
- }
- }
- }
- }
- catch (Exception)
- {
- throw;
- }
- }
- public IActionResult OnPost()
- {
- try
- {
- string enteredUsername = Request.Form["username"];
- string enteredPassword = Request.Form["password"];
- if (AuthenticateUser(enteredUsername, enteredPassword, out string userRole))
- {
- var claims = new List<Claim>
- {
- new Claim(ClaimTypes.Name, enteredUsername),
- new Claim(ClaimTypes.Role, userRole),
- };
- var userIdentity = new ClaimsIdentity(claims, "login");
- var userPrincipal = new ClaimsPrincipal(userIdentity);
- HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal);
- if (userRole.Equals("ADMIN", StringComparison.OrdinalIgnoreCase))
- {
- message = $"Welcome dear {userRole} {enteredUsername}!";
- return RedirectToPage("/Users/CreateUser");
- }
- else if (userRole.Equals("MEMBER", StringComparison.OrdinalIgnoreCase))
- {
- message = $"Welcome dear {userRole} {enteredUsername}!";
- return RedirectToPage("/Index");
- }
- else
- {
- message = "Invalid role for user";
- return Page();
- }
- }
- else
- {
- message = "Invalid username or password";
- return Page();
- }
- }
- catch (Exception ex)
- {
- message = "There's a problem: " + ex.Message;
- return Page();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement