{"id":13879794,"url":"https://github.com/ontohub/graphql-pundit","last_synced_at":"2025-07-16T15:33:05.455Z","repository":{"id":56875204,"uuid":"95375341","full_name":"ontohub/graphql-pundit","owner":"ontohub","description":"Pundit authorization helpers for the GraphQL Ruby gem","archived":true,"fork":false,"pushed_at":"2020-01-30T14:48:40.000Z","size":103,"stargazers_count":111,"open_issues_count":18,"forks_count":31,"subscribers_count":9,"default_branch":"master","last_synced_at":"2024-11-11T03:53:17.106Z","etag":null,"topics":["authorization","graphql","pundit","ruby"],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ontohub.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-06-25T17:32:39.000Z","updated_at":"2023-01-28T15:57:21.000Z","dependencies_parsed_at":"2022-08-20T22:00:39.171Z","dependency_job_id":null,"html_url":"https://github.com/ontohub/graphql-pundit","commit_stats":null,"previous_names":[],"tags_count":9,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ontohub%2Fgraphql-pundit","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ontohub%2Fgraphql-pundit/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ontohub%2Fgraphql-pundit/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ontohub%2Fgraphql-pundit/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ontohub","download_url":"https://codeload.github.com/ontohub/graphql-pundit/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":226143895,"owners_count":17580245,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["authorization","graphql","pundit","ruby"],"created_at":"2024-08-06T08:02:33.473Z","updated_at":"2024-11-24T08:31:47.214Z","avatar_url":"https://github.com/ontohub.png","language":"Ruby","funding_links":[],"categories":["Ruby"],"sub_categories":[],"readme":"[![Gem](https://img.shields.io/gem/v/graphql-pundit.svg)](https://rubygems.org/gems/graphql-pundit)\n[![Build Status](https://travis-ci.org/ontohub/graphql-pundit.svg?branch=master)](https://travis-ci.org/ontohub/graphql-pundit)\n[![Coverage Status](https://codecov.io/gh/ontohub/graphql-pundit/branch/master/graph/badge.svg)](https://codecov.io/gh/ontohub/graphql-pundit)\n[![Code Climate](https://codeclimate.com/github/ontohub/graphql-pundit/badges/gpa.svg)](https://codeclimate.com/github/ontohub/graphql-pundit)\n[![GitHub issues](https://img.shields.io/github/issues/ontohub/graphql-pundit.svg?maxAge=2592000)](https://waffle.io/ontohub/ontohub-backend?source=ontohub%2Fgraphql-pundit)\n\n# GraphQL::Pundit\n\n## Installation\n\nAdd this line to your application's Gemfile:\n\n```ruby\ngem 'graphql-pundit', '~\u003e 0.7.0'\n```\n\nAnd then execute:\n\n```bash\n$ bundle\n```\n\n### Upgrade Notice\n\nIf you're upgrading from an earlier version, make sure to delete your\n`bootsnap` cache, to avoid a load error (see\n[this issue](https://github.com/ontohub/graphql-pundit/issues/51)).\nThe cache files are usually located in the `tmp` directory in your\nrepository and are named `bootsnap-compile-cache` and\n`bootsnap-load-path-cache`.\n\n## Usage\n\n### Class based API (`graphql-ruby \u003e= 1.8`)\n\nTo use `graphql-pundit` with the class based API introduced in `graphql`\nversion 1.8, the used `Field` class must be changed:\n\nIt is recommended to have application-specific base classes, from which the\nother types inherit (similar to having an `ApplicationController` from which\nall other controllers inherit). That base class can be used to define a\ncustom field class, on which the new `graphql-pundit` API builds.\n\n```ruby\nclass BaseObject \u003c GraphQL::Schema::Object\n  field_class GraphQL::Pundit::Field\nend\n```\n\nAll other object types now inherit from `BaseObject`, and that is all that is\nneeded to get `graphql-pundit` working with the class based API.\n\nIn case you already use a custom field type, or if you want to use a context\nkey other than `:current_user` to make your current user available, you can\ninclude `graphql-pundit`'s functionality into your field type:\n\n```ruby\nclass MyFieldType \u003c GraphQL::Schema::Field\n  prepend GraphQL::Pundit::Scope\n  prepend GraphQL::Pundit::Authorization\n\n  current_user :me # if the current_user is passed in as context[:me]\nend\n```\n\nWhen using this, make sure the order of `prepend`s is correct, as you usually want the authorization to happen **first**, which means that it needs to be `prepend`ed **after** the scopes (if you need them).\n\n#### Usage\n\n```ruby\nclass Car \u003c BaseObject\n  field :trunk, CarContent, null: true,\n                            authorize: true\nend\n```\n\nThe above example shows the most basic usage of this gem. The example would\nuse `CarPolicy#trunk?` for authorizing access to the field, passing in the\nparent object (in this case probably a `Car` model).\n\n##### Options\n\nTwo styles of declaring fields is supported:\n\n1. the inline style, passing all the options as a hash to the field method\n2. the block style\n\nBoth styles are presented below side by side.\n\n###### `authorize` and `authorize!`\n\nTo use authorization on a field, you **must** pass either the `authorize` or\n`authorize!` option. Both options will cause the field to return `nil` if the\naccess is unauthorized, but `authorize!` will also add an error message (e.g.\nfor usage with mutations).\n\n`authorize` and `authorize!` can be passed three different things:\n\n```ruby\nclass User \u003c BaseObject\n  # will use the `UserPolicy#display_name?` method\n  field :display_name, ..., authorize: true\n  field :display_name, ... do\n    authorize\n  end\n\n  # will use the passed lambda instead of a policy method\n  field :password_hash, ..., authorize: -\u003e(obj, args, ctx) { ... }\n  field :password_hash, ... do\n    authorize -\u003e(obj, args, ctx) { ... }\n  end\n\n  # will use the `UserPolicy#personal_info?` method\n  field :email, ..., authorize: :personal_info\n  field :email, ... do\n    authorize :personal_info\n  end\nend\n```\n\n- `true` will trigger the inference mechanism, meaning that the method that will be called on the policy class will be inferred from the (snake_case) field name.\n- a lambda function that will be called with the parent object, the arguments of the field and the context object; if the lambda returns a truthy value, authorization succeeds; otherwise (including thrown exceptions), authorization fails\n- a string or a symbol that corresponds to the policy method that should be called **minus the \"?\"**\n\n###### `policy`\n\n`policy` is an optional argument that can also be passed three different values:\n\n```ruby\nclass User \u003c BaseObject\n  # will use the `UserPolicy#display_name?` method (default inference)\n  field :display_name, ..., authorize: true, policy: nil\n  field :display_name do\n    authorize policy: nil\n  end\n\n  # will use OtherUserPolicy#password_hash?\n  field :password_hash, ...,\n                        authorize: true,\n                        policy: -\u003e(obj, args, ctx) { OtherUserPolicy }\n  field :password_hash, ... do\n    authorize policy: -\u003e(obj, args, ctx) { OtherUserPolicy }\n  end\n\n  # will use MemberPolicy#email?\n  field :email, ..., authorize: true, policy: MemberPolicy\n  field :email, ... do\n    authorize policy: MemberPolicy\n  end\nend\n```\n\n- `nil` is the default behavior and results in inferring the policy class from the record (see below)\n- a lambda function that will be called with the parent object, the arguments of the field and the context object; the return value of this function will be used as the policy class\n- an actual policy class\n\n###### `record`\n\n`record` can be used to pass a different value to the policy. Like `policy`,\nthis argument also can receive three different values:\n\n```ruby\nclass User \u003c BaseObject\n  # will use the parent object\n  field :display_name, ..., authorize: true, record: nil\n  field :display_name do\n    authorize record: nil\n  end\n\n  # will use the current user as the record\n  field :password_hash, ...,\n                        authorize: true,\n                        record: -\u003e(obj, args, ctx) { ctx[:current_user] }\n  field :password_hash, ... do\n    authorize record: -\u003e(obj, args, ctx) { ctx[:current_user] }\n  end\n\n  # will use AccountPolicy#email? with the first account as the record (the policy was inferred from the record class)\n  field :email, ..., authorize: true, record: Account.first\n  field :email, ... do\n    authorize record: Account.first\n  end\nend\n```\n\n- `nil` is again used for the inference; in this case, the parent object is used\n- a lambda function, again called with the parent object, the field arguments and the context object; the result will be used as the record\n- any other value that will be used as the record\n\nUsing `record` can be helpful for e.g. mutations, where you need a value to\ninitialize the policy with, but for mutations there is no parent object.\n\n###### `before_scope` and `after_scope`\n\n`before_scope` and `after_scope` can be used to apply Pundit scopes to the\nfields. Both options can be combined freely within one field. The result of\n`before_scope` is passed to the resolver as the \"parent object\", while the\nresult of `after_scope` is returned as the result of the field.\n\n```ruby\nclass User \u003c BaseObject\n  # will use the `PostPolicy::Scope` before the resolver\n  field :posts, ..., before_scope: true\n  field :posts, ... do\n    before_scope\n  end\n\n  # will use the passed lambda after the resolver\n  field :comments, ..., after_scope: -\u003e(comments, args, ctx) { ... }\n  field :comments, ... do\n    after_scope -\u003e(comments, args, ctx) { ... }\n  end\n\n  # will use the `FriendPolicy::Scope`\n  field :friends, ..., after_scope: FriendPolicy\n  field :friends, ... do\n    after_scope FriendPolicy\n  end\nend\n```\n\n- `true` will trigger the inference mechanism, where the policy class, which contains the scope class, is inferred based on either the parent object (for `before_scope`) or the result of the resolver (for `after_scope`).\n- a lambda function, that will be called with the parent object (for `before_scope`) or the result of the resolver (for `after_scope`), the field arguments and the context\n- a policy class that contains a `Scope` class (this does not actually have to be a policy class, but could also be a module containing a `Scope` class)\n\n###### Combining options\n\nAll options can be combined with one another (except `authorize` and `authorize!`; please don't do that). Examples:\n\n```ruby\n# MemberPolicy#name? initialized with the parent\nfield :display_name, ..., authorize: :name,\n                          policy: MemberPolicy\n\n# UserPolicy#display_name? initialized with user.account_data\nfield :display_name, ..., do\n  authorize policy: UserPolicy, \n            record: -\u003e(obj, args, ctx) { obj.account_data }\nend\n```\n\n### Legacy `define` API\n\nThe legacy `define` based API will be supported until it is removed from the\n`graphql` gem (as planned for version 1.10).\n\n#### Add the authorization middleware\n\nAdd the following to your GraphQL schema:\n\n```ruby\nMySchema = GraphQL::Schema.define do\n  ...\n  instrument(:field, GraphQL::Pundit::Instrumenter.new)\n  ...\nend\n```\n\nBy default, `ctx[:current_user]` will be used as the user to authorize. To change that behavior, pass a symbol to `GraphQL::Pundit::Instrumenter`. \n\n```ruby\nGraphQL::Pundit::Instrumenter.new(:me) # will use ctx[:me]\n```\n\n#### Authorize fields\n\nFor each field you want to authorize via Pundit, add the following code to the field definition:\n\n```ruby\nfield :email do\n  authorize # will use UserPolicy#email?\n  resolve ...\nend\n```\n\nBy default, this will use the Policy for the parent object (the first argument passed to the resolve proc), checking for `:email?` for the current user. Sometimes, the field name will differ from the policy method name, in which case you can specify it explicitly:\n\n```ruby\nfield :email do\n  authorize :read_email # will use UserPolicy#read_email?\n  resolve ...\nend\n```\n\nNow, in some cases you'll want to use a different policy, or in case of mutations, the passed object might be `nil`:\n\n```ruby\nfield :createUser\n  authorize! :create, policy: User # or User.new; will use UserPolicy#create?\n  resolve ...\nend\n```\n\nThis will use the `:create?` method of the `UserPolicy`. You can also pass in objects instead of a class (or symbol), if you wish to authorize the user for the specific object.\n\nIf you want to pass a different value to the policy, you can use the keyword argument `record`:\n\n```ruby\nfield :createUser\n  authorize! :create, record: User.new # or User.new; will use UserPolicy#create?\n  resolve ...\nend\n```\n\nYou can also pass a `lambda` as a record. This receives the usual three arguments (parent value, arguments, context) and returns the value to be used as a record.\n\nYou might have also noticed the use of `authorize!` instead of `authorize` in this example. The difference between the two is this:\n\n- `authorize` will set the field to `nil` if authorization fails\n- `authorize!` will set the field to `nil` and add an error to the response if authorization fails\n\nYou would normally want to use `authorize` for fields in queries, that only e.g. the owner of something can see, while `authorize!` would be usually used in mutations, where you want to communicate to the client that the operation failed because the user is unauthorized.\n\nIf you still need more control over how policies are called, you can pass a lambda to `authorize`:\n\n```ruby\nfield :email\n  authorize -\u003e(obj, args, ctx) { UserPolicy.new(obj, ctx[:me]).private_data?(:email) }\n  resolve ...\nend\n```\n\nIf the lambda returns a falsy value or raises a `Pundit::UnauthorizedError` the field will resolve to `nil`, if it returns a truthy value, control will be passed to the resolve function. Of course, this can be used with `authorize!` as well.\n\n#### Scopes\n\nPundit scopes are supported by using `before_scope` and `after_scope` in the field definition\n\n```ruby\nfield :posts\n  after_scope\n  resolve ...\nend\n```\n\nPassing no arguments to `after_scope` and `before_scope` will infer the policy to use from the value it is passed: `before_scope` is run before `resolve` and will receive the parent object, `after_scope` will be run after `resolve` and receives the output of `resolve`. You can also pass a proc or a policy class to both `_scope`s:\n\n```ruby\nfield :posts\n  before_scope -\u003e(_root, _args, ctx) { Post.where(owner: ctx[:current_user]) }\n  resolve -\u003e(posts, args, ctx) { ... }\nend\n```\n\n```ruby\nfield :posts\n  after_scope PostablePolicy\n  resolve ...\nend\n```\n\n## Development\n\nAfter checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.\n\nTo install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).\n\n## Contributing\n\nBug reports and pull requests are welcome on GitHub at https://github.com/ontohub/graphql-pundit.\n\n\n## License\n\nThe gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fontohub%2Fgraphql-pundit","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fontohub%2Fgraphql-pundit","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fontohub%2Fgraphql-pundit/lists"}