Rails + Graphql and Authentication confusion

Viewed 798

I'm a bit confused in regards to setting a current_user with GraphQL. So the way I would have done it in a Restful application would be to have the user controller login a user upon its creation like so

  def create
    @user = User.new(user_params)

    if @user.save
      login(@user)
      render :show
    else
      render json: @user.errors.messages, status: 422
    end
  end

I've got login(user) method within the application controller and what it does it basically set the user to current_user helper_method and assign a session token like so

  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

I guess my real question is how should I go about to have current_user present within my GraphQL controller context? I'm using 'graphql' gem which created a graphQL controller for me but still confused how I should implement it. When a new user gets created its output is

[["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"]]

For more information on how I have my project setup, I'll include the User model, the mutation for creating a User and the GraphQL controller in the bottom. If there is any further information you need please feel free to ask. Thank you for everyone who will help explain how I should approach this problem and further educate me with GraphQL since I'm confused while looking at the docs and a few people examples.

User Model

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

Create User Mutation

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

GraphQL controller

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
0 Answers
Related