• Stars
    star
    156
  • Rank 239,589 (Top 5 %)
  • Language
    Ruby
  • License
    MIT License
  • Created almost 2 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

The devise-api gem is a convenient way to add authentication to your Ruby on Rails application using the devise gem. It provides support for access tokens and refresh tokens, which allow you to authenticate API requests and keep the user's session active for a longer period of time on the client side

Gem Version test rubocop Ruby Style Guide Ruby Version

Devise API

The devise-api gem is a convenient way to add authentication to your Ruby on Rails application using the devise gem. It provides support for access tokens and refresh tokens, which allow you to authenticate API requests and keep the user's session active for a longer period of time on the client side. It can be installed by adding the gem to your Gemfile, running migrations, and adding the :api module to your devise model. The gem is fully configurable, allowing you to set things like token expiration times and token generators.

Here's how it works:

  • When a user logs in to your Rails application, the devise-api gem generates an access token and a refresh token.
  • The access token is included in the API request headers and is used to authenticate the user on each subsequent request.
  • The refresh token is stored on the client side (e.g. in a browser cookie or on a mobile device) and is used to obtain a new access token when the original access token expires.
  • This allows the user to remain logged in and make API requests without having to constantly re-enter their login credentials.

Overall, the devise-api gem is a useful tool for adding secure authentication to your Ruby on Rails application.

Installation

Install the gem and add to the application's Gemfile by executing:

$ bundle add devise-api

Or add the following line to the application's Gemfile:

gem 'devise-api', github: 'nejdetkadir/devise-api', branch: 'main'

If bundler is not being used to manage dependencies, install the gem by executing:

gem install devise-api

After that, you need to generate relevant migrations and locales by executing:

$ rails generate devise_api:install

This will introduce two changes:

  • Locale files in config/locales/devise_api.en.yml
  • Migration file in db/migrate to create devise api tokens table

Now you're ready to run the migrations:

$ rails db:migrate

Finally, you need to add :api module to your devise model. For example:

class User < ApplicationRecord
  devise :database_authenticatable, 
         :registerable, 
         :recoverable,
         :rememberable,
         :validatable,
         :api # <--- Add this module
end

Your user model is now ready to use devise-api gem. It will draw routes for token authenticatable and token refreshable.

Prefix Verb URI Pattern Controller#Action
revoke_user_tokens POST /users/tokens/revoke devise/api/tokens#revoke
refresh_user_tokens POST /users/tokens/refresh devise/api/tokens#refresh
sign_up_user_tokens POST /users/tokens/sign_up devise/api/tokens#sign_up
sign_in_user_tokens POST /users/tokens/sign_in devise/api/tokens#sign_in
info_user_tokens GET /users/tokens/info devise/api/tokens#info

You can look up the example requests.

Configuration

devise-api is a full configurable gem. You can configure it to your needs. Here is a basic usage example:

# config/initializers/devise.rb
Devise.setup do |config|
  config.api.configure do |api|
    # Access Token
    api.access_token.expires_in = 1.hour
    api.access_token.expires_in_infinite = ->(_resource_owner) { false }
    api.access_token.generator = ->(_resource_owner) { Devise.friendly_token(60) }


    # Refresh Token
    api.refresh_token.enabled = true
    api.refresh_token.expires_in = 1.week
    api.refresh_token.generator = ->(_resource_owner) { Devise.friendly_token(60) }
    api.refresh_token.expires_in_infinite = ->(_resource_owner) { false }

    # Sign up
    api.sign_up.enabled = true
    api.sign_up.extra_fields = []

    # Authorization
    api.authorization.key = 'Authorization'
    api.authorization.scheme = 'Bearer'
    api.authorization.location = :both # :header or :params or :both
    api.authorization.params_key = 'access_token'


    # Base classes
    api.base_token_model = 'Devise::Api::Token'
    api.base_controller = '::DeviseController'


    # After successful callbacks
    api.after_successful_sign_in = ->(_resource_owner, _token, _request) { }
    api.after_successful_sign_up = ->(_resource_owner, _token, _request) { }
    api.after_successful_refresh = ->(_resource_owner, _token, _request) { }
    api.after_successful_revoke = ->(_resource_owner, _token, _request) { }


    # Before callbacks
    api.before_sign_in = ->(_params, _request, _resource_class) { }
    api.before_sign_up = ->(_params, _request, _resource_class) { }
    api.before_refresh = ->(_params, _request, _resource_class) { }
    api.before_revoke = ->(_params, _request, _resource_class) { }
  end
