2016-11-10 96 views
0

我試圖完成使用基本身份驗證的Rails

http_basic_authenticate_with name: "admin", password: "secret" 

辦法有一個用戶的電子郵件和密碼使用,而不必硬編碼密碼進行身份驗證。這是我的控制器類的其餘部分。

class Api::V1::UserInfosController < ApplicationController 
    before_action :set_user_info, only: [:show, :edit, :update, :destroy] 
    http_basic_authenticate_with name: "admin", password: "secret" 

    # GET /user_infos 
    def index 
    @user_infos = UserInfo.all 
    end 

    respond_to :json 

    def show 
    respond_with UserInfo.find(params[:id]) 
    end 

    # GET /user_infos/new 
    def new 
    @user_info = UserInfo.new 
    end 

    # GET /user_infos/1/edit 
    def edit 
    end 

    # POST /user_infos 
    def create 
    @user_info = UserInfo.new(user_info_params) 

    if @user_info.save 
     redirect_to @user_info, notice: 'User info was successfully created.' 
    else 
     render :new 
    end 
    end 

    # PATCH/PUT /user_infos/1 
    def update 
    if @user_info.update(user_info_params) 
     redirect_to @user_info, notice: 'User info was successfully updated.' 
    else 
     render :edit 
    end 
    end 

    # DELETE /user_infos/1 
    def destroy 
    @user_info.destroy 
    redirect_to user_infos_url, notice: 'User info was successfully destroyed.' 
    end 

    private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_user_info 
     @user_info = UserInfo.find(params[:id]) 
    end 

    # Only allow a trusted parameter "white list" through. 
    def user_info_params 
     params.require(:user_info).permit(:artist, :email, :password) 
    end 
end 

任何幫助都將不勝感激! :)

回答

2

我建議您使用Devise gem進行身份驗證。它很容易使用,並有一個巨大的社區支持。

然而,回答你的問題,你可以做的就是按照例如ActionController::HttpAuthentication::Basic文檔和實現是這樣的:

class Api::V1::UserInfosController < ApplicationController 
    before_filter :set_current_user 

    private 

    def set_current_user 
    @current_user ||= authenticate_or_request_with_http_basic do |u, p| 
     User.find(email: u, password: p) 
    end 
    end 
end 

哪裏User是你的授權用戶的模型。

+0

謝謝!這是一個非常合理的解決方案。但是當我插入這段代碼時,它說出於某種原因,電子郵件不是一個已定義的局部變量。 :( – Aaron

+0

我想你需要運行'rake db:reset' –

+0

這不會是刪除數據庫嗎? – Aaron