我正在使用设计令牌认证(devise_token_auth)进行用户登录和基于令牌的注册,因为它仅用于开发api。我需要在用户注册他/她的帐户后立即让用户登录。我怎么能这样做?我试过但不能成功,所以我在这里希望得到帮助。
class Users::RegistrationsController < DeviseTokenAuth::RegistrationsController
prepend_before_action :configure_permitted_parameters
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:account_update, keys: [:id, :first_name, :last_name, :phone, :status])
devise_parameter_sanitizer.permit(:sign_up, keys: [:confirm_success_url])
end
private
def user_params
params.permit.all #(:id, :email, :firstname, :lastname, :phone, :status)
end
end
Rails.application.routes.draw do
# devise_for :users, controllers: { confirmations: 'confirmations' }
mount_devise_token_auth_for 'User', at: 'auth', controllers: {
# confirmations: 'confirmations',
registrations: 'users/registrations',
passwords: 'users/passwords'
}
class ApplicationController < ActionController::API
before_action :authenticate_user!
include DeviseTokenAuth::Concerns::SetUserByToken
def authenticate_current_user
head :unauthorized if get_current_user.nil?
end
def get_current_user
return nil unless cookies[:auth_headers]
auth_headers = JSON.parse cookies[:auth_headers]
puts('################################')
puts('auth_headers', auth_headers)
expiration_datetime = DateTime.strptime(auth_headers["expiry"], "%s")
current_user = User.find_by(uid: auth_headers["uid"])
if current_user &&
current_user.tokens.has_key?(auth_headers["client"]) &&
expiration_datetime > DateTime.now
@current_user = current_user
end
@current_user
end
end
我在下面尝试了代码
def after_sign_up_path_for(resource)
puts('it should be shown')
puts('################################')
puts('resource', resource)
puts('header', request.headers['client'])
client_id = request.headers['client']
new_auth_header = @resource.create_new_auth_token(client_id)
response.headers.merge!(new_auth_header)
end
在Users :: RegistrationController中,但在成功注册后根本不执行。
答案 0 :(得分:0)
不太复杂。创建用户后,只需调用sign_in
并传递资源(用户)。
https://github.com/plataformatec/devise/wiki/How-To:-Sign-in-from-a-controller
示例:
sign_in @current_user
Devise::RegistrationController
实际上是already does this。
此外,由于您使用的是DeviseTokenAuth
gem
和DeviseTokenAuth::RegistrationsController
controller inherits from Devise
's own base controller,因此您{应该} access to all the helpers Devise
控制器。
一个implementation might look like这个。
class Users::RegistrationsController < DeviseTokenAuth::RegistrationsController
def create
super do |resource|
sign_in(resource)
end
end
end