ダン・クァン・ミン Blog

はじめまして

Building a RESTful API in a Rails Application

Auto setup

rails new PROJECT -m https://raw.github.com/RailsApps/rails-composer/master/composer.rb

PROJECT is name

Devise

Devise is a flexible authentication solution for Rails based on Warden. It:

  • Is Rack based;
  • Is a complete MVC solution based on Rails engines;
  • Allows you to have multiple models signed in at the same time;
  • Is based on a modularity concept: use only what you really need.

It’s composed of 10 modules:

  • Database Authenticatable encrypts and stores a password in the database to validate the authenticity of a user while signing in. The authentication can be done both through POST requests or HTTP Basic Authentication.
  • Omniauthable adds OmniAuth (https://github.com/intridea/omniauth) support.
  • Confirmable sends emails with confirmation instructions and verifies whether an account is already confirmed during sign in.
  • Recoverable resets the user password and sends reset instructions.
  • Registerable handles signing up users through a registration process, also allowing them to edit and destroy their account.
  • Rememberable manages generating and clearing a token for remembering the user from a saved cookie.
  • Trackable tracks sign in count, timestamps and IP address.
  • Timeoutable expires sessions that have not been active in a specified period of time.
  • Validatable provides validations of email and password. It’s optional and can be customized, so you’re able to define your own validations.
  • Lockable locks an account after a specified number of failed sign-in attempts. Can unlock via email or after a specified time period.
Getting started
gem 'devise'

rails generate devise:install

rails generate devise MODEL

Replace MODEL with the class name used for the application’s users (it’s frequently User but could also be Admin).

This will create a model (if one does not exist) and configure it with default Devise modules. The generator also configures your config/routes.rb file to point to the Devise controller.

Next, check the MODEL for any additional configuration options you might want to add, such as confirmable or lockable. If you add an option, be sure to inspect the migration file (created by the generator if your ORM supports them) and uncomment the appropriate section. For example, if you add the confirmable option in the model, you’ll need to uncomment the Confirmable section in the migration.

Then run:

rake db:migrate

Next, you need to set up the default URL options for the Devise mailer in each environment.

Here is a possible configuration for config/environments/development.rb:

config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

Comments