Rails基于JWT的验证登录

在app下创建unit目录:

新建token类:

class Token
  def self.encode(payload)
    payload.merge!(exp: (Time.now.to_i + 3600))
    JWT.encode(payload, Rails.application.secrets.secret_key_base)
  end

  def self.decode(token)
    return HashWithIndifferentAccess.new(JWT.decode(token, Rails.application.secrets.secret_key_base)[0])
  rescue
    nil
  end

end

在ApplicationController中:

class ApplicationController < ActionController::Base

  def authenticate!
    unless user_id_in_token?
      flash.now[:notice] = "请验证登录"
      redirect_to admin_logins_path and return
    end
    @current_user = Member.find(auth_token[:member_id])
  rescue JWT::VerificationError, JWT::DecodeError, JWT::ExpiredSignature
    flash.now[:notice] = "请重新登录"
    redirect_to admin_logins_path and return
  end

  private

  def http_token
    @http_token ||= if request.headers['Authorization'].present?
                      request.headers['Authorization']
                    end
  end

  def auth_token
    @auth_token ||= Token.decode(http_token)
  end

  #验证用户id和token
  def user_id_in_token?
    http_token && auth_token && auth_token[:member_id].to_i
  end

end

创建LoginController:

class Admin::LoginsController < ApplicationController
  layout "application"

  def index
  end

  def create
    @member = Member.find_by(email: params[:email])
    unless @member.present?
      flash.now[:notice] = "用户名不存在"
      render :index and return
    end
    unless @member.authenticate(params[:password])
      flash.now[:notice] = "密码错误"
      render :index and return
    end
    unless @member.role.present?
      flash.now[:notice] = "用户没有权限"
      render :index and return
    end
    render json: payload(@member)
  end

  def destroy
    flash[:notice] = "登录已退出"
    redirect_to admin_logins_path
  end
  
  private

  def payload(member)
    return nil unless member and member.id
    {
        status:  200,
        message: "SUCCESS",
        data:    { id:    member.id, email: member.email,
                   token: Token.encode({ member_id: member.id }) }
    }
  end
end

 

转载于:https://my.oschina.net/u/3970558/blog/2053022

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值