In this eleventh part of a series on the Action Pack library for Rails, you'll learn another way to assign local variables inside a partial template, and how to control the logging in and out of users. This article is excerpted from chapter six of the book Beginning Rails: From Novice to Professional, written by Jeffery Allan Hardy, Cloves Carneiro Jr. and Hampton Catlin (Apress; ISBN: 1590596862).
More on Action Pack Partial Templates - Adding the Login and Logout Actions (Page 2 of 2 )
Our users controller needs to serve another important function: controlling the logging in and out of users. To accomplish this, we’ll create two new actions: login and logout . The login action has an associated view template; the logout action does not. Listing 6-12 shows the new actions.
Listing 6-12. Login and Logout Actions Added to app/controllers/users_controller.rb
def login if request.post?
if user = User.authenticate(params[:login], params[:password] ) session[:user_id] = user.id redirect_to events_url
else flash[:notice] = 'Invalid login/password combination' end end end
We’ll take a closer look at the login and logout actions soon, but before we go any further, we need to take a minute to talk about sessions.
Lying in State
Here’s the thing: HTTP is stateless. In short, that means that each and every request you make across the HTTP protocol is autonomous. The web server has no idea that it has talked to your browser before; each request is like a blind date. Given this tidbit of infor mation, you might be wondering how you can stay logged in to a given site. How can the application remember that you’re logged in if HTTP is stateless? The answer is that we fake state.
Rails ships with a few different session storage mechanisms. You can choose to store session data directly on the application server via the file system (the current default), directly in the browser cookies (there is some controversy regarding the security of this approach), or in the database. We like the database approach the best, because it fits well with Rails’ architectural principles.
DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.