Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Graphql auth #751

Merged
merged 15 commits into from
Apr 5, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ GEM
activesupport (>= 4.2.0)
graphiql-rails (1.4.4)
rails
graphql (1.6.7)
graphql (1.7.13)
hashie (3.5.6)
i18n (0.8.6)
jbuilder (2.7.0)
Expand All @@ -183,7 +183,7 @@ GEM
addressable (~> 2.3)
letter_opener (1.4.1)
launchy (~> 2.2)
loofah (2.2.1)
loofah (2.2.2)
crass (~> 1.0.2)
nokogiri (>= 1.5.9)
mail (2.6.6)
Expand Down Expand Up @@ -256,8 +256,8 @@ GEM
rails-dom-testing (2.0.3)
activesupport (>= 4.2.0)
nokogiri (>= 1.6)
rails-html-sanitizer (1.0.3)
loofah (~> 2.0)
rails-html-sanitizer (1.0.4)
loofah (~> 2.2, >= 2.2.2)
rails_12factor (0.0.3)
rails_serve_static_assets
rails_stdout_logging
Expand Down
4 changes: 4 additions & 0 deletions app/controllers/concerns/tournament_concern.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,8 @@ def load_tournament
render_404
end
end

def current_tournament
@tournament
end
end
33 changes: 33 additions & 0 deletions app/controllers/graphql_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
class GraphqlController < ApplicationController
include TournamentConcern

skip_before_action :verify_authenticity_token

def execute
result = Schema.execute(
query_string,
variables: query_variables,
context: {
tournament: current_tournament,
current_user: current_user
},
only: filter
)

render json: result
end

private

def query_string
params[:query]
end

def query_variables
params[:variables]
end

def filter
params[:filter] == false ? nil : OnlyFilter
end
end
19 changes: 0 additions & 19 deletions app/controllers/graphqls_controller.rb

This file was deleted.

4 changes: 4 additions & 0 deletions app/graphql/mutation_type.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
name "Mutation"
description "The mutation root for this schema"

# public
field :submitScore, field: SubmitScoreMutation.field
field :checkPin, field: CheckPinMutation.field

# admin
field :gameUpdateScore, field: GameUpdateScoreMutation.field, auth_required: true
end
32 changes: 32 additions & 0 deletions app/graphql/mutations/game_update_score_mutation.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
GameUpdateScoreMutation = GraphQL::Relay::Mutation.define do
name "GameUpdateScore"

input_field :game_id, types.ID
input_field :home_score, types.Int
input_field :away_score, types.Int
input_field :force, types.Boolean
input_field :resolve, types.Boolean

return_field :success, !types.Boolean

resolve(Auth.protect -> (obj, inputs, ctx) {
game = ctx[:tournament].games.find(inputs[:game_id])

op = GameUpdateScore.new(
game: game,
home_score: inputs[:home_score],
away_score: inputs[:away_score],
user: ctx[:current_user],
force: inputs[:force],
resolve: inputs[:resolve]
)

op.perform

if op.succeeded?
{ success: true }
else
{ success: false }
end
})
end
2 changes: 2 additions & 0 deletions app/graphql/schema.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
require_relative 'utils/definitions'

Schema = GraphQL::Schema.define do
query QueryType
mutation MutationType
Expand Down
17 changes: 17 additions & 0 deletions app/graphql/utils/auth.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
module Auth
def self.visible(ctx)
ctx[:current_user] && ctx[:current_user].is_tournament_user?(ctx[:tournament])
end

def self.protect(resolve)
-> (obj, args, ctx) do
if ctx[:current_user].nil?
GraphQL::ExecutionError.new("You need to sign in or sign up before continuing")
elsif ctx[:current_user].is_tournament_user?(ctx[:tournament])
resolve.call(obj, args, ctx)
else
GraphQL::ExecutionError.new("You are not a registered user for this tournament")
end
end
end
end
5 changes: 5 additions & 0 deletions app/graphql/utils/definitions.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
GraphQL::Field.accepts_definitions(
auth_required: -> (field, _) {
field.metadata[:visibility_proc] = -> (ctx) { Auth.visible(ctx) }
}
)
6 changes: 6 additions & 0 deletions app/graphql/utils/only_filter.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
class OnlyFilter
def self.call(schema_member, context)
return true unless visibility_proc = schema_member.metadata[:visibility_proc]
visibility_proc.call(context)
end
end
4 changes: 2 additions & 2 deletions app/models/user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ def name
email.split('@').first
end

