Rodauth를 사용하여 Rails 6에 인증 추가
Basic POST CRUD 및 Bootstrap가 설치된 새로운 Rails 애플리케이션을 사용할 예정입니다.
$ git clone https://gitlab.com/janko-m/rails_bootstrap_starter.git rodauth_blog
$ cd rodauth_blog
$ bin/setup
Rodauth 설치
우선, 우리는 rodauth-railsgem를gem 파일에 추가할 것이다.
$ bundle add rodauth-rails
다음은 Rodauth rails에서 제공하는 rodauth:install
생성기를 실행합니다.$ rails generate rodauth:install
# create db/migrate/20200820215819_create_rodauth.rb
# create config/initializers/rodauth.rb
# create config/initializers/sequel.rb
# create app/lib/rodauth_app.rb
# create app/controllers/rodauth_controller.rb
# create app/models/account.rb
이것은 기본 인증 기능을 가진 Rodauth 프로그램을 만들고 데이터베이스 상호작용에 사용되는 RodauthSequel를 reuse Active Record's database connection로 설정하며 로드된 Rodauth 기능을 위한 테이블을 생성합니다.마이그레이션 실행:$ rails db:migrate
# == CreateRodauth: migrating ====================================
# -- create_table(:accounts)
# -- create_table(:account_password_hashes)
# -- create_table(:account_password_reset_keys)
# -- create_table(:account_verification_keys)
# -- create_table(:account_login_change_keys)
# -- create_table(:account_remember_keys)
# == CreateRodauth: migrated ===========================
만약 모든 것이 성공적으로 설치되었다면, 우리는 /create-account
페이지를 열고, 로다츠의 기본 등록표를 볼 수 있을 것이다.인증 링크 추가
Rodauth rails에서 생성한 Rodauth 구성은 인증 및 계정 관리에 다음과 같은 몇 가지 방법을 제공합니다.
$ rails rodauth:routes
# /login rodauth.login_path
# /create-account rodauth.create_account_path
# /verify-account-resend rodauth.verify_account_resend_path
# /verify-account rodauth.verify_account_path
# /logout rodauth.logout_path
# /remember rodauth.remember_path
# /reset-password-request rodauth.reset_password_request_path
# /reset-password rodauth.reset_password_path
# /change-password rodauth.change_password_path
# /change-login rodauth.change_login_path
# /verify-login-change rodauth.verify_login_change_path
# /close-account rodauth.close_account_path
이 정보를 사용하여 탐색 제목에 주요 인증 링크를 추가합니다.<!-- app/views/application/_navbar.html.erb -->
<!-- ... --->
<% if rodauth.logged_in? %>
<div class="dropdown">
<%= link_to current_account.email, "#", class: "btn btn-info dropdown-toggle", data: { toggle: "dropdown" } %>
<div class="dropdown-menu dropdown-menu-right">
<%= link_to "Change password", rodauth.change_password_path, class: "dropdown-item" %>
<%= link_to "Change email", rodauth.change_login_path, class: "dropdown-item" %>
<div class="dropdown-divider"></div>
<%= link_to "Close account", rodauth.close_account_path, class: "dropdown-item text-danger" %>
<%= link_to "Sign out", rodauth.logout_path, method: :post, class: "dropdown-item" %>
</div>
</div>
<% else %>
<div>
<%= link_to "Sign in", rodauth.login_path, class: "btn btn-outline-primary" %>
<%= link_to "Sign up", rodauth.create_account_path, class: "btn btn-success" %>
</div>
<% end %>
<!-- ... --->
Rodauth에 정의#current_account
방법이 없으므로 Rodauth rails 읽어보기 파일의 예를 복사하여 붙여넣습니다.# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
before_action :current_account, if: -> { rodauth.logged_in? }
private
def current_account
@current_account ||= Account.find(rodauth.session_value)
rescue ActiveRecord::RecordNotFound
rodauth.logout
rodauth.login_required
end
helper_method :current_account
end
이제 사용자가 로그인하지 않은 경우 로그인 및 등록 링크가 표시됩니다.로그인하면 다음과 같은 기본 계정 관리 링크가 표시됩니다.
인증 필요
현재 우리는 이미 효과적인 신분 검증을 받았기 때문에 응용 프로그램의 일부 부분의 사용자에 대해 신분 검증을 해야 할 가능성이 높다.우리의 예에서, 우리는posts 컨트롤러를 검증하고 싶다.
컨트롤러에
before_action
리셋을 추가할 수 있지만, Rodauth는 Rodauth 프로그램의 루프 블록에서 이 동작을 실행하고, 각각의 Rails 루트가 있기 전에 루프 블록을 호출할 수 있도록 합니다.이렇게 하면 우리는 신분 검증 논리를 한 곳에 저장할 수 있다.# app/lib/rodauth_app.rb
class RodauthApp < Rodauth::Rails::App
# ...
route do |r|
# ...
if r.path.start_with?("/posts")
rodauth.require_authentication
end
end
end
이제 사용자가 로그인하지 않은 경우 액세스/posts
페이지에서 사용자를 /login
페이지로 리디렉션합니다.또한 이 게시물을
accounts
테이블에 연결하고자 합니다.$ rails generate migration add_account_id_to_posts account:references
$ rails db:migrate
# app/models/account.rb
class Account < ApplicationRecord
has_many :posts
# ...
end
posts controller의 당좌 계정으로 범위를 확장합니다.# app/controllers/posts_controller.rb
class PostsController < ApplicationController
# ...
def index
@posts = current_account.posts.all
end
# ...
def create
@post = current_account.posts.build(post_params)
# ...
end
# ...
private
def set_post
@post = current_account.posts.find(params[:id])
end
# ...
end
새 필드 추가
전자 우편 주소가 아닌 사용자를 표시하기 위해서, 가입할 때 사용자의 이름을 입력하도록 요구합니다.또한 Rodauth를 구성하는 방법에 대해서도 알아볼 수 있습니다.
레지스트리를 편집해야 하므로 먼저 Rodauth HTML 템플릿을 Rails 응용 프로그램에 복사합니다.
$ rails generate rodauth:views
# create app/views/rodauth/_field.html.erb
# create app/views/rodauth/_field_error.html.erb
# create app/views/rodauth/_login_field.html.erb
# create app/views/rodauth/_login_display.html.erb
# create app/views/rodauth/_password_field.html.erb
# create app/views/rodauth/_submit.html.erb
# create app/views/rodauth/_login_form.html.erb
# create app/views/rodauth/_login_form_footer.html.erb
# create app/views/rodauth/_login_form_header.html.erb
# create app/views/rodauth/login.html.erb
# create app/views/rodauth/multi_phase_login.html.erb
# create app/views/rodauth/logout.html.erb
# create app/views/rodauth/_login_confirm_field.html.erb
# create app/views/rodauth/_password_confirm_field.html.erb
# create app/views/rodauth/create_account.html.erb
# create app/views/rodauth/_login_hidden_field.html.erb
# create app/views/rodauth/verify_account_resend.html.erb
# create app/views/rodauth/verify_account.html.erb
# create app/views/rodauth/reset_password_request.html.erb
# create app/views/rodauth/reset_password.html.erb
# create app/views/rodauth/_new_password_field.html.erb
# create app/views/rodauth/change_password.html.erb
# create app/views/rodauth/change_login.html.erb
# create app/views/rodauth/close_account.html.erb
이제 템플릿create_account.erb
을 열고 새 필드name
를 추가할 수 있습니다.<!-- app/views/rodauth/create_account.erb -->
<%= form_tag rodauth.create_account_path, method: :post do %>
<!-- new "name" field -->
<div class="form-group">
<%= label_tag "name", "Name" %>
<%= render "field", name: "name", id: "name" %>
</div>
<%= render "login_field" %>
<%= render "login_confirm_field" if rodauth.require_login_confirmation? %>
<%= render "password_field" if rodauth.create_account_set_password? %>
<%= render "password_confirm_field" if rodauth.create_account_set_password? && rodauth.require_password_confirmation? %>
<%= render "submit", value: "Create Account" %>
<% end %>
사용자 이름은 인증에 사용되지 않기 때문에 새 profiles
테이블에 저장하고 profiles
테이블과 accounts
테이블을 연결합니다.$ rails generate model Profile account:references name:string
$ rails db:migrate
# app/models/account.rb
class Account < ApplicationRecord
has_one :profile
# ...
end
새로운 name
인자를 실제적으로 처리하기 위해서는 Rodauth 프로그램이 필요합니다.계정이 작성되었는지 확인하고 계정을 만든 후에 관련 프로필 기록을 만들 것입니다.# app/lib/rodauth_app.rb
class RodauthApp < Rodauth::Rails::App
configure do
# ...
before_create_account do
# Validate presence of the name field
throw_error_status(422, "name", "must be present") unless param_or_nil("name")
end
after_create_account do
# Create the associated profile record with name
Profile.create!(account_id: account_id, name: param("name"))
end
after_close_account do
# Delete the associated profile record
Profile.find_by!(account_id: account_id).destroy
end
# ...
end
end
이제 e-메일 주소가 아닌 사용자 이름을 사용하여 탐색 제목을 업데이트할 수 있습니다.- <%= link_to current_account.email, "#", class: "btn btn-info dropdown-toggle", data: { toggle: "dropdown" } %>
+ <%= link_to current_account.profile.name, "#", class: "btn btn-info dropdown-toggle", data: { toggle: "dropdown" } %>
비동기식으로 e-메일 보내기
Rodauth는 계정 확인, 이메일 변경, 암호 변경 및 암호 재설정의 일부로 이메일을 보냅니다.기본적으로 이 전자메일은 내부 메일 프로그램을 통해 동기화되지만, 성능 때문에 백엔드 작업에서 비동기적으로 보내야 합니다.
최종적으로 Rodauth의 기본 전자 메일 템플릿을 수정하고자 하므로 기본 템플릿을 사용하여 자체 메일 프로그램을 만듭니다.
$ rails generate rodauth:mailer
# create app/mailers/rodauth_mailer.rb
# create app/views/rodauth_mailer/email_auth.text.erb
# create app/views/rodauth_mailer/password_changed.text.erb
# create app/views/rodauth_mailer/reset_password.text.erb
# create app/views/rodauth_mailer/unlock_account.text.erb
# create app/views/rodauth_mailer/verify_account.text.erb
# create app/views/rodauth_mailer/verify_login_change.text.erb
class RodauthMailer < ApplicationMailer
def verify_account(recipient, email_link)
# ...
end
def reset_password(recipient, email_link)
# ...
end
def verify_login_change(recipient, old_login, new_login, email_link)
# ...
end
def password_changed(recipient)
# ...
end
end
이제 Rodauth에서 메일 프로그램을 자동으로 호출하고 백그라운드에서 이메일을 보내기 위해 Rodauth 응용 프로그램에서 다음 행에 대한 설명을 취소합니다.# app/lib/rodauth_app.rb
class RodauthApp < Rodauth::Rails::App
configure do
# ...
send_reset_password_email do
mailer_send(:reset_password, email_to, reset_password_email_link)
end
send_verify_account_email do
mailer_send(:verify_account, email_to, verify_account_email_link)
end
send_verify_login_change_email do |login|
mailer_send(:verify_login_change, login, verify_login_change_old_login, verify_login_change_new_login, verify_login_change_email_link)
end
send_password_changed_email do
mailer_send(:password_changed, email_to)
end
auth_class_eval do
def mailer_send(type, *args)
db.after_commit do
RodauthMailer.public_send(type, *args).deliver_later
end
end
end
# ...
end
end
백그라운드 작업이 추출될 때 Rodauth가 메일 프로그램으로 호출되기 전에 데이터베이스 변경 사항이 적용되었는지 확인하기 위해 데이터베이스 업무를 제출한 후 전자 우편을 줄을 서서 보냅니다.끝말
본 강좌에서 우리는 Rodauth 인증 프레임워크를 이용하여 완전한 인증과 계정 관리 절차를 점차적으로 구축했다.로그인 및 로그아웃, 이메일 확인 및 유예 기간 계정 생성, 암호 변경 및 재설정, 이메일 확인을 통한 이메일 변경 및 계정 닫기 기능을 지원합니다.우리는 어떤 루트에 대한 인증을 요구하고, 등록표에 새로운 필드를 추가하며, 인증 전자메일을 비동기적으로 보내는 방법을 알고 있다.
개인적으로 Rodauth는 인상적인 기능집과 새롭고 깨끗한 디자인을 가지고 있으며 궤도와 연결되지 않기 때문에 매우 흥분된다.나는 Rails가 가능한 한 쉽게 입문할 수 있도록 노력하고 있기 때문에 Rodauth가 Rails 커뮤니티에서 더 많은 흡인력을 얻을 수 있도록 도와주기를 바란다.
Reference
이 문제에 관하여(Rodauth를 사용하여 Rails 6에 인증 추가), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/janko/adding-authentication-in-rails-6-with-rodauth-66b텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)