Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,4 @@
.ruby-gemset

.env
/spec/tmp/config/routes.rb
50 changes: 36 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,21 +20,40 @@ Or install it yourself as:

$ gem install graphql_devise

## Usage
All configurations for [Devise](https://github.com/plataformatec/devise) and
[Devise Token Auth](https://github.com/lynndylanhurley/devise_token_auth) are
available, so you can read the docs there to customize your options.
Next, you need to run the generator:

$ rails generate graphql_devise:install

Graphql Devise generator will execute `Devise` and `Devise Token Auth`
generators for you. These will make the required changes for the gems to
work correctly. All configurations for [Devise](https://github.com/plataformatec/devise) and
[Devise Token Auth](https://github.com/lynndylanhurley/devise_token_auth) are available,
so you can read the docs there to customize your options.
Configurations are done via initializer files as usual, one per gem.
You can generate most of the configuration by using DTA's installer while we work
on our own generators like this

The generator accepts 2 params: `user_class` and `mount_path`. The params
will be used to mount the route in `config/routes.rb`. For instance the executing:

```bash
$ rails g devise_token_auth:install User auth
$ rails g graphql_devise:install Admin api/auth
```
`User` could be any model name you are going to be using for authentication,
and `auth` could be anything as we will be removing that from the routes file.

### Mounting Routes
First, you need to mount the gem in the routes file like this
Will do the following:
- Execute `Devise` install generator
- Execute `Devise Token Auth` install generator with `Admin` and `api/auth` as params
- Find or create `Admin` model
- Add `devise` modules to `Admin` model
- Other changes that you can find [here](https://devise-token-auth.gitbook.io/devise-token-auth/config)
- Add the route to `config/routes.rb`
- `mount_graphql_devise_for 'Admin', at: 'api/auth'

`Admin` could be any model name you are going to be using for authentication,
and `api/auth` could be any mount path you would like to use for auth.

### Mounting Routes manually
Routes can be added using the initializer or manually.
You can add a route like this:

```ruby
# config/routes.rb

Expand All @@ -50,8 +69,6 @@ Rails.application.routes.draw do
)
end
```
If you used DTA's installer you will have to remove the `mount_devise_token_auth_for`
line.

Here are the options for the mount method:

Expand Down Expand Up @@ -107,6 +124,9 @@ class User < ApplicationRecord
end
```

The install generator can do this for you if you specify the `user_class` option.
See [Installation](#Installation) for details.

### Customizing Email Templates
The approach of this gem is a bit different from DeviseTokenAuth. We have placed our templates in `app/views/graphql_devise/mailer`,
so if you want to change them, place yours on the same dir structure on your Rails project. You can customize these two templates:
Expand All @@ -132,6 +152,9 @@ class MyController < ApplicationController
end
```

The install generator can do this for you because it executes DTA installer.
See [Installation](#Installation) for details.

### Making Requests
Here is a list of the available mutations and queries assuming your mounted model
is `User`.
Expand Down Expand Up @@ -167,7 +190,6 @@ templates.
## Future Work
We will continue to improve the gem and add better docs.

1. Add install generator.
1. Add mount option that will create a separate schema for the mounted resource.
1. Make sure this gem can correctly work alongside DTA and the original Devise gem.
1. Improve DOCS.
Expand Down
1 change: 1 addition & 0 deletions graphql_devise.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,5 @@ Gem::Specification.new do |spec|
spec.add_development_dependency 'rubocop-rspec'
spec.add_development_dependency 'sqlite3', '~> 1.3'
spec.add_development_dependency 'github_changelog_generator'
spec.add_development_dependency 'generator_spec'
end
66 changes: 66 additions & 0 deletions lib/generators/graphql_devise/install_generator.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
module GraphqlDevise
class InstallGenerator < ::Rails::Generators::Base
source_root File.expand_path('templates', __dir__)

argument :user_class, type: :string, default: 'User'
argument :mount_path, type: :string, default: 'auth'

def execute_devise_installer
generate 'devise:install'
end

def execute_dta_installer
generate 'devise_token_auth:install', "#{user_class} #{mount_path}"
end

def mount_resource_route
routes_file = 'config/routes.rb'
routes_path = File.join(destination_root, routes_file)
gem_helper = 'mount_graphql_devise_for'
gem_route = "#{gem_helper} '#{user_class}', at: '#{mount_path}'"
dta_route = "mount_devise_token_auth_for '#{user_class}', at: '#{mount_path}'"
file_start = 'Rails.application.routes.draw do'

if File.exist?(routes_path)
current_route = parse_file_for_line(routes_path, gem_route)

if current_route.present?
say_status('skipped', "Routes already exist for #{user_class} at #{mount_path}")
else
current_dta_route = parse_file_for_line(routes_path, dta_route)

if current_dta_route.present?
replace_line(routes_path, dta_route, gem_route)
else
insert_text_after_line(routes_path, file_start, gem_route)
end
end
else
say_status('skipped', "#{routes_file} not found. Add \"#{gem_route}\" to your routes file.")
end
end

private

def insert_text_after_line(filename, line, str)
gsub_file(filename, /(#{Regexp.escape(line)})/mi) do |match|
"#{match}\n #{str}"
end
end

def replace_line(filename, old_line, new_line)
gsub_file(filename, /(#{Regexp.escape(old_line)})/mi, " #{new_line}")
end

def parse_file_for_line(filename, str)
match = false

File.open(filename) do |f|
f.each_line do |line|
match = line if line =~ /(#{Regexp.escape(str)})/mi
end
end
match
end
end
end
65 changes: 65 additions & 0 deletions spec/dummy/config/locales/devise.en.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Additional translations at https://github.com/plataformatec/devise/wiki/I18n

en:
devise:
confirmations:
confirmed: "Your email address has been successfully confirmed."
send_instructions: "You will receive an email with instructions for how to confirm your email address in a few minutes."
send_paranoid_instructions: "If your email address exists in our database, you will receive an email with instructions for how to confirm your email address in a few minutes."
failure:
already_authenticated: "You are already signed in."
inactive: "Your account is not activated yet."
invalid: "Invalid %{authentication_keys} or password."
locked: "Your account is locked."
last_attempt: "You have one more attempt before your account is locked."
not_found_in_database: "Invalid %{authentication_keys} or password."
timeout: "Your session expired. Please sign in again to continue."
unauthenticated: "You need to sign in or sign up before continuing."
unconfirmed: "You have to confirm your email address before continuing."
mailer:
confirmation_instructions:
subject: "Confirmation instructions"
reset_password_instructions:
subject: "Reset password instructions"
unlock_instructions:
subject: "Unlock instructions"
email_changed:
subject: "Email Changed"
password_change:
subject: "Password Changed"
omniauth_callbacks:
failure: "Could not authenticate you from %{kind} because \"%{reason}\"."
success: "Successfully authenticated from %{kind} account."
passwords:
no_token: "You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided."
send_instructions: "You will receive an email with instructions on how to reset your password in a few minutes."
send_paranoid_instructions: "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes."
updated: "Your password has been changed successfully. You are now signed in."
updated_not_active: "Your password has been changed successfully."
registrations:
destroyed: "Bye! Your account has been successfully cancelled. We hope to see you again soon."
signed_up: "Welcome! You have signed up successfully."
signed_up_but_inactive: "You have signed up successfully. However, we could not sign you in because your account is not yet activated."
signed_up_but_locked: "You have signed up successfully. However, we could not sign you in because your account is locked."
signed_up_but_unconfirmed: "A message with a confirmation link has been sent to your email address. Please follow the link to activate your account."
update_needs_confirmation: "You updated your account successfully, but we need to verify your new email address. Please check your email and follow the confirmation link to confirm your new email address."
updated: "Your account has been updated successfully."
updated_but_not_signed_in: "Your account has been updated successfully, but since your password was changed, you need to sign in again"
sessions:
signed_in: "Signed in successfully."
signed_out: "Signed out successfully."
already_signed_out: "Signed out successfully."
unlocks:
send_instructions: "You will receive an email with instructions for how to unlock your account in a few minutes."
send_paranoid_instructions: "If your account exists, you will receive an email with instructions for how to unlock it in a few minutes."
unlocked: "Your account has been unlocked successfully. Please sign in to continue."
errors:
messages:
already_confirmed: "was already confirmed, please try signing in"
confirmation_period_expired: "needs to be confirmed within %{period}, please request a new one"
expired: "has expired, please request a new one"
not_found: "not found"
not_locked: "was not locked"
not_saved:
one: "1 error prohibited this %{resource} from being saved:"
other: "%{count} errors prohibited this %{resource} from being saved:"
52 changes: 52 additions & 0 deletions spec/generators/graphql_devise/install_generator_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Generators are not automatically loaded by Rails
require 'rails_helper'
require 'generators/graphql_devise/install_generator'

RSpec.describe GraphqlDevise::InstallGenerator, type: :generator do
destination File.expand_path('../../../tmp', __FILE__)

before do
prepare_destination
end

let(:routes_path) { "#{destination_root}/config/routes.rb" }
let(:routes_content) { File.read(routes_path) }
let(:dta_route) { "mount_devise_token_auth_for 'User', at: 'auth'" }

xcontext 'when the file exists' do
before do
create_file_with_content(
routes_path,
"Rails.application.routes.draw do\n#{dta_route}\nend"
)
end

context 'when passing no params to the generator' do
before { run_generator }

it 'replaces dta route using the default values for class and path' do
generator_added_route = / mount_graphql_devise_for 'User', at: 'auth'/
expect(routes_content).to match(generator_added_route)
expect(routes_content).not_to match(dta_route)
end
end

context 'when passing custom params to the generator' do
before { run_generator %w[Admin api] }

it 'add the routes using the provided values for class and path and keeps dta route' do
generator_added_route = / mount_graphql_devise_for 'Admin', at: 'api'/
expect(routes_content).to match(generator_added_route)
expect(routes_content).to match(dta_route)
end
end
end

xcontext 'when file does *NOT* exist' do
before { run_generator }

it 'does *NOT* create the file and throw no exception' do
expect(File.exist?(routes_path)).to be_falsey
end
end
end
2 changes: 2 additions & 0 deletions spec/rails_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
# Add additional requires below this line. Rails is not loaded until this point!
require 'factory_bot'
require 'faker'
require 'generator_spec'

# Load RSpec helpers.
Dir[File.join(ENGINE_ROOT, 'spec/support/**/*.rb')].each { |f| require f }
Expand All @@ -36,4 +37,5 @@
config.include(Requests::JsonHelpers, type: :request)
config.include(Requests::AuthHelpers, type: :request)
config.include(ActiveSupport::Testing::TimeHelpers)
config.include(Generators::FileHelpers, type: :generator)
end
12 changes: 12 additions & 0 deletions spec/support/generators/file_helpers.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
require 'fileutils'

module Generators
module FileHelpers
def create_file_with_content(path, content)
FileUtils.mkdir(File.dirname(path))
File.open(path, 'w') do |f|
f.write(content)
end
end
end
end