giza: Giza White Mage (Default)
[personal profile] giza
Awhile back, I was working on a private Drupal website for members only. Now, Drupal has a module called Secure Site which can be used for this. However, Secure Site throws up an HTTP 401 error to request authentication from the user. If you've ever seen a "enter username and password" box pop up in your browser, that's an HTTP 401 error. That's okay, but I don't think it's the best UI out there. I wanted something a little user-friendlier.

So, I came up with the code below. Put it in your index.php file (or better yet, in a file included by index.php) right after the call to drupal_bootstrap(). It will redirect all but a certain subset of pages to the login page, and prompt users to log in.

$path = getenv("SCRIPT_URL");

//
// If a user is not logged in, they can only access certain unrestricted pages.
//
if ($user->uid == 0) {
   if (
      // 
      // strstr() is called for efficiency.  Keep in mind that ANY path that matches
      // these strings will be allowed to anonymous users.  So if you have something
      // like "/userlist", an anonymous user can view that.  I warned ya!
      // 
      !strstr($path, "user")
      && !strstr($path, "how-to-join")
      && !strstr($path, "contact")
      ) {
         form_set_error("", "You must be logged in first.");
         drupal_goto("user");
      }

}


Enjoy!

[Edit: Added blurb about security. Thanks for pointing that out [livejournal.com profile] taral.]

Profile

giza: Giza White Mage (Default)
Douglas Muth

April 2012

S M T W T F S
1234567
891011121314
15161718192021
22232425262728
2930     

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags