Rails 8的Authentication模块

如果你像我一样刚开始学习Rails,则建议直接开始使用Rails 8.0.0.beta版本,因为该版本更新优化了很多功能,最重要的是加入了身份验证模块抽象层,不用像7之前的版本那样麻烦。
在这里记录下我的相关笔记

  • 一键生成身份验证系统: bin/rails generate authentication
    该命令会创建User、Current、Session三个模型,并且会在app/controllers/conerns下添加Authentication模块

  • 只有认证模块,没有注册模块

  • 默认使用邮箱和密码进行认证

  • Authentication模块的方法,建议直接打开该模块文件,就55行代码,非常的简洁明了

  • 查看三个模型对应的的controller文件,也非常简洁明了。。。

  • 认证流程(via):

    1858501620801126776-Gcq5LQfXcAA-_U3.jpg

  • 重置密码流程(via):

    1857239379875606782-GcY9JH3akAA1Lm6.png

  • 添加注册流程

    1. 创建Users Controller: bin/rails g controller Users

      # File: app/controllers/users_controller.rb
      class UsersController < ApplicationController
      allow_unauthenticated_access only: %i[ new create ]
      def new
      end
      
      def create
      @user = User.new(user_params)
      if @user.save
        redirect_to root_path, notice: "User was successfully created."
      else
        render :new
      end
      end
      
      private
      def user_params
      params.require(:user).permit(:email_address, :password, :password_confirmation)
      end
      end
    2. 创建view文件

      <pre><code>#File: app/views/users/new.html.erb &lt;%= tag.div(flash[:alert], style: &#34;color:red&#34;) if flash[:alert] %&gt; &lt;%= tag.div(flash[:notice], style: &#34;color:green&#34;) if flash[:notice] %&gt; <strong>Sign Up</strong> &lt;%= form_with(model:User) do |form| %&gt; &lt;%= form.email_field :email_address, required: true, autofocus: true, autocomplete: &#34;username&#34;, placeholder: &#34;Enter your email address&#34;, value: params[:email_address] %&gt; &lt;%= form.password_field :password, required: true, placeholder: &#34;Enter your password&#34;, maxlength: 72 %&gt; &lt;%= form.password_field :password_confirmation, required: true, placeholder: &#34;Confirm your password&#34;, maxlength: 72 %&gt; &lt;%= form.submit &#34;Sign up&#34; %&gt; &lt;% end %&gt;</code></pre>

    3. 添加route

      #File: config/routes.rb
      resources :users