0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rails6にnamespaseを使ってdeviseを導入

Posted at

AdminLTE3のテンプレートにdeviseを使って、ログイン認証をインストールする。
roleなどの設定は、別記事にて

deviseの初期設定

gemのインストール

Gemfile
gem 'devise'
.sh
$ bundle install --path vendor/bundle

deviseの設定

今回は/admin配下に、deviseをインストール

.sh
rails g devise manage_user
rails g devise:views admin/manage_users
rails g devise:controllers admin/manage_user

コメントアウトを解除

必要な機能をコメントアウトします。

devise_create_manage_users.rb
# frozen_string_literal: true

class DeviseCreateManageUsers < ActiveRecord::Migration[6.0]
  def change
    create_table :manage_users do |t|
      ## Database authenticatable
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""

      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      t.integer  :sign_in_count, default: 0, null: false
      t.datetime :current_sign_in_at
      t.datetime :last_sign_in_at
      t.string   :current_sign_in_ip
      t.string   :last_sign_in_ip

      ## Confirmable
      t.string   :confirmation_token
      t.datetime :confirmed_at
      t.datetime :confirmation_sent_at
      t.string   :unconfirmed_email # Only if using reconfirmable

      ## Lockable
      t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
      t.string   :unlock_token # Only if unlock strategy is :email or :both
      t.datetime :locked_at


      t.timestamps null: false
    end

    add_index :manage_users, :email,                unique: true
    add_index :manage_users, :reset_password_token, unique: true
    add_index :manage_users, :confirmation_token,   unique: true
    add_index :manage_users, :unlock_token,         unique: true
  end
end

modelも同様にコメントアウト

ManageUser.rb
class ManageUser < ApplicationRecord
  # Include default devise modules. Others available are:
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable,
         :confirmable, :lockable, :timeoutable, :trackable
end

routesを設定

routesにrootを追記し、devise_forの設定を書く
これで、 /admin/manage_users/sign_up でアクセスできるようになる

/config/routes.rb
Rails.application.routes.draw do
  root to: "home#index"
   :
   :
  scope :admin, module: :admin do
    devise_for :manage_users, controllers: {
        sessions: 'admin/manage_users/sessions',
        passwords: 'admin/manage_users/passwords',
        registrations: 'admin/manage_users/registrations',
        confirmations: 'admin/manage_users/confirmations',
        unlocks: 'admin/manage_users/unlocks'
    }
   :
   :
  end
end

その他設定の修正

development.rbに以下を追加

/config/environments/development.rb
config.action_mailer.default_url_options = { host: '127.0.0.1', port: 5000 }

認証を親クラスに追記

/admin/ApapplicationController.rb
class Admin::ApapplicationController < ActionController::Base
  :
  :
  before_action :authenticate_manage_user! # 追記
end

maigrationを実行

.sh
$ rails db:migrate

AdminLTE3に組む混む

今回はregistration画面のみ組み込む
以下URLをコピーして、layoutを作成する
/node_modules/admin-lte/pages/examples/register.html

/layouts/admin/registration.html.haml
!!!
%html
  %head
    %meta{:content => "text/html; charset=UTF-8", "http-equiv" => "Content-Type"}/
    %meta{:charset => "utf-8"}/
    %meta{:content => "IE=edge", "http-equiv" => "X-UA-Compatible"}/
    %title MyAdmin 3 | Registration Page
    / Tell the browser to be responsive to screen width
    %meta{:content => "width=device-width, initial-scale=1", :name => "viewport"}/
    = csrf_meta_tags
    = csp_meta_tag
    = stylesheet_link_tag 'admin', media: 'all', 'data-turbolinks-track': 'reload'
    = javascript_pack_tag 'admin', 'data-turbolinks-track': 'reload'

  %body.hold-transition.register-page
    .register-box
      .register-logo
        %a{:href => "../../index2.html"}
          %b> Admin
          LTE
      .card
        = yield
    / /.register-box

/node_modules/admin-lte/pages/examples/register.html
viewファイルを書き換える

/views/admin/manage_users/registrations/new.html.haml
.card-body.register-card-body
  %p.login-box-msg Register a new membership
  = form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f|
    = render "devise/shared/error_messages", resource: resource
    .input-group.mb-3
      = f.email_field :email, class: "form-control", autofocus: true, autocomplete: "email", placeholder: "Email"
      .input-group-append
        .input-group-text
          %span.fas.fa-envelope
    .input-group.mb-3

      = f.password_field :password, class: "form-control", autocomplete: "new-password", placeholder: "Password"
      .input-group-append
        .input-group-text
          %span.fas.fa-lock
    .input-group.mb-3
      = f.password_field :password_confirmation, class: "form-control", autocomplete: "new-password", placeholder: "Retype password"
      .input-group-append
        .input-group-text
          %span.fas.fa-lock
    .row
      .col-8
        .icheck-primary
          %input#agreeTerms{:name => "terms", :type => "checkbox", :value => "agree"}/
          %label{:for => "agreeTerms"}
            I agree to the
            %a{:href => "#"} terms
      .col-4
        = f.submit "Sign up", class: "btn btn-primary btn-block", type: "submit"
  .social-auth-links.text-center
    %p - OR -
    %a.btn.btn-block.btn-primary{:href => "#"}
      %i.fab.fa-facebook.mr-2
      Sign up using Facebook
    %a.btn.btn-block.btn-danger{:href => "#"}
      %i.fab.fa-google-plus.mr-2
      Sign up using Google+
  = render "admin/manage_users/shared/links"

確かめる

http://127.0.0.1:5000/admin/manage_users/sign_up
image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?