Today we covered sessions, authentication, and authorization. We also touched briefly on associations again, since they seem to be the trickiest to execute properly. The examples we used to go over each module were part of our assignment for the amazon clone. So it’s code we’ve already done, but not actually understood.
Sessions are straight forward: When you’re logged into a site using your credentials, you’re starting a session. Logging out destroys that session. It gets complicated when you’re writing the actual code to make this work, but luckily on Rails the code isn’t that hard. E.g.:
def create user = User.find_by_email(params[:email]) if user && user.authenticate(params[:password]) session[:user_id] = user.id redirect_to products_path, :notice => "Logged in!" else flash.now[:alert] = "Invalid email or password" render 'new' end end
This basically says when a user is logging in, check the database and make sure the email exists, then make sure the password entered is correct. If both criteria are met, then assign the user a session number and redirect them to the home page. If one of the criteria is not met, then give a warning and stay on the same page.
Authentication is making sure users are who they say they are. To authenticate an account, you make the user log in into their account, or make a new one. That’s not entirely correct, as a proper authentication would make you confirm a link in your email or something, but for our simple application, that’s all we’re doing.
Authorization as you might have guessed, is simply making sure a user is authorized to perform an action. So in this example, before a user is able to post, edit, etc a review, they must be authenticated and logged in, which is our only authorization requirement right now.
before_filter :ensure_logged_in, :only=>[:edit, :create, :show, :update, :destroy]
That’s pretty much it for today. Going to redo the assignment and hope to learn more by doing it more.