### Example Installation Command Source: https://devise-token-auth.gitbook.io/devise-token-auth/config This is an example of how to run the installation generator with specific arguments for the User class and 'auth' mount path. ```bash rails g devise_token_auth:install User auth ``` -------------------------------- ### API Query Example - GET Request Source: https://devise-token-auth.gitbook.io/devise-token-auth/conceptual This example shows how to query the documentation dynamically by performing an HTTP GET request with the 'ask' query parameter. This is useful for retrieving specific information or clarifications not explicitly present on the page. ```http GET https://devise-token-auth.gitbook.io/devise-token-auth/conceptual.md?ask= ``` -------------------------------- ### Example GET Request for Dynamic Documentation Querying Source: https://devise-token-auth.gitbook.io/devise-token-auth/config/cors Demonstrates how to query the documentation dynamically by appending an 'ask' query parameter to the page URL. This is useful for retrieving specific information not explicitly stated on the page. ```http GET https://devise-token-auth.gitbook.io/devise-token-auth/config/cors.md?ask= ``` -------------------------------- ### Querying Documentation Example Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage/controller_methods To get additional information not explicitly present on a page, perform an HTTP GET request with the 'ask' query parameter. The question should be specific and self-contained. ```http GET https://devise-token-auth.gitbook.io/devise-token-auth/usage/controller_methods.md?ask= ``` -------------------------------- ### Install Gems with Bundler Source: https://devise-token-auth.gitbook.io/devise-token-auth After updating your Gemfile, run this command to install the new gem. ```bash bundle install ``` -------------------------------- ### Install Generator for New Model Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage/multiple_models Run this command to install devise-token-auth for a new model, such as 'Admin'. It creates the model and defines its authentication routes. ```bash rails g devise_token_auth:install Admin admin_auth ``` -------------------------------- ### Query Documentation with GET Request Source: https://devise-token-auth.gitbook.io/devise-token-auth/faq Demonstrates how to query the documentation dynamically by appending an 'ask' query parameter to the page URL. This is useful for getting specific answers or related documentation. ```http GET https://devise-token-auth.gitbook.io/devise-token-auth/faq.md?ask= ``` -------------------------------- ### Install Devise Token Auth (ActiveRecord) Source: https://devise-token-auth.gitbook.io/devise-token-auth/config Use this command to install the gem for ActiveRecord. Replace [USER_CLASS] with your user model name and [MOUNT_PATH] with the desired authentication route path. ```bash rails g devise_token_auth:install [USER_CLASS] [MOUNT_PATH] ``` -------------------------------- ### Query Documentation Dynamically Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage/multiple_models To get additional information not directly on the page, make an HTTP GET request with the `ask` query parameter. The response includes an answer and relevant documentation excerpts. ```http GET https://devise-token-auth.gitbook.io/devise-token-auth/usage/multiple_models.md?ask= ``` -------------------------------- ### Query Documentation Dynamically Source: https://devise-token-auth.gitbook.io/devise-token-auth/config/devise To get information not explicitly on the page, perform an HTTP GET request with the `ask` query parameter. The question should be specific and in natural language. ```http GET https://devise-token-auth.gitbook.io/devise-token-auth/config/devise.md?ask= ``` -------------------------------- ### Query Documentation via HTTP GET Source: https://devise-token-auth.gitbook.io/devise-token-auth/config/email_auth Perform an HTTP GET request with the 'ask' query parameter to dynamically query documentation. This is useful for retrieving specific information not explicitly present on the page. ```http GET https://devise-token-auth.gitbook.io/devise-token-auth/config/email_auth.md?ask= ``` -------------------------------- ### Query Documentation Dynamically Source: https://devise-token-auth.gitbook.io/devise-token-auth/config To get information not directly on the page, make a GET request to the page URL with an 'ask' query parameter containing your question. ```http GET https://devise-token-auth.gitbook.io/devise-token-auth/config.md?ask= ``` -------------------------------- ### Install Devise Token Auth (Mongoid) Source: https://devise-token-auth.gitbook.io/devise-token-auth/config Use this command to install the gem for Mongoid. Replace [USER_CLASS] with your user model name and [MOUNT_PATH] with the desired authentication route path. ```bash rails g devise_token_auth:install_mongoid [USER_CLASS] [MOUNT_PATH] ``` -------------------------------- ### Query Documentation with GET Request Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage/overrides Perform an HTTP GET request to the current page URL with the 'ask' query parameter to dynamically query the documentation. The question should be specific and in natural language. ```http GET https://devise-token-auth.gitbook.io/devise-token-auth/usage/overrides.md?ask= ``` -------------------------------- ### Query Documentation Dynamically Source: https://devise-token-auth.gitbook.io/devise-token-auth/conceptual/token-management Perform an HTTP GET request on the current page URL with the `ask` query parameter to get specific information. The question should be specific, self-contained, and in natural language. Use this mechanism when the answer is not explicitly present, you need clarification, or want to retrieve related documentation sections. ```http GET https://devise-token-auth.gitbook.io/devise-token-auth/conceptual/token-management.md?ask= ``` -------------------------------- ### Query Documentation via HTTP GET Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage Perform an HTTP GET request on the current page URL with the `ask` query parameter to retrieve additional information. The question should be specific and self-contained. ```http GET https://devise-token-auth.gitbook.io/devise-token-auth/usage.md?ask= ``` -------------------------------- ### Batch Request Example - JavaScript Source: https://devise-token-auth.gitbook.io/devise-token-auth/conceptual This example demonstrates how to make multiple concurrent requests to the API using $http in AngularJS. It shows handling responses from different resources. ```javascript $scope.getResourceData = function() { $http.get('/api/restricted_resource_1').success(function(resp) { // handle response $scope.resource1 = resp.data; }); $http.get('/api/restricted_resource_2').success(function(resp) { // handle response $scope.resource2 = resp.data; }); }; ``` -------------------------------- ### Perform HTTP GET Request with `ask` Parameter Source: https://devise-token-auth.gitbook.io/devise-token-auth/config/initialization Use this method to query the documentation dynamically when information is not directly available. The question should be specific and in natural language. ```http GET https://devise-token-auth.gitbook.io/devise-token-auth/config/initialization.md?ask= ``` -------------------------------- ### Authentication Headers Example Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage/controller_methods These headers are required for each authenticated request. They are typically provided in the response of a previous request. Libraries like ng-token-auth and jToker handle this automatically. ```text "access-token": "wwwww", "token-type": "Bearer", "client": "xxxxx", "expiry": "yyyyy", "uid": "zzzzz" ``` -------------------------------- ### Customize Sign Up and Account Update Parameters Source: https://devise-token-auth.gitbook.io/devise-token-auth/faq Override the DeviseTokenAuth RegistrationsController to permit additional parameters for sign-up and account updates. This example shows how to add a 'name' parameter. ```ruby class RegistrationsController < DeviseTokenAuth::RegistrationsController before_action :configure_permitted_parameters protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: %i(name)) devise_parameter_sanitizer.permit(:account_update, keys: %i(name)) end end ``` -------------------------------- ### Rspec: General Request Specs Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage/testing Generic examples for testing API authentication using Rspec. These cover scenarios like unauthorized access, successful login, and accessing restricted pages with valid tokens. ```ruby # spec/requests/authentication_test_spec.rb require 'rails_helper' include ActionController::RespondWith # The authentication header looks something like this: # {"access-token"=>"abcd1dMVlvW2BT67xIAS_A", "token-type"=>"Bearer", "client"=>"LSJEVZ7Pq6DX5LXvOWMq1w", "expiry"=>"1519086891", "uid"=>"darnell@konopelski.info"} describe 'Whether access is ocurring properly', type: :request do before(:each) do @current_user = FactoryBot.create(:user) @client = FactoryBot.create(:client) end context 'context: general authentication via API, ' do it "doesn't give you anything if you don't log in" do get api_client_path(@client) expect(response.status).to eq(401) end it 'gives you an authentication code if you are an existing user and you satisfy the password' do login # puts "#{response.headers.inspect}" # puts "#{response.body.inspect}" expect(response.has_header?('access-token')).to eq(true) end it 'gives you a status 200 on signing in ' do login expect(response.status).to eq(200) end it 'first get a token, then access a restricted page' do login auth_params = get_auth_params_from_login_response_headers(response) new_client = FactoryBot.create(:client) get api_find_client_by_name_path(new_client.name), headers: auth_params expect(response).to have_http_status(:success) end it 'deny access to a restricted page with an incorrect token' do login auth_params = get_auth_params_from_login_response_headers(response).tap do |h| h.each do |k, _v| if k == 'access-token' h[k] = '123' end end end new_client = FactoryBot.create(:client) get api_find_client_by_name_path(new_client.name), headers: auth_params expect(response).not_to have_http_status(:success) end end RSpec.shared_examples 'use authentication tokens of different ages' do |token_age, http_status| let(:vary_authentication_age) { token_age } it 'uses the given parameter' do expect(vary_authentication_age(token_age)).to have_http_status(http_status) end def vary_authentication_age(token_age) login auth_params = get_auth_params_from_login_response_headers(response) new_client = FactoryBot.create(:client) get api_find_client_by_name_path(new_client.name), headers: auth_params expect(response).to have_http_status(:success) allow(Time).to receive(:now).and_return(Time.now + token_age) get api_find_client_by_name_path(new_client.name), headers: auth_params response end end context 'test access tokens of varying ages' do include_examples 'use authentication tokens of different ages', 2.days, :success include_examples 'use authentication tokens of different ages', 5.years, :unauthorized end def login post api_user_session_path, params: { email: @current_user.email, password: 'password' }.to_json, headers: { 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' } end def get_auth_params_from_login_response_headers(response) client = response.headers['client'] token = response.headers['access-token'] expiry = response.headers['expiry'] token_type = response.headers['token-type'] uid = response.headers['uid'] auth_params = { 'access-token' => token, 'client' => client, 'uid' => uid, 'expiry' => expiry, 'token-type' => token_type } auth_params end end ``` -------------------------------- ### Configure rack-cors Middleware in Rails Application Source: https://devise-token-auth.gitbook.io/devise-token-auth/config/cors Configure the rack-cors middleware in your Rails application's `config/application.rb` file. This example allows requests from any origin, but it's recommended to whitelist specific domains for security. ```ruby # config/application.rb module YourApp class Application < Rails::Application config.middleware.use Rack::Cors do allow do origins '*' resource '*', headers: :any, expose: ['access-token', 'expiry', 'token-type', 'uid', 'client'], methods: [:get, :post, :options, :delete, :put] end end end end ``` -------------------------------- ### Link to Change Password in Email Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage/reset_password Modify the `reset_password_instructions.html.erb` file to point to the API endpoint for changing the password. This example shows how to construct the link with necessary parameters. ```erb <%= link_to 'Change my password', edit_api_v1_user_password_url(reset_password_token: @token, config: message['client-config'].to_s, redirect_url: message['redirect-url'].to_s) %> ``` -------------------------------- ### Configure Default Controller Overrides Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage/overrides Specify custom controllers for various Devise Token Auth functionalities by passing a hash to the `controllers` option when mounting the gem. This example shows the default settings. ```ruby mount_devise_token_auth_for 'User', at: 'auth', controllers: { confirmations: 'devise_token_auth/confirmations', passwords: 'devise_token_auth/passwords', omniauth_callbacks: 'devise_token_auth/omniauth_callbacks', registrations: 'devise_token_auth/registrations', sessions: 'devise_token_auth/sessions', token_validations: 'devise_token_auth/token_validations' } ``` -------------------------------- ### Create Authorization Header from Scratch in Ruby Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage/testing This Ruby method demonstrates how to manually create an authorization header for testing purposes. It requires FactoryBot to be set up and simulates a user login by creating a token and storing it in the user's token hash. Use this when you need to programmatically generate auth headers for request specs. ```ruby require 'rails_helper' include ActionController::RespondWith def create_auth_header_from_scratch # You need to set up factory bot to use this method @current_user = FactoryBot.create(:user) # create token token = DeviseTokenAuth::TokenFactory.create # store client + token in user's token hash @current_user.tokens[token.client] = { token: token.token_hash, expiry: token.expiry } # Now we have to pretend like an API user has already logged in. # (When the user actually logs in, the server will send the user # - assuming that the user has correctly and successfully logged in # - four auth headers. We are to then use these headers to access # things which are typically restricted # The following assumes that the user has received those headers # and that they are then using those headers to make a request new_auth_header = @current_user.build_auth_headers(token.token, token.client) puts 'This is the new auth header' puts new_auth_header.to_s # update response with the header that will be required by the next request puts response.headers.merge!(new_auth_header).to_s end ``` -------------------------------- ### Run Database Migrations Source: https://devise-token-auth.gitbook.io/devise-token-auth/config After the generator creates migration files for ActiveRecord, run this command to apply them to your database. Inspect the migration files first to add any necessary custom columns. ```bash rake db:migrate ``` -------------------------------- ### Create New Authentication Token and Headers Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage/model_concerns Call `create_new_auth_token` to generate a new authentication token and its associated metadata. An optional `client` argument can be provided; otherwise, a new one is generated. The method returns the authentication headers required for the client's next request. ```ruby # extract client from auth header client = request.headers['client'] # update token, generate updated auth headers for response new_auth_header = @resource.create_new_auth_token(client) # update response with the header that will be required by the next request response.headers.merge!(new_auth_header) ``` -------------------------------- ### Configure Devise Initializer Settings Source: https://devise-token-auth.gitbook.io/devise-token-auth/config/initialization Set the mailer sender address and configure ORM and navigational formats. Ensure the correct ORM is required. ```ruby Devise.setup do |config| # The e-mail address that mail will appear to be sent from # If absent, mail is sent from "please-change-me-at-config-initializers-devise@example.com" config.mailer_sender = "support@myapp.com" # ==> ORM configuration # Load and configure the ORM. Supports :active_record (default) and # :mongoid (bson_ext recommended) by default. Other ORMs may be # available as additional gems. require 'devise/orm/active_record' # If using rails-api, you may want to tell devise to not use ActionDispatch::Flash # middleware b/c rails-api does not include it. # See: https://stackoverflow.com/q/19600905/806956 config.navigational_formats = [:json] end ``` -------------------------------- ### OmniAuth Full Host Configuration for Development Source: https://devise-token-auth.gitbook.io/devise-token-auth/config/omniauth Set `OmniAuth.config.full_host` in `config/environments/development.rb` to resolve `redirect-uri-mismatch` errors when using Pow or xip.io. ```ruby # config/environments/development.rb # when using pow OmniAuth.config.full_host = "http://app-name.dev" # when using xip.io OmniAuth.config.full_host = "http://xxx.xxx.xxx.app-name.xip.io" ``` -------------------------------- ### Enable Standard Devise Support Source: https://devise-token-auth.gitbook.io/devise-token-auth/faq Configure Devise Token Auth to support standard Devise features by enabling this option. Ensure this initializer is set up correctly. ```ruby DeviseTokenAuth.setup do |config| config.enable_standard_devise_support = true end ``` -------------------------------- ### Build Authentication Headers for Response Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage/model_concerns Use `build_auth_headers` to construct the authentication headers that should be sent back to the client. This method requires the token and client identifier as arguments and returns a string representing the headers. ```ruby # create token token = DeviseTokenAuth::TokenFactory.create # store client + token in user's token hash @resource.tokens[token.client] = { token: token.token_hash, expiry: token.expiry } # generate auth headers for response new_auth_header = @resource.build_auth_headers(token.token, token.client) # update response with the header that will be required by the next request response.headers.merge!(new_auth_header) ``` -------------------------------- ### Configure OmniAuth Providers Source: https://devise-token-auth.gitbook.io/devise-token-auth/config/omniauth Configure OmniAuth providers in `config/initializers/omniauth.rb` using environment variables for keys and secrets. ```ruby # config/initializers/omniauth.rb Rails.application.config.middleware.use OmniAuth::Builder do provider :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET'], scope: 'email,profile' provider :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET'] provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'] provider :apple, ENV['APPLE_CLIENT_ID'], '', { scope: 'email name', team_id: ENV['APPLE_TEAM_ID'], key_id: ENV['APPLE_KEY'], pem: ENV['APPLE_PEM'] } end ``` -------------------------------- ### build_auth_headers Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage/model_concerns Generates the authentication header to be sent to the client with the next request. It accepts token and client as arguments and returns a string. ```APIDOC ## build_auth_headers ### Description Generates the auth header that should be sent to the client with the next request. ### Method `build_auth_headers(token, client)` ### Parameters #### Path Parameters - **token** (string) - Required - The authentication token. - **client** (string) - Required - The client identifier. ### Response #### Success Response (string) - **auth_headers** (string) - The authentication headers that should be sent to the client. ### Request Example ```ruby # create token token = DeviseTokenAuth::TokenFactory.create # store client + token in user's token hash @resource.tokens[token.client] = { token: token.token_hash, expiry: token.expiry } # generate auth headers for response new_auth_header = @resource.build_auth_headers(token.token, token.client) # update response with the header that will be required by the next request response.headers.merge!(new_auth_header) ``` ``` -------------------------------- ### Mount Devise Token Auth Routes Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage/routes Use this helper to mount the authentication routes. Specify the model class and an optional path prefix. The default path is '/auth'. ```ruby # config/routes.rb mount_devise_token_auth_for 'User', at: 'auth' ``` -------------------------------- ### Email Authentication (Sign In) Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage Authenticates a user via email and password. On successful login, it returns a JSON representation of the User model and includes `access-token` and `client` in the response headers. ```APIDOC ## POST /sign_in ### Description Email authentication. Requires **`email`** and **`password`** as params. This route will return a JSON representation of the `User` model on successful login along with the `access-token` and `client` in the header of the response. ### Method POST ### Endpoint /sign_in ### Parameters #### Request Body - **email** (string) - Required - The user's email address. - **password** (string) - Required - The user's password. ``` -------------------------------- ### Provider Authentication Endpoint Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage Set this route as the destination for client authentication. Ideally, this will happen in an external window or popup. ```APIDOC ## GET /:provider ### Description Set this route as the destination for client authentication. Ideally this will happen in an external window or popup. [Read more](#omniauth-authentication). ### Method GET ### Endpoint /:provider ``` -------------------------------- ### create_new_auth_token Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage/model_concerns Creates a new authentication token with necessary metadata. It accepts an optional client argument and returns the authentication headers. ```APIDOC ## create_new_auth_token ### Description Creates a new authentication token with all of the necessary metadata. Will generate a new `client` if none is provided. ### Method `create_new_auth_token(client = nil)` ### Parameters #### Path Parameters - **client** (string) - Optional - The client identifier. If not provided, a new one will be generated. ### Response #### Success Response (object) - **auth_headers** (object) - The authentication headers that should be sent by the client as an object. ### Request Example ```ruby # extract client from auth header client = request.headers['client'] # update token, generate updated auth headers for response new_auth_header = @resource.create_new_auth_token(client) # update response with the header that will be required by the next request response.headers.merge!(new_auth_header) ``` ``` -------------------------------- ### Add Gemfile Dependency Source: https://devise-token-auth.gitbook.io/devise-token-auth Add this line to your Gemfile to include the devise-token-auth gem. ```ruby gem 'devise_token_auth' ``` -------------------------------- ### Add Auth Headers to Request Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage/testing Pass the required authentication headers to your request. Use `resource.create_new_auth_token` to easily obtain these values. ```ruby request.headers.merge! resource.create_new_auth_token get '/api/authenticated_resource' # success ``` -------------------------------- ### Email Registration Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage Handles user registration via email. It requires email, password, and password confirmation. A confirmation email is sent, and upon clicking the link, the API redirects to the specified success URL. ```APIDOC ## POST / ### Description Email registration. Requires **`email`**, **`password`**, **`password_confirmation`**, and **`confirm_success_url`** params (this last one can be omitted if you have set `config.default_confirm_success_url` in `config/initializers/devise_token_auth.rb`). A verification email will be sent to the email address provided. Upon clicking the link in the confirmation email, the API will redirect to the URL specified in **`confirm_success_url`**. Accepted params can be customized using the [`devise_parameter_sanitizer`](https://github.com/plataformatec/devise#strong-parameters) system. ### Method POST ### Endpoint / ### Parameters #### Request Body - **email** (string) - Required - The user's email address. - **password** (string) - Required - The user's desired password. - **password_confirmation** (string) - Required - The user's desired password, confirmed. - **confirm_success_url** (string) - Optional - The URL to redirect to after email confirmation. ``` -------------------------------- ### Generate Email Templates Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage/overrides Copy the default Devise Token Auth email templates to your application to customize them. This command generates `reset_password_instructions.html.erb` and `confirmation_instructions.html.erb` in `app/views/devise/mailer/`. ```bash rails generate devise_token_auth:install_views ``` -------------------------------- ### Configure Admin Restricted Controllers Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage/multiple_models Use these methods in controllers to restrict access to administrators. Ensure `authenticate_admin!` is called as a `before_action`. ```ruby # before_action :authenticate_admin! # current_admin # admin_signed_in? ``` -------------------------------- ### Provider Callback Endpoint Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage Destination for the OAuth2 provider's callback URI. `postMessage` events containing the authenticated user's data will be sent back to the main client window from this page. ```APIDOC ## GET/POST /:provider/callback ### Description Destination for the oauth2 provider's callback uri. `postMessage` events containing the authenticated user's data will be sent back to the main client window from this page. [Read more](#omniauth-authentication). ### Method GET/POST ### Endpoint /:provider/callback ``` -------------------------------- ### Validate Token Endpoint Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage Use this route to validate tokens on return visits to the client. Requires `uid`, `client`, and `access-token` as params. These values should correspond to the columns in your `User` table of the same names. ```APIDOC ## GET /validate_token ### Description Use this route to validate tokens on return visits to the client. Requires **`uid`**, **`client`**, and **`access-token`** as params. These values should correspond to the columns in your `User` table of the same names. ### Method GET ### Endpoint /validate_token ### Parameters #### Query Parameters - **uid** (string) - Required - The user ID. - **client** (string) - Required - The client identifier. - **access-token** (string) - Required - The access token. ``` -------------------------------- ### Configure Rails Routes for Devise and Devise Token Auth Source: https://devise-token-auth.gitbook.io/devise-token-auth/faq Set up your Rails routes to accommodate both standard Devise and Devise Token Auth. The standard Devise routes should be defined before the token auth routes. ```ruby Rails.application.routes.draw do # standard devise routes available at /users # NOTE: make sure this comes first!!! devise_for :users # token auth routes available at /api/v1/auth namespace :api do scope :v1 do mount_devise_token_auth_for 'User', at: 'auth' end end end ``` -------------------------------- ### Password Reset Request Endpoint Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage Use this route to send a password reset confirmation email to users that registered by email. Accepts `email` and `redirect_url` as params. The user matching the `email` param will be sent instructions on how to reset their password. `redirect_url` is the URL to which the user will be redirected after visiting the link contained in the email. ```APIDOC ## POST /password ### Description Use this route to send a password reset confirmation email to users that registered by email. Accepts **`email`** and **`redirect_url`** as params. The user matching the `email` param will be sent instructions on how to reset their password. `redirect_url` is the url to which the user will be redirected after visiting the link contained in the email. ### Method POST ### Endpoint /password ### Parameters #### Request Body - **email** (string) - Required - The email address of the user. - **redirect_url** (string) - Optional - The URL to redirect to after password reset. ``` -------------------------------- ### Configure Mailcatcher for Development Source: https://devise-token-auth.gitbook.io/devise-token-auth/config/email_auth Set default URL options and delivery method for Action Mailer in the development environment to use mailcatcher for email testing. ```ruby # config/environments/development.rb Rails.application.configure do config.action_mailer.default_url_options = { host: 'your-dev-host.dev' } config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { address: 'your-dev-host.dev', port: 1025 } end ``` -------------------------------- ### Add rack-cors Gem to Gemfile Source: https://devise-token-auth.gitbook.io/devise-token-auth/config/cors Include the rack-cors gem in your Gemfile to enable CORS functionality. This is the first step in configuring cross-origin requests. ```ruby # gemfile gem 'rack-cors', :require => 'rack/cors' ``` -------------------------------- ### API Request for Password Reset Initiation Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage/reset_password Initiates the password reset process by sending a POST request to the `/auth/password` endpoint with the user's email and a redirect URL. ```http POST /auth/password Parameters: email, redirect_url ``` -------------------------------- ### Define Routes for Multiple Models Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage/multiple_models Configure routes to handle multiple devise mappings. Subsequent mappings require routes defined within a `devise_scope` block to specify which model to use for authorization. ```ruby Rails.application.routes.draw do # when using multiple models, controllers will default to the first available # devise mapping. routes for subsequent devise mappings will need to defined # within a `devise_scope` block # define :users as the first devise mapping: mount_devise_token_auth_for 'User', at: 'auth' # define :admins as the second devise mapping. routes using this class will # need to be defined within a devise_scope as shown below mount_devise_token_auth_for "Admin", at: 'admin_auth' # this route will authorize requests using the User class get 'demo/members_only', to: 'demo#members_only' # routes within this block will authorize requests using the Admin class devise_scope :admin do get 'demo/admins_only', to: 'demo#admins_only' end end ``` -------------------------------- ### Add New Fields to User Model Migration Source: https://devise-token-auth.gitbook.io/devise-token-auth/faq Use this Ruby code to create a migration for adding new fields like provider, uid, and tokens to your User model. It includes logic to update existing users and set up necessary indexes. ```ruby # create migration by running a command like this (where `User` is your USER_CLASS table): # `rails g migration AddTokensToUsers provider:string uid:string tokens:text` def up add_column :users, :provider, :string, null: false, default: 'email' add_column :users, :uid, :string, null: false, default: '' add_column :users, :tokens, :text # if your existing User model does not have an existing **encrypted_password** column uncomment below line. # add_column :users, :encrypted_password, :string, null: false, default: '' # if your existing User model does not have an existing **allow_password_change** column uncomment below line. # add_column :users, :allow_password_change, :boolean, default: false # the following will update your models so that when you run your migration # updates the user table immediately with the above defaults User.reset_column_information # finds all existing users and updates them. # if you change the default values above you'll also have to change them here below: User.find_each do |user| user.uid = user.email user.provider = 'email' user.save! end # to speed up lookups to these columns: add_index :users, [:uid, :provider], unique: true end def down # if you added **encrypted_password** above, add here to successfully rollback # if you added **allow_password_change** above, add here to successfully rollback remove_columns :users, :provider, :uid, :tokens end ``` -------------------------------- ### Group Access Methods Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage/multiple_models When using group authentication, these methods become available for managing access and retrieving the current member across different user types. ```ruby # before_action: :authenticate_member! # current_member # member_signed_in? ``` -------------------------------- ### Base Application Controller Source: https://devise-token-auth.gitbook.io/devise-token-auth/faq The base application controller for your Rails application. This file can be used to configure general settings like CSRF protection, which can then be optionally skipped in API-specific controllers. ```ruby class ApplicationController < ActionController::Base protect_from_forgery with: :exception end ``` -------------------------------- ### Separate Application Controllers for API and ActiveAdmin Source: https://devise-token-auth.gitbook.io/devise-token-auth/faq Implement separate application controllers for API routes and ActiveAdmin to avoid conflicts when using DeviseTokenAuth::Concerns::SetUserByToken in the main ApplicationController. ```ruby # app/controllers/api_controller.rb # API routes extend from this controller class ApiController < ActionController::Base include DeviseTokenAuth::Concerns::SetUserByToken end # app/controllers/application_controller.rb # leave this for ActiveAdmin, and any other non-api routes class ApplicationController < ActionController::Base end ``` -------------------------------- ### Account Updates Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage Updates an existing user's account settings. By default, it accepts `password` and `password_confirmation`. The behavior regarding `current_password` checking depends on the `config.check_current_password_before_update` setting. ```APIDOC ## PUT / ### Description Account updates. This route will update an existing user's account settings. The default accepted params are **`password`** and **`password_confirmation`**, but this can be customized using the [`devise_parameter_sanitizer`](https://github.com/plataformatec/devise#strong-parameters) system. If **`config.check_current_password_before_update`** is set to `:attributes` the **`current_password`** param is checked before any update, if it is set to `:password` the **`current_password`** param is checked only if the request updates user password. ### Method PUT ### Endpoint / ### Parameters #### Request Body - **password** (string) - Optional - The new password for the user. - **password_confirmation** (string) - Optional - The new password, confirmed. - **current_password** (string) - Optional - The user's current password, required under certain configuration settings. #### Request Headers - **uid** (string) - Required - The user's unique identifier. - **access-token** (string) - Required - The user's authentication token. - **client** (string) - Required - The client identifier. ``` -------------------------------- ### Password Reset Verification Endpoint Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage Verify user by password reset token. This route is the destination URL for password reset confirmation. This route must contain `reset_password_token` and `redirect_url` params. These values will be set automatically by the confirmation email that is generated by the password reset request. ```APIDOC ## GET /password/edit ### Description Verify user by password reset token. This route is the destination URL for password reset confirmation. This route must contain **`reset_password_token`** and **`redirect_url`** params. These values will be set automatically by the confirmation email that is generated by the password reset request. ### Method GET ### Endpoint /password/edit ### Parameters #### Query Parameters - **reset_password_token** (string) - Required - The password reset token. - **redirect_url** (string) - Required - The URL to redirect to after verification. ``` -------------------------------- ### Extend Controller Behavior with Blocks Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage/overrides Add custom logic to existing controller actions without rewriting the entire action. Inherit from the Devise Token Auth controller and pass a block to `super` to execute custom code before the default success response. ```ruby class Custom::RegistrationsController < DeviseTokenAuth::RegistrationsController def create super do |resource| resource.do_something(extra) end end end ``` -------------------------------- ### Add OmniAuth Provider Gems Source: https://devise-token-auth.gitbook.io/devise-token-auth/config/omniauth Add the necessary OmniAuth provider gems to your Gemfile for authentication. ```ruby gem 'omniauth-github' gem 'omniauth-facebook' gem 'omniauth-google-oauth2' gem 'omniauth-apple' ``` -------------------------------- ### Disable Standard Devise Support in Initializer Source: https://devise-token-auth.gitbook.io/devise-token-auth/faq Ensure that `enable_standard_devise_support` is commented out or set to `false` in the Devise Token Auth initializer when using separate application controllers. ```ruby # config.enable_standard_devise_support = false ``` -------------------------------- ### valid_token? Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage/model_concerns Checks if an authentication token is valid. It accepts a token and client as arguments and returns a boolean. ```APIDOC ## valid_token? ### Description Checks if an authentication token is valid. ### Method `valid_token?(token, client)` ### Parameters #### Path Parameters - **token** (string) - Required - The authentication token to validate. - **client** (string) - Required - The client identifier associated with the token. ### Response #### Success Response (boolean) - **true** - if the token is valid. - **false** - if the token is invalid. ### Request Example ```ruby # extract token + client from auth header client = request.headers['client'] token = request.headers['access-token'] @resource.valid_token?(token, client) ``` ``` -------------------------------- ### Check if Authentication Token is Valid Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage/model_concerns Use `valid_token?` to verify if a given authentication token and client identifier are valid for the resource. This method accepts the token and client as arguments and returns a boolean. ```ruby # extract token + client from auth header client = request.headers['client'] token = request.headers['access-token'] @resource.valid_token?(token, client) ``` -------------------------------- ### Password Update Endpoint Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage Use this route to change users' passwords. Requires `password` and `password_confirmation` as params. This route is only valid for users that registered by email (OAuth2 users will receive an error). It also checks `current_password` if `config.check_current_password_before_update` is not set to `false` (disabled by default). ```APIDOC ## PUT /password ### Description Use this route to change users' passwords. Requires **`password`** and **`password_confirmation`** as params. This route is only valid for users that registered by email (OAuth2 users will receive an error). It also checks **`current_password`** if **`config.check_current_password_before_update`** is not set `false` (disabled by default). ### Method PUT ### Endpoint /password ### Parameters #### Request Body - **password** (string) - Required - The new password. - **password_confirmation** (string) - Required - The confirmation of the new password. - **current_password** (string) - Optional - The user's current password (if `config.check_current_password_before_update` is enabled). ``` -------------------------------- ### API Child Application Controller for Devise Token Auth Source: https://devise-token-auth.gitbook.io/devise-token-auth/faq Define a child application controller for your API endpoints that includes Devise Token Auth concerns. This controller inherits from the base application controller and sets up user authentication by token. ```ruby module Api module V1 class ApplicationController < ::ApplicationController skip_before_action :verify_authenticity_token include DeviseTokenAuth::Concerns::SetUserByToken end end end ``` -------------------------------- ### Angular.js Client Configuration for OmniAuth Source: https://devise-token-auth.gitbook.io/devise-token-auth/config/omniauth Configure the Angular.js client to authenticate with OmniAuth providers, noting the difference in `authProviderPaths` compared to server-side settings. ```javascript angular.module('myApp', ['ng-token-auth']) .config(function($authProvider) { $authProvider.configure({ apiUrl: 'https://api.example.com' authProviderPaths: { github: '/auth/github' // <-- note that this is different than what was set with github } }); }); ``` -------------------------------- ### Account Deletion Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage Deletes a user account. This operation requires authentication via `uid`, `access-token`, and `client` headers. ```APIDOC ## DELETE / ### Description Account deletion. This route will destroy users identified by their **`uid`**, **`access-token`** and **`client`** headers. ### Method DELETE ### Endpoint / ### Parameters #### Request Headers - **uid** (string) - Required - The user's unique identifier. - **access-token** (string) - Required - The user's authentication token. - **client** (string) - Required - The client identifier. ``` -------------------------------- ### Limit Access to Authenticated Users Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage/controller_methods Use the `before_action :authenticate_user!` filter to ensure that only authenticated users can access specific controller actions. This will return a 401 error if no user is signed in. ```ruby class TestController < ApplicationController before_action :authenticate_user! def members_only render json: { data: { message: "Welcome #{current_user.name}", user: current_user } }, status: 200 end end ``` -------------------------------- ### API Request to Update Password Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage/reset_password Updates the user's password after they have verified their token. This PUT request to `/auth/password` requires password parameters and authentication headers. ```http PUT /auth/password Parameters: password, password_confirmation Headers: uid, client, access-token ``` -------------------------------- ### jToker Client Configuration for OmniAuth Source: https://devise-token-auth.gitbook.io/devise-token-auth/config/omniauth Configure jToker for OmniAuth authentication, specifying the API URL and provider paths. ```javascript $.auth.configure({ apiUrl: 'https://api.example.com', authProviderPaths: { github: '/auth/github' // <-- note that this is different than what was set with github } }); ``` -------------------------------- ### Resend Confirmation Email Endpoint Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage Re-sends confirmation email. Requires `email` and accepts `redirect_url` params (this last one can be omitted if you have set `config.default_confirm_success_url` in `config/initializers/devise_token_auth.rb`). ```APIDOC ## POST /confirmation ### Description Re-sends confirmation email. Requires **`email`** and accepts **`redirect_url`** params (this last one can be omitted if you have set `config.default_confirm_success_url` in `config/initializers/devise_token_auth.rb`). ### Method POST ### Endpoint /confirmation ### Parameters #### Request Body - **email** (string) - Required - The email address of the user. - **redirect_url** (string) - Optional - The URL to redirect to after confirmation success. ``` -------------------------------- ### Sign Out Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage Ends the user's current session by invalidating their authentication token. Requires `uid`, `client`, and `access-token` in the request headers. ```APIDOC ## DELETE /sign_out ### Description Use this route to end the user's current session. This route will invalidate the user's authentication token. You must pass in **`uid`**, **`client`**, and **`access-token`** in the request headers. ### Method DELETE ### Endpoint /sign_out ### Parameters #### Request Headers - **uid** (string) - Required - The user's unique identifier. - **access-token** (string) - Required - The user's authentication token. - **client** (string) - Required - The client identifier. ``` -------------------------------- ### Admin Child Application Controller for Standard Devise Source: https://devise-token-auth.gitbook.io/devise-token-auth/faq Define a child application controller for your admin or full-stack sections that uses standard Devise authentication. This controller inherits from the base application controller and enforces admin authentication. ```ruby module Admin class ApplicationController < ::ApplicationController before_action :authenticate_admin! end end ``` -------------------------------- ### Include SetUserByToken Concern in ApplicationController Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage/controller_methods Include the `DeviseTokenAuth::Concerns::SetUserByToken` concern in your `ApplicationController` to make its methods available to all controllers in your application. ```ruby class ApplicationController < ActionController::Base include DeviseTokenAuth::Concerns::SetUserByToken end ``` -------------------------------- ### Override TokenValidationsController validate_token Action Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage/overrides Customize the response of the `validate_token` action by creating a new controller that inherits from `DeviseTokenAuth::TokenValidationsController` and overriding the `validate_token` method. Ensure your routes file points to the custom controller. ```ruby # config/routes.rb Rails.application.routes.draw do ... mount_devise_token_auth_for 'User', at: 'auth', controllers: { token_validations: 'overrides/token_validations' } end # app/controllers/overrides/token_validations_controller.rb module Overrides class TokenValidationsController < DeviseTokenAuth::TokenValidationsController def validate_token # @resource will have been set by set_user_by_token concern if @resource render json: { data: @resource.as_json(methods: :calculate_operating_thetan) } else render json: { success: false, errors: ["Invalid login credentials"] }, status: 401 end end end end ``` -------------------------------- ### Configure Devise Mail Sender Source: https://devise-token-auth.gitbook.io/devise-token-auth/config/email_auth Set a custom email address to be used as the sender for Devise emails if you are not using a custom mailer class. ```ruby # config/initializers/devise.rb Devise.setup do |config| config.mailer_sender = "example@example.com" end ``` -------------------------------- ### Customize Devise Email Subject Lines Source: https://devise-token-auth.gitbook.io/devise-token-auth/config/devise Override default email subject lines for confirmation and password reset instructions by defining custom verbiage in `config/locales/devise.en.yml`. ```yaml en: devise: mailer: confirmation_instructions: subject: "Please confirm your e-mail address" reset_password_instructions: subject: "Reset password request" ``` -------------------------------- ### Group Authentication for Multiple User Types Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage/multiple_models Define a group to control access for multiple user types simultaneously. The `devise_token_auth_group` method specifies which models are included in the group. ```ruby class DemoGroupController < ApplicationController devise_token_auth_group :member, contains: [:user, :admin] before_action :authenticate_member! def members_only render json: { data: { message: "Welcome #{current_member.name}", user: current_member } }, status: 200 end end ``` -------------------------------- ### Disable OAuth Authentication and Routes Source: https://devise-token-auth.gitbook.io/devise-token-auth/usage/excluding_models To disable OAuth, first instruct the model not to include the `omniauthable` module in the `devise` block. Then, tell the route helper to `skip` mounting the `omniauth_callbacks` controller. ```ruby class User < ActiveRecord::Base # notice that :omniauthable is not included in this block devise :database_authenticatable, :confirmable, :recoverable, :trackable, :validatable, :registerable include DeviseTokenAuth::Concerns::User end ``` ```ruby Rails.application.routes.draw do # config/routes.rb mount_devise_token_auth_for 'User', at: 'auth', skip: [:omniauth_callbacks] end ```