Riferimento rapido

Cheat Sheet autenticazione con Devise per Ruby on Rails

Guida rapida a Devise in Ruby on Rails: generatori, moduli di modello, helper dei controller, viste e routing protetto.

· Pubblicato

Devise è una soluzione di autenticazione modulare e flessibile per Ruby on Rails basata su Warden.

Installazione e generatori (Installation & Generators)

# Add gem to Gemfile and bundle
bundle add devise

# Install Devise configuration initializer
rails generate devise:install

# Generate Devise model (e.g. User or Admin)
rails generate devise User
rails db:migrate

# Generate editable views
rails generate devise:views

Helper per controller e viste (Controller & View Helpers)

# Protect controller actions with before_action
before_action :authenticate_user!

# Status checks
user_signed_in?
current_user
user_session

# URL and Path Helpers
new_user_session_path           # Login form
destroy_user_session_path       # Logout (DELETE)
new_user_registration_path      # Sign up form
edit_user_registration_path     # Edit account settings
new_user_password_path          # Password reset request

Moduli del modello (Model Modules)

class User < ApplicationRecord
  devise :database_authenticatable, # Hashes and stores passwords in DB
         :registerable,           # Sign up, edit, and destroy accounts
         :recoverable,            # Resets password and sends reset instructions
         :rememberable,           # Manages cookies to remember user sessions
         :trackable,              # Tracks sign in count, timestamps, and IP addresses
         :validatable,            # Validates email and password length/presence
         :confirmable,            # Sends verification emails with tokens
         :lockable,               # Locks accounts after failed login attempts
         :timeoutable             # Expires inactive sessions after set duration
end

Routing condizionale (Scoped Routing)

Rails.application.routes.draw do
  devise_for :users

  # Custom route scopes based on authentication status
  authenticated :user do
    root to: 'dashboard#index', as: :authenticated_root
  end

  unauthenticated do
    root to: 'home#index'
  end
end

Cheat Sheet correlati

Argomenti correlati