Snelle referentie

Devise authenticatie spiekbriefje voor Ruby on Rails

Snelle naslaggids voor Devise in Ruby on Rails: generators, modelmodules, controller-helpers, view-aanpassingen en routes.

· Gepubliceerd

Devise is een flexibele, modulaire authenticatie-oplossing voor Ruby on Rails gebaseerd op Warden.

Installatie en generators (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

Controller- en 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

Modelmodules (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

Bereikafhankelijke routering (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

Gerelateerde spiekbriefjes

Verwante onderwerpen