Index: bakery.module
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/bakery/bakery.module,v
retrieving revision 1.52.2.2
diff -u -p -r1.52.2.2 bakery.module
--- bakery.module	15 Sep 2010 22:49:41 -0000	1.52.2.2
+++ bakery.module	22 Sep 2010 22:08:49 -0000
@@ -490,7 +490,22 @@ function _bakery_taste_oatmeal_cookie()

   if ($cookie) {
     _bakery_eat_cookie('OATMEAL');
-    drupal_goto($cookie['destination']);
+
+    // Redirect back to subsite. We cannot use drupal_goto() here.
+    // We only redirect if the subsite is listed as a slave site on the master.
+    $destination_array = parse_url($cookie['destination']);
+    $destination = $destination_array['scheme'] . '://' . $destination_array['host'] . '/';
+
+    if (in_array($destination, variable_get('bakery_slaves', array()))) {
+      if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
+         module_invoke_all('exit', $url);
+      }
+
+      session_write_close();
+      header('Location: ' . $cookie['destination'], TRUE, 302);
+      exit();
+    }
+    else {
+      // The user has successfully logged in, but the slave is not recognised.
+      // Instead of redirecting the user back to the slave, we redirect to their master user profile as per core login behaviour.
+      watchdog('bakery', 'User logged in via unknown bakery slave: %slave', array('%slave' => $destination));
+      drupal_goto('user');
+    }
   }
 }
