Пример #1
0
 //Logical requirement for this to function as intended, is that the users email is unique
 //This method will only find users in a role.. the Add methods does not add role by default ... TODO:Fix
 public User Login(string username, string password)
 {
     //DbConnection is IDisposable
     using (var connection = new SqlConnection(CONNECTION_STRING))
     {
         connection.Open();
         using (var cmd = connection.CreateCommand())
         {
             string sql = "SELECT Users.Id as UserId,Email, Password, Salt, Roles.Id as RoleId," +
                          " Title FROM Users" +
                          " JOIN UserRoles ON Users.Id = UserRoles.UserId" +
                          " JOIN Roles ON UserRoles.RoleId = Roles.Id" +
                          " WHERE Email = @email";
             cmd.CommandText = sql;
             cmd.Parameters.AddWithValue("email", username);
             var reader = cmd.ExecuteReader();
             if (!reader.HasRows)
             {
                 if (InvalidLoginAttempt != null)
                 {
                     InvalidLoginAttempt("bla bla someone tried to log in with incorrect or not existing credentials, none found in DB");
                 }
                 return(null);
             }
             else
             {
                 if (LoginAttempt != null)
                 {
                     LoginAttempt(username + " log in credentials were found in the database");
                 }
                 reader.Read();//advance pointer 1 row, and get the user information from the first row
                 var foundUser = new User();
                 foundUser.Id       = reader.GetInt32(reader.GetOrdinal("UserId"));
                 foundUser.Email    = reader.GetString(reader.GetOrdinal("Email"));
                 foundUser.Password = reader.GetString(reader.GetOrdinal("Password"));
                 string currentSalt       = reader.GetString(reader.GetOrdinal("Salt"));//TODO: Salt and Salted hash not in the test database!
                 string currentSaltedHash = reader.GetString(reader.GetOrdinal("Password"));
                 if (!HashingManager.CheckPassword(password, currentSalt, currentSaltedHash))
                 {
                     throw new Exception("Incorrect Credentials!");
                 }
                 //TODO: Forgot the first role!!!!
                 while (reader.Read())//Continue advancing the pointer untill the end, and save the Role information
                 {
                     Role foundRole = new Role();
                     foundRole.Title = reader.GetString(reader.GetOrdinal("Title"));
                     foundRole.Id    = reader.GetInt32(reader.GetOrdinal("RoleId"));
                     foundUser.Roles.Add(foundRole);
                 }
                 return(foundUser);
             }
         }
     }
 }