def is_tournament_user?(tournament_id)
tournaments.exists?(id: tournament_id)
def is_tournament_user?(tournament)
tournaments.exists?(id: tournament.try(:id) || tournament)
end

private
Expand Down
1 change: 1 addition & 0 deletions config/application.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ module UltimateTournament
class Application < Rails::Application
config.active_record.default_timezone = :local

config.autoload_paths << Rails.root.join('app/graphql/utils')
config.autoload_paths << Rails.root.join('app/graphql/types')
config.autoload_paths << Rails.root.join('app/graphql/mutations')

Expand Down
2 changes: 1 addition & 1 deletion config/routes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
draw :internal

constraints(Subdomain) do
post 'graphql' => 'graphqls#create'
post 'graphql' => 'graphql#execute'
mount GraphiQL::Rails::Engine, at: '/graphiql', graphql_path: '/graphql'
draw :admin
draw :player_app
Expand Down
77 changes: 77 additions & 0 deletions test/integration/api_auth_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
require 'test_helper'

class ApiAuthTest < ActionDispatch::IntegrationTest
setup do
@user = FactoryGirl.create(:user)
@tournament = FactoryGirl.create(:tournament)
FactoryGirl.create(:tournament_user, user: @user, tournament: @tournament)
ReactOnRails::TestHelper.ensure_assets_compiled
end

test "mutation with auth" do
login_user
game = FactoryGirl.create(:game, :scheduled)
input = {"game_id" => game.id, "home_score" => 10, "away_score" => 5}
execute_graphql("gameUpdateScore", "GameUpdateScoreInput", input)
assert_success
end

test "mutation without auth" do
game = FactoryGirl.create(:game, :scheduled)
input = {"game_id" => game.id, "home_score" => 10, "away_score" => 5}
execute_graphql("gameUpdateScore", "GameUpdateScoreInput", input)
assert_error "You need to sign in or sign up before continuing"
end

test "mutation with auth for wrong tournament" do
login_user
@tournament = FactoryGirl.create(:tournament)
game = FactoryGirl.create(:game, :scheduled, tournament: @tournament)
input = {"game_id" => game.id, "home_score" => 10, "away_score" => 5}
execute_graphql("gameUpdateScore", "GameUpdateScoreInput", input)
assert_error "You are not a registered user for this tournament"
end

test "mutation without auth with filter" do
game = FactoryGirl.create(:game, :scheduled)
input = {"game_id" => game.id, "home_score" => 10, "away_score" => 5}
execute_graphql("gameUpdateScore", "GameUpdateScoreInput", input, filter: true)
assert_error "Field 'gameUpdateScore' doesn't exist on type 'Mutation'"
end

private

def login_user
get "http://#{@tournament.handle}.lvh.me/admin"
follow_redirect!
assert_equal 200, status
assert_equal new_user_session_path, path

post new_user_session_path, params: { user: {email: @user.email, password: 'password'} }
follow_redirect!
assert_equal 200, status
assert_equal "/admin", path
end

def execute_graphql(mutation, input_type, input, filter: false)
url = "http://#{@tournament.handle}.lvh.me/graphql"

params = {
"query" => "mutation #{mutation}($input: #{input_type}!) { #{mutation}(input: $input) { success }}",
"variables" => {"input" => input},
"filter" => filter
}

post url, params: params.to_json, headers: { 'CONTENT_TYPE' => 'application/json' }

@result = JSON.parse(response.body)
end

def assert_success
assert @result['data'].first[1]['success']
end

def assert_error(message)
assert_equal message, @result['errors'].first['message']
end
end