关于使用GraphQL设置current_user有点困惑。因此,我在Restful应用程序中完成此操作的方式将是让用户控制器像这样创建时登录用户
def create
@user = User.new(user_params)
if @user.save
login(@user)
render :show
else
render json: @user.errors.messages, status: 422
end
end
我在应用程序控制器中有login(user)方法,它的作用基本上是将用户设置为current_user helper_method,并像这样分配会话令牌
protect_from_forgery with: :exception
helper_method :current_user
def login(user)
@current_user = user
session[:session_token] = user.reset_session_token!
end
def logout
current_user.reset_session_token!
session[:session_token] = nil
end
def logged_in?
!!current_user
end
def current_user
@current_user ||= User.find_by(session_token: session[:session_token])
end
我猜我真正的问题是我应该如何在GraphQL控制器上下文中使用current_user?我使用的是“ graphql” gem,它为我创建了一个graphQL控制器,但仍然对如何实现它感到困惑。创建新用户时,其输出为
[["username", "elyy"], ["email", "kelly@kelly.com"], ["password_digest", "$2a$10$ATfHgklNx0bED7N9JCQfHuHjNF/sJ5AcwkOzMOqX7sPLdgAREcHd6"], ["created_at", "2018-10-21 01:46:06.913393"], ["updated_at", "2018-10-21 01:46:06.913393"], ["session_token","uOqgAxb5sOLm2AQMExLwaQ"]]
有关我如何进行项目设置的更多信息,我将在底部包括用户模型,用于创建用户的变体和GraphQL控制器。如果您需要任何其他信息,请随时询问。谢谢所有能帮助我解释该问题的人,并通过GraphQL对我进行进一步的教育,因为我在阅读文档和一些示例时感到困惑。
class User < ApplicationRecord
has_secure_password
validates :username, :email, :password_digest, presence: true, on: :create
validates :username, uniqueness: true
validates :password, length: { minimum: 6, allow_nil: true }
validates_format_of :email, :with => /@/
attr_reader :password
after_initialize :ensure_session_token
def self.find_by_credentials(email, password)
user = User.find_by(email: email)
user && user.is_password?(password) ? user : nil
end
def self.generate_session_token
SecureRandom.urlsafe_base64
end
def password=(password)
@password = password
self.password_digest = BCrypt::Password.create(password)
end
def is_password?(password)
BCrypt::Password.new(self.password_digest).is_password?(password)
end
def reset_session_token!
self.session_token = User.generate_session_token
self.save!
self.session_token
end
def ensure_session_token
self.session_token ||= User.generate_session_token
end
end
class Resolvers::CreateUser < GraphQL::Function
argument :email, !types.String
argument :password, !types.String
argument :username, !types.String
type Types::UserType
def call(_obj, args, _ctx)
User.create!(
email: args[:email],
password: args[:password],
username: args[:username]
)
end
end
class GraphqlController < ApplicationController
def execute
variables = ensure_hash(params[:variables])
query = params[:query]
operation_name = params[:operationName]
context = {
# Query context goes here, for example:
current_user: current_user,
}
result = PrivateBookSchema.execute(query, variables: variables, context: context, operation_name: operation_name)
render json: result
rescue => e
raise e unless Rails.env.development?
handle_error_in_development e
end
private
# Handle form data, JSON body, or a blank value
def ensure_hash(ambiguous_param)
case ambiguous_param
when String
if ambiguous_param.present?
ensure_hash(JSON.parse(ambiguous_param))
else
{}
end
when Hash, ActionController::Parameters
ambiguous_param
when nil
{}
else
raise ArgumentError, "Unexpected parameter: #{ambiguous_param}"
end
end
def handle_error_in_development(e)
logger.error e.message
logger.error e.backtrace.join("\n")
render json: { error: { message: e.message, backtrace: e.backtrace }, data: {} }, status: 500
end
end