2017-05-05 53 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