Adding basic authentication

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 initially, with devise, clearance, oauth, etc.
  • 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  get    '/signup', to: 'users#new'
3  get    '/login',   to: 'sessions#new'
4  post   '/login',   to: 'sessions#create'
5  delete '/logout',  to: '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
Sessions Helper
  • Where the core authorization logic is
  • Session[] is used to store the user_id of logged in user
  • Helper methods are used throughout
  • Take a look at view/users/index