Adding user authentication - Ramaze/ramaze GitHub Wiki

There is a handy helper for this. Basically, all you have to do is to add an authenticate class method to your user model.

The whole thing is explained in details in the Ramaze::User::Helper documentation.

As an example, here is a complete, self contained Hello World ! style application with authentication :

require 'ramaze'

# The authentication helper, by default, uses a class named User to 
# handle authentication. This class is usually provided by your ORM.
# This class must provide an "authenticate" class method that returns
# true/false when called with login credentials 
class User
  def self.authenticate(credentials)
    credentials if credentials['name'] == 'manveru' && credentials['pass'] == 'sensei'
  end
end
    
# Our controller must use the :user helper
class Main < Ramaze::Controller
  map '/'
  helper :user
    
  def index
    # logged_in? is provided by the user helper
    # If the user is not logged in, we send him to the login page
    redirect Users.r(:login) unless logged_in?
    # Else, we just greet him
    'Hi #{user["name"]} #{Users.a :logout}'
  end
end

# The users controller handles login/logout for users
# While it's called Users, it just could be called FooBar too, it
# doesn't really matter
class Users < Ramaze::Controller
  map '/user'
  helper :user
   
  # We display a login form, or try to login the user
  # depending on the HTTP request used
  def login
    if request.post?
      # Form has been posted, let's try to authenticate the user
      # with the supplied credentials
      user_login(request.subset(:name, :pass))
      redirect Main.r(:index)
    else
      # This was probably a get, let's send back the login form
      <<-FORM
<form method="post">
  <input type="text" name="name">
  <input type="password" name="pass">
  <input type="submit">
</form>
      FORM
    end
  end
   
  # logout will call user_logout, provided by the user helper
  def logout
    user_logout
    redirect r(:login)
  end
end
    
Ramaze.start
⚠️ **GitHub.com Fallback** ⚠️