end

Routes

You can configure the tokens routes with the orginally devise_for method. For example:

# config/routes.rb
Rails.application.routes.draw do
  devise_for :customers, 
             controllers: { tokens: 'customers/api/tokens' }
end

Usage

devise-api module works with :lockable and :confirmable modules. It also works with :trackable module.

devise-api provides a set of controllers and helpers to help you implement authentication in your Rails application. Here's a quick overview of the available controllers and helpers:

  • Devise::Api::TokensController - This controller is responsible for generating access tokens and refresh tokens. It also provides actions for refreshing access tokens and revoking refresh tokens.

  • Devise::Api::Token - This model is responsible for storing access tokens and refresh tokens in the database.

  • Devise::Api::Responses::ErrorResponse - This class is responsible for generating error responses. It also provides a set of error types and helpers to help you implement error responses in your Rails application.

  • Devise::Api::Responses::TokenResponse - This class is responsible for generating token responses. It also provides actions for generating access tokens and refresh tokens for each action.

Overriding Responses

You can prepend your decorators to the response classes to override the default responses. For example:

# app/lib/devise/api/responses/token_response_decorator.rb
module Devise::Api::Responses::TokenResponseDecorator
  def body
    return default_body.merge({ roles: resource_owner.roles })
  end
end

Then you need to load and prepend your decorator to the response class. For example:

# config/initializers/devise.rb
require 'devise/api/responses/token_response_decorator' # Either do this or autoload the lib directory

Devise.setup do |config|
end

Devise::Api::Responses::TokenResponse.prepend Devise::Api::Responses::TokenResponseDecorator

Using helpers

devise-api provides a set of helpers to help you implement authentication in your Rails application. Here's a quick overview of the available helpers:

Example:

# app/controllers/api/v1/orders_controller.rb
class Api::V1::OrdersController < YourBaseController
  skip_before_action :verify_authenticity_token, raise: false  
  before_action :authenticate_devise_api_token!

  def index
    render json: current_devise_api_user.orders, status: :ok
  end

  def show
    devise_api_token = current_devise_api_token
    render json: devise_api_token.resource_owner.orders.find(params[:id]), status: :ok
  end
end

Using devise base services

devise-api provides a set of base services to help you implement authentication in your Rails application. Here's a quick overview of the available services:

You can create a service by inheriting the Devise::Api::BaseService class. For example:

# app/services/devise/api/tokens_service/v2/create.rb
module Devise::Api::TokensService::V2
  class Create < Devise::Api::BaseService
    option :params, type: Types::Hash, reader: true
    option :resource_class, type: Types::Class, reader: true

    def call
      ...

      Success(resource)
    end
  end
end

Then you can call the service in your controller. For example:

# app/controllers/api/v1/tokens_controller.rb
class Api::V1::TokensController < YourBaseController
  skip_before_action :verify_authenticity_token, raise: false

  def create
    service = Devise::Api::TokensService::V2::Create.call(params: params, resource_class: Customer || resource_class)
    if service.success?
      render json: service.success, status: :created
    else
      render json: service.failure, status: :unprocessable_entity
    end
  end
end

Example API requests

Sign in

curl --location --request POST 'http://127.0.0.1:3000/users/tokens/sign_in' \
--header 'Content-Type: application/json' \
--data-raw '{
    "email": "[email protected]",
    "password": "123456"
}'

Sign up

curl --location --request POST 'http://127.0.0.1:3000/users/tokens/sign_up' \
--header 'Content-Type: application/json' \
--data-raw '{
    "email": "[email protected]",
    "password": "123456"
}'

Refresh token

curl --location --request POST 'http://127.0.0.1:3000/users/tokens/refresh' \
--header 'Authorization: Bearer <refresh_token>'

Revoke

curl --location --request POST 'http://127.0.0.1:3000/users/tokens/revoke' \
--header 'Authorization: Bearer <access_token>'

Info

curl --location --request GET 'http://127.0.0.1:3000/users/tokens/info' \
--header 'Authorization: Bearer <access_token>'

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake rspec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To 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 the created tag, and push the .gem file to rubygems.org.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/nejdetkadir/devise-api. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the code of conduct.

