Pages

Wednesday, March 17, 2010

Display login form for anymous users when 'access denied'

When a user requests a page he's not allowed to see, he gets an 'Access denied' page with the message 'You are not authorized to access this page. '.
Sometimes the user has access to the page but he hasn't logged in yet. So to make the user's life easier, you provide him with a login form on the 'access denied' page so he can login immediately and gets redirected to the page he requested originally.
How do you do this?
Start by creating a new Page (node of type Page). Set the input format for the body to 'PHP code'. Start typing the message you want to give to the user, something like 'This page is restricted to logged in users. Please provide your credentials below.'.
You then display the login form my typing the following code below your message (or anywhere you want to put the login form):
print drupal_get_form('user_login');
If you also want the 'Create new account' and 'Request new password' links under your form you can use the login block by typing the following code instead of the previous:

print drupal_get_form('user_login_block');
Yup, your page is done. But you won't be able to see it since you are logged in right now. So to test your page log out and go to your page. If you don't know the drupal path of your page, go to Administer > Content Management > Content to find it.
To finish setting up your page, you have to tell Drupal to use your new page as the 'Access denied' page. You can do this by going to Administer > Site configuration > Error reporting and providing the drupal path of your new page for the 403 page.

No comments:

Post a Comment