{"id":13879428,"url":"https://github.com/graphql-devise/graphql_devise","last_synced_at":"2025-05-15T02:07:27.345Z","repository":{"id":37514792,"uuid":"200547264","full_name":"graphql-devise/graphql_devise","owner":"graphql-devise","description":"GraphQL interface on top devise_token_auth","archived":false,"fork":false,"pushed_at":"2024-12-10T04:22:13.000Z","size":631,"stargazers_count":200,"open_issues_count":17,"forks_count":47,"subscribers_count":6,"default_branch":"master","last_synced_at":"2025-04-14T00:57:46.458Z","etag":null,"topics":["activerecord","api","api-server","authenticate","authentication","authentication-backend","authentication-schema","authentication-token","devise","devise-token-auth","dta","gem","graphql","graphql-interface","mongoid","rails","ruby","rubygem"],"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/graphql-devise.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-08-04T22:21:58.000Z","updated_at":"2025-02-11T21:34:41.000Z","dependencies_parsed_at":"2024-01-13T20:57:18.678Z","dependency_job_id":"fdee7b49-d83f-447d-8af6-09df3231e50b","html_url":"https://github.com/graphql-devise/graphql_devise","commit_stats":{"total_commits":278,"total_committers":15,"mean_commits":"18.533333333333335","dds":"0.23381294964028776","last_synced_commit":"ba5f275bb8167ce0364fe6884050647b748c2b68"},"previous_names":[],"tags_count":51,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/graphql-devise%2Fgraphql_devise","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/graphql-devise%2Fgraphql_devise/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/graphql-devise%2Fgraphql_devise/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/graphql-devise%2Fgraphql_devise/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/graphql-devise","download_url":"https://codeload.github.com/graphql-devise/graphql_devise/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254259383,"owners_count":22040820,"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":["activerecord","api","api-server","authenticate","authentication","authentication-backend","authentication-schema","authentication-token","devise","devise-token-auth","dta","gem","graphql","graphql-interface","mongoid","rails","ruby","rubygem"],"created_at":"2024-08-06T08:02:20.786Z","updated_at":"2025-05-15T02:07:27.322Z","avatar_url":"https://github.com/graphql-devise.png","language":"Ruby","readme":"# GraphqlDevise\n[![Build Status](https://circleci.com/gh/graphql-devise/graphql_devise.svg?style=svg)](https://app.circleci.com/pipelines/github/graphql-devise/graphql_devise)\n[![Coverage Status](https://coveralls.io/repos/github/graphql-devise/graphql_devise/badge.svg)](https://coveralls.io/github/graphql-devise/graphql_devise)\n[![Gem Version](https://badge.fury.io/rb/graphql_devise.svg)](https://badge.fury.io/rb/graphql_devise)\n\nGraphQL interface on top of the [Devise Token Auth](https://github.com/lynndylanhurley/devise_token_auth) (DTA) gem.\n\n## Table of Contents\n\n\u003c!--ts--\u003e\n* [GraphqlDevise](#graphqldevise)\n   * [Table of Contents](#table-of-contents)\n   * [Introduction](#introduction)\n   * [Installation](#installation)\n      * [Running the Generator](#running-the-generator)\n         * [Mounting the Schema in a Separate Route](#mounting-the-schema-in-a-separate-route)\n         * [Mounting Operations in an Existing Schema (\u0026gt; v0.12.0)](#mounting-operations-in-an-existing-schema--v0120)\n   * [Usage](#usage)\n      * [Mounting Auth Schema on a Separate Route](#mounting-auth-schema-on-a-separate-route)\n      * [Mounting Operations In an Existing Schema](#mounting-operations-in-an-existing-schema)\n      * [Available Mount Options](#available-mount-options)\n      * [Available Operations](#available-operations)\n      * [Configuring Model](#configuring-model)\n      * [Email Reconfirmation](#email-reconfirmation)\n         * [Current flow](#current-flow)\n      * [Customizing Email Templates](#customizing-email-templates)\n      * [I18n](#i18n)\n      * [Authenticating Controller Actions](#authenticating-controller-actions)\n         * [Authenticate Resource in the Controller (\u0026gt;= v0.15.0)](#authenticate-resource-in-the-controller--v0150)\n            * [Authentication Options](#authentication-options)\n      * [Making Requests](#making-requests)\n         * [Introspection query](#introspection-query)\n         * [Mutations](#mutations)\n      * [Reset Password Flow](#reset-password-flow)\n      * [More Configuration Options](#more-configuration-options)\n         * [Devise Token Auth Initializer](#devise-token-auth-initializer)\n         * [Devise Initializer](#devise-initializer)\n      * [GraphQL 2.0 Support (\u0026gt;= v1.0.0)](#graphql-20-support--v100)\n      * [GraphQL Interpreter](#graphql-interpreter)\n      * [Using Alongside Standard Devise](#using-alongside-standard-devise)\n   * [Changelog](#changelog)\n   * [Future Work](#future-work)\n   * [Buy Us a Coffee](#buy-us-a-coffee)\n            * [BTC](#btc)\n            * [ADA](#ada)\n   * [Contributing](#contributing)\n   * [License](#license)\n\n\u003c!-- Added by: mcelicalderon, at: Wed Aug  3 22:04:10 -05 2022 --\u003e\n\n\u003c!--te--\u003e\n\n## Introduction\nGraphql-Devise heavily relies on 3 gems:\n- [GraphQL Ruby](https://github.com/rmosolgo/graphql-ruby)\n- [Devise Token Auth](https://github.com/lynndylanhurley/devise_token_auth) (DTA)\n- [Devise](https://github.com/heartcombo/devise) (which is a DTA dependency)\n\nThis gem provides a GraphQL interface on top of DTA which is designed for REST APIs. Features like token management, token expiration and everything up until using the actual GraphQL schema is still controlled by DTA. For that reason the gem's generator invokes DTA and Devise generators and creates initializer files for each one of them.\n\n**We strongly recommend getting familiar with [DTA documentation](https://github.com/lynndylanhurley/devise_token_auth) to use this gem to its full potential**.\nMore configuration details available in [configuration section](#more-configuration-options)\n\n## Installation\n\nAdd this line to your application's Gemfile:\n\n```ruby\ngem 'graphql_devise'\n```\n\nAnd then execute:\n```bash\n$ bundle\n```\n\n### Running the Generator\nGraphql Devise generator will execute `Devise` and `Devise Token Auth` generators to setup the gems in your project. You can customize them to your needs using their initializer files(one per gem) as usual.\n\n```bash\n$ bundle exec rails generate graphql_devise:install\n```\nThe generator accepts 2 params and 1 option:\n- `user_class`: Model name in which `Devise` modules will be included. This uses a `find or create` strategy. Defaults to `User`.\n- `mount_path`: Path in which the dedicated graphql schema for devise will be mounted. Defaults to `/graphql_auth`.\n- `--mount`: This options is available starting from `v0.12.0`, it allows you to mount the operations in your own schema instead of a dedicated one. When provided `mount_path` param is ignored.\n\n#### Mounting the Schema in a Separate Route\n\nTo configure the gem to use a separate schema, the generator will use `user_class` and `mount_path` params.\nThe route will be mounted in `config/routes.rb`. For instance the executing:\n\n```bash\n$ bundle exec rails g graphql_devise:install Admin api/auth\n```\n\nWill do the following:\n- Execute `Devise` install generator\n- Execute `Devise Token Auth` install generator with `Admin` and `api/auth` as params\n  - Find or create `Admin` model\n  - Add `devise` modules to `Admin` model\n  - Other changes that you can find [here](https://devise-token-auth.gitbook.io/devise-token-auth/config)\n- Add the route to `config/routes.rb`\n  - `mount_graphql_devise_for Admin, at: 'api/auth'`\n\n`Admin` could be any model name you are going to be using for authentication,\nand `api/auth` could be any mount path you would like to use for auth.\n\n**Important**\n - Remember that by default this gem mounts a completely separate GraphQL schema on a separate controller in the route provided by the `at` option in the `mount_graphql_devise_for` method in the `config/routes.rb` file. If no `at` option is provided, the route will be `/graphql_auth`.\n - Avoid passing the `--mount` option if you want to use a separate route and schema.\n\n#### Mounting Operations in an Existing Schema (\u003e v0.12.0)\nTo configure the gem to use an existing GQL schema use the `--mount` option.\nFor instance the executing:\n\n```bash\n$ bundle exec rails g graphql_devise:install Admin --mount MySchema\n```\n\nWill do the following:\n- Execute `Devise` install generator\n- Execute `Devise Token Auth` install generator with `Admin` and `api/auth` as params\n  - Find or create `Admin` model\n  - Add `devise` modules to `Admin` model\n  - Other changes that you can find [here](https://devise-token-auth.gitbook.io/devise-token-auth/config)\n  - Add `SchemaPlugin` to the specified schema.\n\n\n**Important**\n - When using the `--mount` option the `mount_path` param is ignored.\n - The generator will look for your schema under `app/graphql/` directory. We are expecting the name of the file is the same as the as the one passed in the mount option transformed with `underscore`. In the example, passing `MySchema`, will try to find the file `app/graphql/my_schema.rb`.\n - You can actually mount a resource's auth schema in a separate route and in your app's schema at the same time, but that's probably not a common scenario.\n\n## Usage\n\nGraphqlDevise operations can be used in two ways:\n- Using a [separate schema](#mounting-auth-schema-on-a-separate-route) via `mount_graphql_devise_for` helper in the routes file.\n- Using [your own schema](#mounting-operations-into-your-own-schema) by adding a plugin in the class.\n\n\nCreating a separate schema is the default option, the generator will do that by default.\n\n### Mounting Auth Schema on a Separate Route\n\nYou can mount this gem's GraphQL auth schema in your routes file like this:\n\n```ruby\n# config/routes.rb\n\nRails.application.routes.draw do\n  mount_graphql_devise_for(\n    User,\n    at: 'api/v1',\n    authenticatable_type: Types::MyCustomUserType,\n    operations: {\n      login: Mutations::Login\n    },\n    skip: [:register],\n    # optional, use only if you need a specific base controller to mount the new actions\n    base_controller: ApiController,\n    additional_mutations: {\n      # generates mutation { adminUserSignUp }\n      admin_user_sign_up: Mutations::AdminUserSignUp\n    },\n    additional_queries: {\n      # generates query { publicUserByUuid }\n      public_user_by_uuid: Resolvers::UserByUuid\n    }\n  )\nend\n```\nThis can be done using the generator or manually.\nThe second argument of the `mount_graphql_devise` method is a hash of options where you can\ncustomize how the queries and mutations are mounted into the schema. For a list of available\noptions go [here](#available-mount-options)\n\n### Mounting Operations In an Existing Schema\n\nStarting with `v0.12.0` you can mount the GQL operations provided by this gem into an\nexisting schema in your app.\n\n```ruby\n# app/graphql/dummy_schema.rb\n\nclass DummySchema \u003c GraphQL::Schema\n  # It's important that this line goes before setting the query and mutation type on your\n  # schema in graphql versions \u003c 1.10.0\n  use GraphqlDevise::SchemaPlugin.new(\n    query:            Types::QueryType,\n    mutation:         Types::MutationType,\n    resource_loaders: [\n      GraphqlDevise::ResourceLoader.new(User, only: [:login, :confirm_registration_with_token])\n    ]\n  )\n\n  mutation(Types::MutationType)\n  query(Types::QueryType)\nend\n```\nThe example above describes just one of the possible scenarios you might need.\nThe second argument of the `GraphqlDevise::ResourceLoader` initializer is a hash of\noptions where you can customize how the queries and mutations are mounted into the schema.\nFor a list of available options go [here](#available-mount-options).\n\nIt's important to use the plugin in your schema before assigning the mutation and query type to\nit in graphql versions `\u003c 1.10.0`. Otherwise the auth operations won't be available.\n\nYou can provide as many resource loaders as you need to the `resource_loaders` option, and each\nof those will be loaded into your schema. These are the options you can initialize the\n`SchemaPlugin` with:\n\n1. `query`: This param is mandatory unless you skip all queries via the resource loader\noptions. This should be the same `QueryType` you provide to the `query` method\nin your schema.\n1. `mutation`: This param mandatory unless you skip all mutations via the resource loader\noptions. This should be the same `MutationType` you provide to the `mutation` method\nin your schema.\n1. `resource_loaders`: This is an optional array of `GraphqlDevise::ResourceLoader` instances.\nHere is where you specify the operations that you want to load into your app's schema.\nIf no loader is provided, no operations will be added to your schema, but you will still be\nable to authenticate queries and mutations selectively. More on this in the controller\nauthentication [section](#authenticating-controller-actions).\n1. `authenticate_default`: This is a boolean value which is `true` by default. This value\ndefines what is the default behavior for authentication in your schema fields. `true` means\nevery root level field requires authentication unless specified otherwise using the\n`authenticate: false` option on the field. `false` means your root level fields won't require\nauthentication unless specified otherwise using the `authenticate: true` option on the field.\n1. `unauthenticated_proc`: This param is optional. Here you can provide a proc that receives\none argument (field name) and is called whenever a field that requires authentication\nis called without an authenticated resource. By default a `GraphQL::ExecutionError` will be\nraised if authentication fails. This will provide a GQL like error message on the response.\n1. `public_introspection`: The [introspection query](https://graphql.org/learn/introspection/) is a very useful GQL resource that provides\ninformation about what queries the schema supports. This query is very powerful and\nthere may be some case in which you want to limit its usage to authenticated users.\nTo accomplish this the schema plugin provides the `public_introspection` option. This option\naccepts a boolean value and by default will consider introspection queries public in all\nenvironments but production.\n\n### Available Mount Options\nBoth the `mount_graphql_devise_for` method and the `GraphqlDevise::ResourceLoader` class\ntake the same options. So, wether you decide to mount this gem in a separate route\nfrom your main application's schema or you use our `GraphqlDevise::SchemaPlugin` to load\nthis gem's auth operation into your schema, these are the options you can provide as a hash.\n\n```ruby\n# Using the mount method in your config/routes.rb file\nmount_graphql_devise_for(User, {})\n\n# Providing options to a GraphqlDevise::ResourceLoader\nGraphqlDevise::ResourceLoader.new(User, {})\n```\n\n1. `at`: Route where the GraphQL schema will be mounted on the Rails server.\nIn [this example](#mounting-auth-schema-on-a-separate-route) your API will have\nthese two routes: `POST /api/v1/graphql_auth` and `GET /api/v1/graphql_auth`.\nIf this option is not specified, the schema will be mounted at `/graphql_auth`. **This option only works if you are using the mount method.**\n1. `operations`: Specifying this is optional. Here you can override default\nbehavior by specifying your own mutations and queries for every GraphQL operation.\nCheck available operations in this file [mutations](https://github.com/graphql-devise/graphql_devise/blob/b5985036e01ea064e43e457b4f0c8516f172471c/lib/graphql_devise/rails/routes.rb#L19)\nand [queries](https://github.com/graphql-devise/graphql_devise/blob/b5985036e01ea064e43e457b4f0c8516f172471c/lib/graphql_devise/rails/routes.rb#L41).\nAll mutations and queries are built so you can extend default behavior just by extending\nour default classes and yielding your customized code after calling `super`, example\n[here](https://github.com/graphql-devise/graphql_devise/blob/b5985036e01ea064e43e457b4f0c8516f172471c/spec/dummy/app/graphql/mutations/login.rb#L6).\n1. `authenticatable_type`: By default, the gem will add an `authenticatable` field to every mutation\nand an `authenticatable` type to every query. Gem will try to use `Types::\u003cmodel\u003eType` by\ndefault, so in our example you could define `Types::UserType` and every query and mutation\nwill use it. But, you can override this type with this option like in the example.\n1. `base_controller`: Specifying this is optional. By default the controller used to mount the route is\n`GraphqlDevise::ApplicationController` which inherits from `ActionController::API` or `ActionController::Base`\ndepending on the rails version of the main project. This option allows you to set the controller used as the parent of\nthe controller where the route will be mounted. This config is similar to `Devise`'s `base_controller` config but in\nthis case each route can have a different parent controller. **This option only works if you are using the mount method.**\n1. `skip`: An array of the operations that should not be available in the authentication schema. All these operations are\nsymbols and should belong to the list of available operations in the gem.\n1. `only`: An array of the operations that should be available in the authentication schema. The `skip` and `only` options are\nmutually exclusive, an error will be raised if you pass both to the mount method.\n1. `additional_mutations`: Here you can add as many mutations as you\nneed, for those features that don't fully match the provided default mutations and queries.\nYou need to provide a hash to this option, and\neach key will be the name of the mutation on the schema. Also, the value provided must be a valid mutation.\nThis is similar to what you can accomplish with\n[devise_scope](https://www.rubydoc.info/github/heartcombo/devise/master/ActionDispatch/Routing/Mapper%3Adevise_for).\n1. `additional_queries`: Here you can add as many queries as you need,\nfor those features that don't fully match the provided default mutations and queries.\nYou need to provide a hash to this option, and\neach key will be the name of the query on the schema. Also, the value provided must be a valid Resolver.\nThis is also similar to what you can accomplish with\n[devise_scope](https://www.rubydoc.info/github/heartcombo/devise/master/ActionDispatch/Routing/Mapper%3Adevise_for).\n\nAdditional mutations and queries will be added to the schema regardless\nof other options you might have specified like `skip` or `only`.\nAdditional queries and mutations is usually a good place for other\noperations on your schema that require no authentication (like sign_up).\nAlso by adding them through the mount method, your mutations and\nresolvers can inherit from our [base mutation](https://github.com/graphql-devise/graphql_devise/blob/master/app/graphql/graphql_devise/mutations/base.rb)\nor [base resolver](https://github.com/graphql-devise/graphql_devise/blob/master/app/graphql/graphql_devise/resolvers/base.rb)\nrespectively, to take advantage of some of the methods provided by devise\njust like with `devise_scope`\n\n### Available Operations\nThe following is a list of the symbols you can provide to the `operations`, `skip` and `only` options of the mount method:\n```ruby\n:login\n:logout\n:register\n:update_password_with_token\n:send_password_reset_with_token\n:resend_confirmation_with_token\n:confirm_registration_with_token\n```\n\n### Configuring Model\nJust like with Devise and DTA, you need to include a module in your authenticatable model,\nso with our example, your user model will have to look like this:\n```ruby\n# app/models/user.rb\n\nclass User \u003c ApplicationRecord\n  devise :database_authenticatable,\n         :registerable,\n         :recoverable,\n         :rememberable,\n         :trackable,\n         :lockable,\n         :validatable,\n         :confirmable\n\n  # including after calling the `devise` method is important.\n  include GraphqlDevise::Authenticatable\nend\n```\n\nThe install generator can do this for you if you specify the `user_class` option.\nSee [Installation](#installation) for details.\n\n### Email Reconfirmation\nWe want reconfirmable in this gem to work separately\nfrom DTA's or Devise (too much complexity in the model based on callbacks).\n\nEmail reconfirmation is supported just like in Devise and DTA, but we want reconfirmable\nin this gem to work on model basis instead of having a global configuration like in Devise.\n**For this reason Devise's global `reconfirmable` setting is ignored.**\n\nFor a resource to be considered reconfirmable it has to meet 2 conditions:\n1. Include the `:confirmable` module.\n1. Has an `unconfirmed_email` column in the resource's table.\n\nIn order to trigger the reconfirmation email in a reconfirmable resource, you simply need\nto call a different update method on your resource,`update_with_email`.\nWhen the resource is not reconfirmable or the email is not updated, this method behaves exactly\nthe same as ActiveRecord's `update`.\n\n#### Current flow\n`update_with_email` requires one additional attribute when email will change or an error\nwill be raised:\n\n- `confirmation_url`: The full url of your client application. The confirmation email will contain this url plus\na confirmation token. You need to call `confirmRegistrationWithToken` with the given token on\nyour client application.\n\nSo, it's up to you where you require confirmation of changing emails.\nHere's a demonstration on the method usage:\n```ruby\nuser.update_with_email(\n  name:             'New Name',\n  email:            'new@domain.com',\n  confirmation_url: 'https://google.com'\n)\n```\n\n### Customizing Email Templates\nThe approach of this gem is a bit different from DeviseTokenAuth. We have placed our templates in `app/views/graphql_devise/mailer`,\nso if you want to change them, place yours on the same dir structure on your Rails project. You can customize these two templates:\n1. `app/views/graphql_devise/mailer/confirmation_instructions.html.erb`\n1. `app/views/graphql_devise/mailer/reset_password_instructions.html.erb`\n\nThe main reason for this difference is just to make it easier to have both Standard `Devise` and this gem running at the same time.\nCheck [these files](app/views/graphql_devise/mailer) to see the available helper methods you can use in your views.\n\n### I18n\nGraphQL Devise supports locales. For example, the `graphql_devise.confirmations.send_instructions` locale setting supports the `%{email}` variable in case you would like to include it in the resend confirmation instructions for the user. Take a look at our [locale file](https://github.com/graphql-devise/graphql_devise/blob/master/config/locales/en.yml) to see all of the available messages.\n\nKeep in mind that if your app uses multiple locales, you should set the `I18n.locale` accordingly. You can learn how to do this [here](https://guides.rubyonrails.org/i18n.html).\n\n### Authenticating Controller Actions\nWhen mounting the operation is in you own schema instead of a dedicated one, you will need to authenticate users in your controllers, just like in DTA. There are 2 alternatives to accomplish this.\n\n#### Authenticate Resource in the Controller (\u003e= v0.15.0)\nThis authentication mechanism sets the resource by token in the controller, or it doesn't if credentials are invalid.\nYou simply need to pass the return value of our `gql_devise_context` method in the context of your\nGQL schema execution like this:\n\n```ruby\n# app/controllers/my_controller.rb\n\nclass MyController \u003c ApplicationController\n  include GraphqlDevise::SetUserByToken\n\n  def my_action\n    result = DummySchema.execute(params[:query], context: gql_devise_context(User))\n    render json: result unless performed?\n  end\nend\n```\n`gql_devise_context` receives as many models as you need to authenticate in the request, like this:\n```ruby\n# app/controllers/my_controller.rb\n\nclass MyController \u003c ApplicationController\n  include GraphqlDevise::SetUserByToken\n\n  def my_action\n    result = DummySchema.execute(params[:query], context: gql_devise_context(User, Admin))\n    render json: result unless performed?\n  end\nend\n```\nInternally in your own mutations and queries a key `current_resource` will be available in\nthe context if a resource was successfully authenticated or `nil` otherwise.\n\nKeep in mind that sending multiple models to the `gql_devise_context` method means that depending\non who makes the request, the context value `current_resource` might contain instances of the\ndifferent models you provided.\n\n**Note:** If for any reason you need more control over how users are authenticated, you can use the `authenticate_model`\nmethod anywhere in your controller. The method will return the authenticated resource or nil if authentication fails.\nIt will also set the instance variable `@resource` in the controller.\n\nPlease note that by using this mechanism your GQL schema will be in control of what queries are\nrestricted to authenticated users and you can only do this at the root level fields of your GQL\nschema. Configure the plugin as explained [here](#mounting-operations-into-your-own-schema)\nso this can work.\n\n##### Authentication Options\nWhether you setup authentications as a default in the plugin, or you do it at the field level,\nthese are the options you can use:\n1. **Any truthy value:** If `current_resource` is not `.present?`, query will return an authentication error.\n1. **A callable object:** Provided object will be called with `current_resource` as the only argument if `current_resource` is `.present?`. If return value of the callable object is false, query will return an authentication error.\n\nIn your main app's schema this is how you might specify if a field needs to be authenticated or not:\n```ruby\nmodule Types\n  class QueryType \u003c Types::BaseObject\n    # user field used the default set in the Plugin's initializer\n    field :user, resolver: Resolvers::UserShow\n    # this field will never require authentication\n    field :public_field, String, null: false, authenticate: false\n    # this field requires authentication\n    field :private_field, String, null: false, authenticate: true\n    # this field requires authenticated users to also be admins\n    field :admin_field, String, null: false, authenticate: -\u003e(user) { user.admin? }\n  end\nend\n```\n\n### Making Requests\nHere is a list of the available mutations and queries assuming your mounted model is `User`.\n\n#### Introspection query\nIf you are using the schema plugin, you can require authentication before doing an introspection query by modifying the `public_introspection` option of the plugin. Check the [plugin config section](#mounting-operations-into-your-own-schema) for more information.\n\n#### Mutations\n\nOperation | Description | Example\n:--- | :--- | :------------------:\nlogin | This mutation has a second field by default. `credentials` can be fetched directly on the mutation return type.\u003cbr\u003eCredentials are still returned in the headers of the response. | userLogin(email: String!, password: String!): UserLoginPayload |\nlogout | requires authentication headers. Deletes current session if successful. | userLogout: UserLogoutPayload |\nregister | The parameter `confirmUrl` is optional unless you are using the `confirmable` plugin from Devise in your `resource`'s model. If you have `confirmable` set up, you will have to provide it unless you have `config.default_confirm_success_url` set in `config/initializers/devise_token_auth.rb`. | userRegister(email: String!, password: String!, passwordConfirmation: String!, confirmUrl: String): UserRegisterPayload |\nsendPasswordResetWithToken | Sends an email to the provided address with a link to reset the password of the resource. First step of the most recently implemented password reset flow. | userSendPasswordResetWithToken(email: String!, redirectUrl: String!): UserSendPasswordResetWithTokenPayload |\nupdatePasswordWithToken | Uses a `resetPasswordToken` to update the password of a resource. Second and last step of the most recently implemented password reset flow. | userSendPasswordResetWithToken(resetPasswordToken: String!, password: String!, passwordConfirmation: String!): UserUpdatePasswordWithTokenPayload |\nresendConfirmationWithToken | The `UserResendConfirmationWithTokenPayload` will return a `message: String!` that can be used to notify a user what to do after the instructions were sent to them. Email will contain a link to the provided `confirmUrl` and a `confirmationToken` query param. | userResendConfirmationWithToken(email: String!, confirmUrl: String!): UserResendConfirmationWithTokenPayload |\n\n### Reset Password Flow\nThis gem supports two password recovery flows. The most recently implemented is preferred and\nrequires less steps. More detail on how it works can be found\n[here](docs/usage/reset_password_flow.md).\n\n### More Configuration Options\nAs mentioned in the introduction there are many configurations that will change how this gem behaves. You can change\nthis values on the initializer files generated by the installer.\n\n#### Devise Token Auth Initializer\nThe generated initializer file `config/initializers/devise_token_auth.rb` has all the available options documented\nas comments. You can also use\n**[DTA's docs](https://devise-token-auth.gitbook.io/devise-token-auth/config/initialization)** as a reference.\nIn this section the most important configurations will be highlighted.\n\n- **change_headers_on_each_request:** This configurations defaults to `false`. This will allow you to store the\n  credentials for as long as the token life_span permits. And you can send the same credentials in each request.\n  Setting this to `true` means that tokens will change on each request you make, and the new values will be returned\n  in the headers. So your client needs to handle this.\n- **batch_request_buffer_throttle:** When change_headers_on_each_request is set to true, you might still want your\n  credentials to be valid more than once as you might send parallel request. The duration you set here will\n  determine how long the same credentials work after the first request is received.\n- **token_lifespan:** This configuration takes a duration and you can set it to a value like\n  `1.month`, `2.weeks`, `1.hour`, etc.\n\n**Note:** Remember this gem adds a layer on top of DTA, so some configurations might not apply.\n\n#### Devise Initializer\nThe generated initializer file `config/initializers/devise_token_auth.rb` has all the available options documented\nas comments. You can also use\n**[Devise's docs](https://github.com/heartcombo/devise)** as a reference.\nIn this section the most important configurations will be highlighted.\n\n- **password_length:** You can change this value to validate password length on sign up and password update\n  (must enable the validatable module).\n- **mailer_sender:** Set it to a string with the sender's email address like `'support@example.com'`.\n- **case_insensitive_keys:** Setting a value like `[:email]` will make email field case insensitive on login, sign up, etc.\n- **email_regexp:** You can customize the regex that will validate the format of email addresses (must enable the validatable module).\n\n**Note:** Remember this gem adds a layer on top of Devise, so some configurations might not apply.\n\n### GraphQL 2.0 Support (\u003e= v1.0.0)\nThis gem now supports [GraphQL Ruby](https://github.com/rmosolgo/graphql-ruby) v2.\nThere's one manual step you need to take in order for this to work.\n\nYou need a custom `field_class` in your `MutationType` and `QueryType`. If you don't have one setup already, you can simply add the one\nthis gem provides, like this:\n\n```ruby\nmodule Types\n  class MutationType \u003c BaseObject\n    field_class GraphqlDevise::Types::BaseField\n  end\nend\n\nmodule Types\n  class QueryType \u003c Types::BaseObject\n    field_class GraphqlDevise::Types::BaseField\n  end\nend\n```\n\nIf you already have a `field_class` defined in any of your types, the only thing you need to do is add another `kwarg`\nto that class initializer (`authenticate`) and make that value available through an attribute reader.\n\nThe next example is this gem's implementation of a custom class, but you can implement your own however you see fit\nas long as you expose an `authenticate` public method with the value that was passed to the initializer.\n\n```ruby\nmodule GraphqlDevise\n  module Types\n    class BaseField \u003c GraphQL::Schema::Field\n      def initialize(*args, authenticate: nil, **kwargs, \u0026block)\n        @authenticate = authenticate\n        super(*args, **kwargs, \u0026block)\n      end\n\n      attr_reader :authenticate\n    end\n  end\nend\n```\n\n### GraphQL Interpreter\nGraphQL-Ruby `\u003e= 1.9.0` includes a new runtime module which you may use for your schema.\nEventually, it will become the default. You can read more about it\n[here](https://graphql-ruby.org/queries/interpreter).\n\nThis gem supports schemas using the interpreter and it is recommended as it introduces several\nimprovements which focus mainly on performance.\n\n### Using Alongside Standard Devise\nThe DeviseTokenAuth gem allows experimental use of the standard Devise gem to be configured at the same time, for more\ninformation you can check [this answer here](https://github.com/lynndylanhurley/devise_token_auth/blob/2a32f18ccce15638a74e72f6cfde5cf15a808d3f/docs/faq.md#can-i-use-this-gem-alongside-standard-devise).\n\nThis gem supports the same and should be easier to handle email templates due to the fact we don't override\nstandard Devise templates.\n\n## Changelog\nFull list of changes in [CHANGELOG.md](CHANGELOG.md)\n\n## Future Work\nWe will continue to improve the gem and add better docs.\n\n1. Make sure this gem can correctly work alongside DTA and the original Devise gem.\n1. Improve DOCS.\n1. Add support for unlockable and other Devise modules.\n1. Add feature specs for confirm account and reset password flows.\n\nWe will continue to build better docs for the gem after this first release, but in the mean time\nyou can use [our specs](spec/requests) to better understand how to use the gem.\nAlso, the [dummy app](spec/dummy) used in our specs will give you\na clear idea on how to configure the gem on your Rails application.\n\n## Buy Us a Coffee\nIf you'd like to support our work, you are welcome to do so!\n\n##### BTC\n```\nbc1qntlmyl24wuf6y5jyn2vg8kduss57dwtyrcflyq\n```\n##### ADA\n```\naddr1q8e8cjzutzptcrfgjgsjl3k4t4xy5ucrmkf2dmq9qn966q8saucty53avujfc9yu9vfk7266auhdx9fz4fsryzeagqds893nfw\n```\n\n## Contributing\n\nBug reports and pull requests are welcome on GitHub at https://github.com/graphql-devise/graphql_devise.\n\n## License\n\nThe gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).\n","funding_links":[],"categories":["Ruby"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgraphql-devise%2Fgraphql_devise","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgraphql-devise%2Fgraphql_devise","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgraphql-devise%2Fgraphql_devise/lists"}