2017-05-05 57 views
1

我試圖在Rails API應用程序中實現用戶帳戶。 我有用戶邏輯工作註冊和登錄,但我的問題是,電子郵件鏈接是一個GET請求,並且所需的操作是POST。我可以激活通過POST請求郵差手動像這樣的網址:Rails API - POST激活

http://localhost:3000/users/confirm-request?token=b96be863aced91480a2a

如何這可以通過點擊電子郵件中的鏈接呢?

我的用戶控制器:

class UsersController < ApplicationController 

    def create 
    user = User.new(user_params) 
    if user.save 
     UserMailer.registration_confirmation(user).deliver 
     render json: { status: 201 }, status: :created 
    else 
     render json: { errors: user.errors.full_messages }, status: :bad_request 
    end 
    end 

    def confirm 
    token = params[:token].to_s 
    user = User.find_by(confirmation_token: token) 

    if user.present? && user.confirmation_token_valid? 
     user.mark_as_confirmed! 
     render json: {status: 'User confirmed successfully'}, status: :ok 
    else 
     render json: {status: 'Invalid token'}, status: :not_found 
    end 
    end 

    def login 
    user = User.find_by(email: params[:email].to_s.downcase) 

    if user && user.authenticate(params[:password]) 
     if user.confirmed_at? 
     auth_token = JsonWebToken.encode({user_id: user.id}) 
     render json: {auth_token: auth_token}, status: :ok 
     else 
     render json: {error: 'Email not verified' }, status: :unauthorized 
     end 
    else 
     render json: {error: 'Invalid username/password'}, status: :unauthorized 
    end 
    end 

    private 

    def user_params 
    params.require(:user).permit(:name, :email, :password, :password_confirmation) 
    end 

end 

我的routes.rb:

Rails.application.routes.draw do 
    resources :users, only: :create do 
    collection do 
     post 'confirm' 
     post 'login' 
    end 
    end 

registration_confirmation.text.erb:

Hi <%= @user.name %>, 

Thanks for registering. To confirm your registration click the URL below. 

<%= confirm_users_url(@user.confirmation_token) %> 
+0

據我所知(據我所知),你不能鏈接到POST因爲默認情況下所有的鏈接都是GET。現在,您可以將鏈接創建爲POST,但這已經通過JS完成了。話雖如此,電子郵件並不真的支持JS(也許有些?),因此最好只使用GET請求。要回答你的問題:你只需要將你的routes.rb從'post'confirm''改爲'get'confirm'' –

回答

1

變化碼的registration_confirmation.text.erb

Hi <%= @user.name %>, 

Thanks for registering. To confirm your registration click the URL below. 

<%#= confirm_users_url(token: @user.confirmation_token) %> 
<a href="https://stackoverflow.com/users/confirm?token=<%[email protected]_token%>"></a> 

的routes.rb

Rails.application.routes.draw do 
    resources :users, only: :create do 
    collection do 
     get 'confirm' 
     post 'login' 
    end 
    end 
end 
+0

對不起,我的實驗結果出錯了。 – baerlein

+0

(如果我不清楚)解決這個問題並不能解決問題。 – baerlein

+0

是你的問題解決? – puneet18