在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