Create a Sinatra Authentication Account, Page 2
Creating an Account
Be sure to test out the routes by navigating to
/signup and creating a new account. You'll see sinatra-authentication's default registration view (presented in Figure 1).
Figure 1. The Default Registration Form
After creating an account, be sure to check out the
dm_users table, where you'll see that a new row has been created such as the following:
mysql> select * from dm_users\G *************************** 1. row *************************** id: 1 email: firstname.lastname@example.org hashed_password: c709816a0d6ebc500206d5d4a3495e9743cfd030 salt: 1gf8Md1Q7l created_at: 2011-10-18 16:22:03 permission_level: 1 1 row in set (0.00 sec)
Adding a Flash Message
If you started the Sinatra application from scratch, then you received an error message after pressing the registration button, despite having confirmed that the new user information was added to the
dm_user table. This is because sinatra-authentication will redirect the user to the application's home page, which doesn't yet exist. Open
app.rb and add the following route:
get '/' do haml :home end
Next, create a file named
home.haml, placing it in the
views directory and adding the following contents:
%h1 Welcome to the Stamp Club website = flash[:notice]
Once added, try logging out of your new account (navigate to
/logout). After being successfully logged out of your account, sinatra-authentication will redirect to you the home page where you'll be greeted with a flash message stating
Accessing User Data
Chances are you'll want to know whether a user is logged in so as to provide custom content. sinatra-authentication makes several global variables available which you can use for this purpose. For instance, add the following snippet to your
layout.haml file will produce a tailored message based upon whether the user is currently logged in:
- if logged_in? = "Welcome back, " + current_user.email - else <a href="/login">Login</a> | <a href="/register">Register</a>
Where to From Here?
The sinatra-authentication extension packs a pretty powerful punch while requiring minimal effort on the part of the developer. In fact, for rudimentary purposes you could conceivably use the extension without even needing to tweak its default behavior. However, chances are you'll want to modify the default views, as well as extend the default users table. For more information about such possibilities, check out the sinatra-authentication home page.
About the Author
Jason Gilmore is founder of the publishing, training, and consulting firm WJGilmore.com. He is the author of several popular books, including "Easy PHP Websites with the Zend Framework", "Easy PayPal with PHP", and "Beginning PHP and MySQL, Fourth Edition". Follow him on Twitter at @wjgilmore.