Szybka pomoc

Ściągawka z uwierzytelniania Devise dla Ruby on Rails

Skrócony przewodnik po Devise w Ruby on Rails: generatory, moduły modeli, pomocniki kontrolerów, widoki i routing.

· Opublikowano

Devise to elastyczne, modułowe rozwiązanie uwierzytelniania dla Ruby on Rails oparte na silniku Warden.

Instalacja i generatory (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

Pomocniki kontrolera i widoku (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

Moduły modelu (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 warunkowy (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

Powiązane ściągawki

Powiązane tematy