Rails Details for Authentication
References
Intro
- There are several popular gems to implement authentication
- Beware that the fact that there is a gem does not mean that it’s trivial
- You need to understand what’s going on.
- Advice: Avoid getting fancy with OAuth, or FB or LinkedIn log in.
- Start with a simple password
has_secure_password
- Line added to top of the model representing what is logging in
- Might be Users, or Accounts, or whatever. The thing that logs in.
- Makes base assumptions about that model
- Database contains a field called password_digest (and does NOT contain a field called password)
- Implements various aspects of the authentication model
- Look at
- ./db/schema.rb
- ./app/models/user.rb
password_digest, password, password_confirmation
- Database only stores password_digest
- Model logic supplied by has_secure_password
- On create: compare password, password_confirmation are equal
- Computed a cryptographic hash (digest)
- And store as password_digest
User.create(email: "tim@brandeis.edu", password: "abc", password_confirmation: "abc")
User.where(email: "tim@brandeis.edu").first.authenticate("abc")
Log in/out
- Displaying the log in page: see ./app/views/sessions/new.html.erb
- Log in is a page like any other, needs a route
- Will assume existance of a SessionsController with create, new and destroy actions. Check rake routes to see what routes are created
1# ./config/routes.rb
2 resources :sessions, only: [:new, :create, :destroy]
sessions POST /sessions(.:format) sessions#create
new_session GET /sessions/new(.:format) sessions#new
session DELETE /sessions/:id(.:format) sessions#destroy
Sessions Controller
- Tricky: Session is not a model!
- Session controller maps a url (route) to some code
- Specifically code to execute when loging in and out
- session#new: display login box
- session#create: try validate password and save “logged in status”
- session#destroy: reset logged_in_status
- form_for is a view helper. Makes it easier to generate the required html for a form.
- Effect of the form is to do an HTTP PUT. This is what submit does
- URL for that form can come from the form_for method
ActiveRecord Triggers
- Methods that get called before, during or after key activerecord events.
1# ./app/models/user.rb
2 before_save { self.email = email.downcase }
3 before_create :create_remember_token
Helpers and Remember Token
- Think of these as “view helpers”, used in creating and working with views and controllers
- Remember Token Used in sessions so we don’t expose the actual ID of the user record
1# ./app/helpers/sessions_helper.rb
2 def sign_in(user)
3 remember_token = User.new_remember_token
4 cookies.permanent[:remember_token] = remember_token
5 user.update_attribute(:remember_token, User.hash(remember_token))
6 self.current_user = user
7 end