License

The gem is available as open source under the terms of the MIT License.

Code of Conduct

Everyone interacting in the Devise::Api project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.

More Repositories

1

followability

Implements the social network followable functionality for your Active Record models
Ruby
62
star
2

sidekiq-aws-sqs

Sidekiq extension that provides an easy way to poll and process messages from AWS SQS (Simple Queue Service) queues within a Sidekiq worker
Ruby
25
star
3

phlex-heroicons

Heroicons extension for Phlex
Ruby
24
star
4

il-ilce-semt-mahalleler

Türkiye'de bulunan tüm il, ilçe, semt ve mahalleler.
21
star
5

dry-validation-rails

Rails plugin for using dry-validation and dry-schema gems instead of your Active Record Validations
Ruby
19
star
6

il-ilce-mahalleler

Türkiye'de bulunan tüm il, ilçe, semt ve mahalleler.
17
star
7

devise-doorkeeper-starter

An app that showcases how to use Devise with Doorkeeper (OAuth 2 provider)
Ruby
14
star
8

google-keep-api

Google Keep API with Ruby on Rails
Ruby
12
star
9

render-ruby

Ruby bindings for Render API V1
Ruby
9
star
10

safe_poller

SafePoller is a Ruby gem that provides a safe and reliable way to perform periodic polling operations in multi-threaded environments
Ruby
9
star
11

turkish-taboo-words

It is includes turkish taboo words with different formats as JSON, XML and YAML (500+ words)
9
star
12

nuxt-mongodb-crud

MongoDB CRUD operations with NuxtJS
Vue
8
star
13

dev-ruby

Ruby bindings for dev.to API
Ruby
7
star
14

spotify-api-usage

An app that showcases how to use Spotify API with VueJS
Vue
6
star
15

nuxt-shopping-cart

An app that showcases how to use Express and Session with NuxtJS for learning it
Vue
6
star
16

who-is-vampire-discord-bot

This bot created with NodeJS
JavaScript
5
star
17

discord-music-player

Sample music player bot for Discord (just 90 lines)
JavaScript
5
star
18

universities-in-turkey-api

Universities in Turkey. It is an unofficial API. Official source : www.osym.gov.tr
Ruby
5
star
19

rails-6-api-boilerplate

A starter template for Ruby on Rails API
Ruby
3
star
20

verifykit

The easiest and most complete unofficial VerifyKit API client for Ruby.
Ruby
3
star
21

i18ngo

Simple internationalization library for Golang
Go
3
star
22

tabulon

Tabulon is a mobile game that is a clone of the taboo game. The game is played in teams of two or more. The goal of the game is to get your team to guess the word on the card without using the taboo words.
TypeScript
3
star
23

statemachine

A lightweight, easy-to-use state machine library for Go
Go
3
star
24

rails-6-boilerplate

A starter template for Ruby on Rails 6
Ruby
2
star
25

turkiye-il-ilce

JSON dosyasından verileri çekerek JS ile dinamik il - ilçe selectbox.
HTML
2
star
26

udemy-ilk-uygulamam

Udemy - Temelden İleri Seviyeye Ruby on Rails Framework'ünü öğrenin
Ruby
2
star
27

nodejs-book-api

NodeJS simple books restful API (used MongoDB)
JavaScript
2
star
28

rails-routes-prettier

The rails-routes-prettier gem makes it easy to view the routes in your Rails application
Ruby
2
star
29

devise-jwt-starter

It is a starter for Ruby on Rails API application with devise gem with devise-jwt extension.
Ruby
2
star
30

rails-messenger

Sample messenger application, created with Ruby on Rails
Ruby
2
star
31

tr-cities-api

All cities, towns, districts and quarters in Turkey (no authentication needed)
Ruby
2
star
32

dictionary

My dictionary project for midterm exam
Java
1
star
33

rories-api

Movies API with Ruby on Rails API
Ruby
1
star
34

letgo-clone

It is a clone application of letgo.com
Ruby
1
star
35

hunt-monster

This is a simple game for learning VueJS
JavaScript
1
star
36

php-foursquare-parser

Simple foursquare parser for development API or application
PHP
1
star
37

railstagramm

It is a clone application of instagram, created with Ruby on Rails
Ruby
1
star
38

radiobtn-with-images

Sample dynamic radio button with images in VueJS
Vue
1
star
39

survivor-bird

Basic survivor game for android.
Java
1
star
40

btc-turk

Ruby wrapper for BtcTurk API
Ruby
1
star
41

learn-ruby

My Ruby exercise for learn Ruby programming
Ruby
1
star
42

simple-rails-crud

For learning the fundamentals of Ruby on Rails. Used PostgreSQL and made CRUD (Create - Read - Update - Delete) processes.
Ruby
1
star
43

online-budget-calculator

Simple budget calculator
JavaScript
1
star
44

fakest

Fakest is a fake student for online lessons
Python
1
star
45

json-server-clone

Create a server and serve content of your json files in localhost
JavaScript
1
star
46

vuelidate-sign-up-form

How to use vuelidate in sign up form
Vue
1
star
47

quiz-game

JavaScript quiz game from console for learning it.
JavaScript
1
star
48

articles-crud-app

Sample CRUD operations with ReactJS & Typescript for learning
TypeScript
1
star
49

spring-boot-h2database

Basic application with Spring boot for using h2database.
Java
1
star
50

stationery-ms

Stationery managment system with VueJS and Firebase
Vue
1
star
51

password-saver

You can save your important password in your local application with VueJS for learning it.
Vue
1
star
52

covid-dictionary

Sample Turkish Covid-19 dictionary with Flutter
Dart
1
star
53

mouse-racer

Mouse click game with NodeJS & AngularJS & socket.io
JavaScript
1
star
54

onlinertificate

Onlinertificate is an open source CMS for organizations, companies or school clubs
Ruby
1
star
55

yes-or-no-game

Basic android game
Java
1
star
56

ybs-oop-java

Bandırma 17 Eylül Üniversitesi Nesne Tabanlı Programlama dersi hafta-hafta ders kaynak kodları
Java
1
star
57

secret-message

Anonymous chat application with NodeJS & AngularJS & socket.io.
JavaScript
1
star
58

to-do-list

JavaScript basic to-do application
CSS
1
star
59

visual-programming-lecture-notes

My visual programming lecture notes about C# programming language
C#
1
star
60

phones-app

This is a simple VueJS application for learning it. You can create a new phone if there is a limit.
Vue
1
star
61

credit-card

Credit card mockup with VueJS and Bootstrap
HTML
1
star
62

google-authentication

Simple google authentication (Google+) with NodeJS & AngularJS
JavaScript
1
star
63

twitter-clone

Twitter clone application created with Ruby on Rails
Ruby
1
star
64

limon

Simple guess application with VueJS for learning it
Vue
1
star
65

hello-world-electronJS

Init electronJS project.
JavaScript
1
star
66

socketio-live-amongus

Realtime chat and game with NodeJS & AngularJS & socket.io
JavaScript
1
star
67

simple-spring-mvc-structure

A sample app that showcases MVC structure in Spring Boot.
Java
1
star
68

arduino-modules

How to use some modules in Arduino?
C++
1
star
69

four-distance-sensor

How to calculate most distant in four distance sensors.
C++
1
star
70

flutter_row_and_column

How to use row and column in Flutter
Dart
1
star
71

fake-call

Fake call android application.
Java
1
star
72

rories

Movies application
Vue
1
star
73

yandex-dictionary-api

How to use Yandex Dictionary API with vue-axios and vuex in VueJS?
Vue
1
star
74

turkish_cities

A comprehensive library for managing Turkish cities and their administrative divisions (towns, districts, quarters) in Go
Go
1
star
75

rails-vue-draggable-crud

An example application with Rails Boilerplate template
Ruby
1
star
76

qrcode-generator

Sample qrcode generator
JavaScript
1
star
77

tsundoku

Tsundoku is a social platform for book lovers
Ruby
1
star
78

use-driver

This is a simple plugin for using Driver.js in your React.js application.
TypeScript
1
star
79

freetube

Freetube is like free and ad-free Youtube and it is created with NuxtJS
Vue
1
star
80

go-todo-api

Simple Todo API with Fiber for fun with Golang 🍄
Go
1
star
81

obstacle-avoiding-robot

Simple obstacle avoiding robot with Arduino Mega.
C++
1
star