cm-devise_token_auth 0.1.30.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (117) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +13 -0
  3. data/README.md +688 -0
  4. data/Rakefile +34 -0
  5. data/app/controllers/devise_token_auth/application_controller.rb +17 -0
  6. data/app/controllers/devise_token_auth/concerns/set_user_by_token.rb +109 -0
  7. data/app/controllers/devise_token_auth/confirmations_controller.rb +31 -0
  8. data/app/controllers/devise_token_auth/omniauth_callbacks_controller.rb +171 -0
  9. data/app/controllers/devise_token_auth/passwords_controller.rb +155 -0
  10. data/app/controllers/devise_token_auth/registrations_controller.rb +123 -0
  11. data/app/controllers/devise_token_auth/sessions_controller.rb +98 -0
  12. data/app/controllers/devise_token_auth/token_validations_controller.rb +23 -0
  13. data/app/models/devise_token_auth/concerns/user.rb +231 -0
  14. data/app/views/devise/mailer/confirmation_instructions.html.erb +5 -0
  15. data/app/views/devise/mailer/reset_password_instructions.html.erb +8 -0
  16. data/app/views/devise/mailer/unlock_instructions.html.erb +7 -0
  17. data/app/views/devise_token_auth/omniauth_failure.html.erb +2 -0
  18. data/app/views/devise_token_auth/omniauth_success.html.erb +8 -0
  19. data/app/views/layouts/omniauth_response.html.erb +31 -0
  20. data/config/initializers/devise.rb +203 -0
  21. data/config/locales/devise.en.yml +59 -0
  22. data/config/routes.rb +5 -0
  23. data/lib/devise_token_auth.rb +7 -0
  24. data/lib/devise_token_auth/controllers/helpers.rb +129 -0
  25. data/lib/devise_token_auth/controllers/url_helpers.rb +8 -0
  26. data/lib/devise_token_auth/engine.rb +25 -0
  27. data/lib/devise_token_auth/rails/routes.rb +65 -0
  28. data/lib/devise_token_auth/version.rb +3 -0
  29. data/lib/generators/devise_token_auth/USAGE +31 -0
  30. data/lib/generators/devise_token_auth/install_generator.rb +115 -0
  31. data/lib/generators/devise_token_auth/install_views_generator.rb +16 -0
  32. data/lib/generators/devise_token_auth/templates/devise_token_auth.rb +22 -0
  33. data/lib/generators/devise_token_auth/templates/devise_token_auth_create_users.rb.erb +54 -0
  34. data/lib/generators/devise_token_auth/templates/user.rb +3 -0
  35. data/lib/tasks/devise_token_auth_tasks.rake +4 -0
  36. data/test/controllers/demo_group_controller_test.rb +126 -0
  37. data/test/controllers/demo_mang_controller_test.rb +263 -0
  38. data/test/controllers/demo_user_controller_test.rb +262 -0
  39. data/test/controllers/devise_token_auth/confirmations_controller_test.rb +107 -0
  40. data/test/controllers/devise_token_auth/omniauth_callbacks_controller_test.rb +167 -0
  41. data/test/controllers/devise_token_auth/passwords_controller_test.rb +287 -0
  42. data/test/controllers/devise_token_auth/registrations_controller_test.rb +458 -0
  43. data/test/controllers/devise_token_auth/sessions_controller_test.rb +221 -0
  44. data/test/controllers/overrides/confirmations_controller_test.rb +44 -0
  45. data/test/controllers/overrides/omniauth_callbacks_controller_test.rb +44 -0
  46. data/test/controllers/overrides/passwords_controller_test.rb +62 -0
  47. data/test/controllers/overrides/registrations_controller_test.rb +40 -0
  48. data/test/controllers/overrides/sessions_controller_test.rb +33 -0
  49. data/test/controllers/overrides/token_validations_controller_test.rb +38 -0
  50. data/test/dummy/README.rdoc +28 -0
  51. data/test/dummy/Rakefile +6 -0
  52. data/test/dummy/app/assets/images/logo.jpg +0 -0
  53. data/test/dummy/app/assets/images/omniauth-provider-settings.png +0 -0
  54. data/test/dummy/app/assets/javascripts/application.js +13 -0
  55. data/test/dummy/app/assets/stylesheets/application.css +15 -0
  56. data/test/dummy/app/controllers/application_controller.rb +16 -0
  57. data/test/dummy/app/controllers/demo_group_controller.rb +13 -0
  58. data/test/dummy/app/controllers/demo_mang_controller.rb +12 -0
  59. data/test/dummy/app/controllers/demo_user_controller.rb +12 -0
  60. data/test/dummy/app/controllers/overrides/confirmations_controller.rb +32 -0
  61. data/test/dummy/app/controllers/overrides/omniauth_callbacks_controller.rb +14 -0
  62. data/test/dummy/app/controllers/overrides/passwords_controller.rb +39 -0
  63. data/test/dummy/app/controllers/overrides/registrations_controller.rb +27 -0
  64. data/test/dummy/app/controllers/overrides/sessions_controller.rb +43 -0
  65. data/test/dummy/app/controllers/overrides/token_validations_controller.rb +23 -0
  66. data/test/dummy/app/helpers/application_helper.rb +1065 -0
  67. data/test/dummy/app/models/evil_user.rb +3 -0
  68. data/test/dummy/app/models/mang.rb +3 -0
  69. data/test/dummy/app/models/user.rb +18 -0
  70. data/test/dummy/app/views/layouts/application.html.erb +14 -0
  71. data/test/dummy/bin/bundle +3 -0
  72. data/test/dummy/bin/rails +8 -0
  73. data/test/dummy/bin/rake +8 -0
  74. data/test/dummy/bin/spring +18 -0
  75. data/test/dummy/config.ru +16 -0
  76. data/test/dummy/config/application.rb +23 -0
  77. data/test/dummy/config/application.yml.bk +0 -0
  78. data/test/dummy/config/boot.rb +5 -0
  79. data/test/dummy/config/database.yml +31 -0
  80. data/test/dummy/config/environment.rb +5 -0
  81. data/test/dummy/config/environments/development.rb +44 -0
  82. data/test/dummy/config/environments/production.rb +82 -0
  83. data/test/dummy/config/environments/test.rb +40 -0
  84. data/test/dummy/config/initializers/assets.rb +8 -0
  85. data/test/dummy/config/initializers/backtrace_silencers.rb +7 -0
  86. data/test/dummy/config/initializers/cookies_serializer.rb +3 -0
  87. data/test/dummy/config/initializers/devise_token_auth.rb +22 -0
  88. data/test/dummy/config/initializers/figaro.rb +1 -0
  89. data/test/dummy/config/initializers/filter_parameter_logging.rb +4 -0
  90. data/test/dummy/config/initializers/inflections.rb +16 -0
  91. data/test/dummy/config/initializers/mime_types.rb +4 -0
  92. data/test/dummy/config/initializers/omniauth.rb +8 -0
  93. data/test/dummy/config/initializers/session_store.rb +3 -0
  94. data/test/dummy/config/initializers/wrap_parameters.rb +14 -0
  95. data/test/dummy/config/locales/en.yml +23 -0
  96. data/test/dummy/config/routes.rb +30 -0
  97. data/test/dummy/config/secrets.yml +22 -0
  98. data/test/dummy/config/spring.rb +1 -0
  99. data/test/dummy/db/migrate/20140715061447_devise_token_auth_create_users.rb +56 -0
  100. data/test/dummy/db/migrate/20140715061805_devise_token_auth_create_mangs.rb +56 -0
  101. data/test/dummy/db/migrate/20140829044006_add_operating_thetan_to_user.rb +6 -0
  102. data/test/dummy/db/migrate/20140916224624_add_favorite_color_to_mangs.rb +5 -0
  103. data/test/dummy/db/migrate/20140928231203_devise_token_auth_create_evil_users.rb +57 -0
  104. data/test/dummy/db/schema.rb +114 -0
  105. data/test/dummy/public/404.html +67 -0
  106. data/test/dummy/public/422.html +67 -0
  107. data/test/dummy/public/500.html +66 -0
  108. data/test/dummy/public/favicon.ico +0 -0
  109. data/test/fixtures/evil_users.yml +29 -0
  110. data/test/fixtures/mangs.yml +29 -0
  111. data/test/fixtures/users.yml +29 -0
  112. data/test/integration/navigation_test.rb +10 -0
  113. data/test/lib/generators/devise_token_auth/install_generator_test.rb +178 -0
  114. data/test/lib/generators/devise_token_auth/install_views_generator_test.rb +23 -0
  115. data/test/models/user_test.rb +90 -0
  116. data/test/test_helper.rb +60 -0
  117. metadata +310 -0
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: a6b8ee8b8e19816cd4a6bdf8e8af186c1faad68f
4
+ data.tar.gz: 7d646332dd81b66f6aaa3759b1b526d23058580e
5
+ SHA512:
6
+ metadata.gz: b6b51e8c3b5724b37c52cd91e93c1eaac1623226c4c012d4c8ae180bd8fe6bac01c9b799b504f554d7382b9aa7a2e4a49ce4b2e57e10387a40d5f12152ba7630
7
+ data.tar.gz: d533b8b6497da80074d6f765f188c36d8f88dcb992e0ae5e3ae480a28f3891209ce7d651c6b7ff830e757768f970806ba15fff2f0252526593b9fb95cdabc961
data/LICENSE ADDED
@@ -0,0 +1,13 @@
1
+ DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
2
+ Version 2, December 2004
3
+
4
+ Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>
5
+
6
+ Everyone is permitted to copy and distribute verbatim or modified
7
+ copies of this license document, and changing it is allowed as long
8
+ as the name is changed.
9
+
10
+ DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
11
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
12
+
13
+ 0. You just DO WHAT THE FUCK YOU WANT TO.
@@ -0,0 +1,688 @@
1
+ ![Serious Trust](https://github.com/lynndylanhurley/devise_token_auth/raw/master/test/dummy/app/assets/images/logo.jpg "Serious Trust")
2
+
3
+ [![Gem Version](https://badge.fury.io/rb/devise_token_auth.svg)](http://badge.fury.io/rb/devise_token_auth)
4
+ [![Build Status](https://travis-ci.org/lynndylanhurley/devise_token_auth.svg?branch=master)](https://travis-ci.org/lynndylanhurley/devise_token_auth)
5
+ [![Code Climate](http://img.shields.io/codeclimate/github/lynndylanhurley/devise_token_auth.svg)](https://codeclimate.com/github/lynndylanhurley/devise_token_auth)
6
+ [![Test Coverage](http://img.shields.io/codeclimate/coverage/github/lynndylanhurley/devise_token_auth.svg)](https://codeclimate.com/github/lynndylanhurley/devise_token_auth)
7
+ [![Dependency Status](https://gemnasium.com/lynndylanhurley/devise_token_auth.svg)](https://gemnasium.com/lynndylanhurley/devise_token_auth)
8
+
9
+ ## Simple, secure token based authentication for Rails.
10
+
11
+ This gem provides the following features:
12
+
13
+ * Seamless integration with the the venerable [ng-token-auth](https://github.com/lynndylanhurley/ng-token-auth) module for [angular.js](https://github.com/angular/angular.js).
14
+ * Oauth2 authentication using [OmniAuth](https://github.com/intridea/omniauth).
15
+ * Email authentication using [Devise](https://github.com/plataformatec/devise), including:
16
+ * User registration
17
+ * Password reset
18
+ * Account updates
19
+ * Account deletion
20
+ * Support for [multiple user models](https://github.com/lynndylanhurley/devise_token_auth#using-multiple-models).
21
+ * It is [secure](#security).
22
+
23
+ # [Live Demo](http://ng-token-auth-demo.herokuapp.com/)
24
+
25
+ [Here is a demo](http://ng-token-auth-demo.herokuapp.com/) of this app running with the [ng-token-auth](https://github.com/lynndylanhurley/ng-token-auth) module.
26
+
27
+ The fully configured api used in the demo can be found [here](https://github.com/lynndylanhurley/devise_token_auth_demo).
28
+
29
+ # Table of Contents
30
+
31
+ * [Dependencies](#dependencies)
32
+ * [Configuration TL;DR](#configuration-tldr)
33
+ * [Usage TL;DR](#usage-tldr)
34
+ * [Configuration Continued](#configuration-cont)
35
+ * [Initializer Settings](#initializer-settings)
36
+ * [OmniAuth Authentication](#omniauth-authentication)
37
+ * [OmniAuth Provider Settings](#omniauth-provider-settings)
38
+ * [Email Authentication](#email-authentication)
39
+ * [Cross Origin Requests (CORS)](#cors)
40
+ * [Usage Continued](#usage-cont)
41
+ * [Mounting Routes](#mounting-routes)
42
+ * [Controller Integration](#controller-concerns)
43
+ * [Model Integration](#model-concerns)
44
+ * [Using Multiple User Classes](#using-multiple-models)
45
+ * [Skip Confirmation Upon Email Registration](#skip-confirmation-upon-registration)
46
+ * [Custom Controller Overrides](#custom-controller-overrides)
47
+ * [Email Template Overrides](#email-template-overrides)
48
+ * [Conceptual Diagrams](#conceptual)
49
+ * [Token Management](#about-token-management)
50
+ * [Batch Requests](#about-batch-requests)
51
+ * [Security](#security)
52
+ * [Contribution Guidelines](#contributing)
53
+
54
+ # Dependencies
55
+ This project leverages the following gems:
56
+
57
+ * [Devise](https://github.com/plataformatec/devise)
58
+ * [OmniAuth](https://github.com/intridea/omniauth)
59
+
60
+ # Installation
61
+ Add the following to your `Gemfile`:
62
+
63
+ ~~~ruby
64
+ gem 'devise_token_auth'
65
+ ~~~
66
+
67
+ Then install the gem using bundle:
68
+
69
+ ~~~bash
70
+ bundle install
71
+ ~~~
72
+
73
+ # Configuration TL;DR
74
+
75
+ You will need to create a [user model](#model-concerns), [define routes](#mounting-routes), [include concerns](#controller-concerns), and you may want to alter some of the [default settings](#initializer-settings) for this gem. Run the following command for an easy one-step installation:
76
+
77
+ ~~~bash
78
+ rails g devise_token_auth:install [USER_CLASS] [MOUNT_PATH]
79
+ ~~~
80
+
81
+ **Example**:
82
+
83
+ ~~~bash
84
+ rails g devise_token_auth:install User /auth
85
+ ~~~
86
+
87
+ This generator accepts the following optional arguments:
88
+
89
+ | Argument | Default | Description |
90
+ |---|---|---|
91
+ | USER_CLASS | `User` | The name of the class to use for user authentication. |
92
+ | MOUNT_PATH | `/auth` | The path at which to mount the authentication routes. [Read more](#usage). |
93
+
94
+ The following events will take place when using the install generator:
95
+
96
+ * An initializer will be created at `config/initializers/devise_token_auth.rb`. [Read more](#initializer-settings).
97
+
98
+ * A model will be created in the `app/models` directory. If the model already exists, a concern will be included at the top of the file. [Read more](#model-concerns).
99
+
100
+ * Routes will be appended to file at `config/routes.rb`. [Read more](#mounting-routes).
101
+
102
+ * A concern will be included by your application controller at `app/controllers/application_controller.rb`. [Read more](#controller-concerns).
103
+
104
+ * A migration file will be created in the `db/migrate` directory. Inspect the migrations file, add additional columns if necessary, and then run the migration:
105
+
106
+ ~~~bash
107
+ rake db:migrate
108
+ ~~~
109
+
110
+ You may also need to configure the following items:
111
+
112
+ * **OmniAuth providers** when using 3rd party oauth2 authentication. [Read more](#omniauth-authentication).
113
+ * **Cross Origin Request Settings** when using cross-domain clients. [Read more](#cors).
114
+ * **Email** when using email registration. [Read more](#email-authentication).
115
+ * **Multiple model support** may require additional steps. [Read more](#using-multiple-models).
116
+
117
+ [Jump here](#configuration-cont) for more configuration information.
118
+
119
+ # Usage TL;DR
120
+
121
+ The following routes are available for use by your client. These routes live relative to the path at which this engine is mounted (`/auth` by default). These routes correspond to the defaults used by the [ng-token-auth](https://github.com/lynndylanhurley/ng-token-auth) module for angular.js.
122
+
123
+ | path | method | purpose |
124
+ |:-----|:-------|:--------|
125
+ | / | POST | Email registration. Accepts **`email`**, **`password`**, and **`password_confirmation`** params. A verification email will be sent to the email address provided. Accepted params can be customized using the [`devise_parameter_sanitizer`](https://github.com/plataformatec/devise#strong-parameters) system. |
126
+ | / | DELETE | Account deletion. This route will destroy users identified by their **`uid`** and **`auth_token`** headers. |
127
+ | / | PUT | 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. |
128
+ | /sign_in | POST | Email authentication. Accepts **`email`** and **`password`** as params. This route will return a JSON representation of the `User` model on successful login. |
129
+ | /sign_out | DELETE | Use this route to end the user's current session. This route will invalidate the user's authentication token. |
130
+ | /:provider | GET | Set this route as the destination for client authentication. Ideally this will happen in an external window or popup. [Read more](#omniauth-authentication). |
131
+ | /:provider/callback | GET/POST | 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). |
132
+ | /validate_token | POST | Use this route to validate tokens on return visits to the client. Accepts **`uid`** and **`auth_token`** as params. These values should correspond to the columns in your `User` table of the same names. |
133
+ | /password | POST | 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. |
134
+ | /password | PUT | Use this route to change users' passwords. Accepts **`password`** and **`password_confirmation`** as params. This route is only valid for users that registered by email (OAuth2 users will receive an error). |
135
+ | /password/edit | GET | 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. |
136
+
137
+ [Jump here](#usage-cont) for more usage information.
138
+
139
+ # Configuration cont.
140
+
141
+ ## Initializer settings
142
+
143
+ The following settings are available for configuration in `config/initializers/devise_token_auth.rb`:
144
+
145
+ | Name | Default | Description|
146
+ |---|---|---|
147
+ | **`change_headers_on_each_request`** | `true` | By default the access_token header will change after each request. The client is responsible for keeping track of the changing tokens. The [ng-token-auth](https://github.com/lynndylanhurley/ng-token-auth) module for angular.js does this out of the box. While this implementation is more secure, it can be difficult to manage. Set this to false to prevent the `access_token` header from changing after each request. [Read more](#about-token-management). |
148
+ | **`token_lifespan`** | `2.weeks` | Set the length of your tokens' lifespans. Users will need to re-authenticate after this duration of time has passed since their last login. |
149
+ | **`batch_request_buffer_throttle`** | `5.seconds` | Sometimes it's necessary to make several requests to the API at the same time. In this case, each request in the batch will need to share the same auth token. This setting determines how far apart the requests can be while still using the same auth token. [Read more](#about-batch-requests). |
150
+ | **`omniauth_prefix`** | `"/omniauth"` | This route will be the prefix for all oauth2 redirect callbacks. For example, using the default '/omniauth' setting, the github oauth2 provider will redirect successful authentications to '/omniauth/github/callback'. [Read more](#omniauth-provider-settings). |
151
+
152
+
153
+ ## OmniAuth authentication
154
+
155
+ If you wish to use omniauth authentication, add all of your desired authentication provider gems to your `Gemfile`.
156
+
157
+ **OmniAuth example using github, facebook, and google**:
158
+ ~~~ruby
159
+ gem 'omniauth-github'
160
+ gem 'omniauth-facebook'
161
+ gem 'omniauth-google-oauth2'
162
+ ~~~
163
+
164
+ Then run `bundle install`.
165
+
166
+ [List of oauth2 providers](https://github.com/intridea/omniauth/wiki/List-of-Strategies)
167
+
168
+ ## OmniAuth provider settings
169
+
170
+ In `config/initializers/omniauth.rb`, add the settings for each of your providers.
171
+
172
+ These settings must be obtained from the providers themselves.
173
+
174
+ **Example using github, facebook, and google**:
175
+ ~~~ruby
176
+ # config/initializers/omniauth.rb
177
+ Rails.application.config.middleware.use OmniAuth::Builder do
178
+ provider :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET'], scope: 'email,profile'
179
+ provider :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET']
180
+ provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET']
181
+ end
182
+ ~~~
183
+
184
+ The above example assumes that your provider keys and secrets are stored in environmental variables. Use the [figaro](https://github.com/laserlemon/figaro) gem (or [dotenv](https://github.com/bkeepers/dotenv) or [secrets.yml](https://github.com/rails/rails/blob/v4.1.0/railties/lib/rails/generators/rails/app/templates/config/secrets.yml) or equivalent) to accomplish this.
185
+
186
+ #### OmniAuth callback settings
187
+
188
+ The "Callback URL" setting that you set with your provider must correspond to the [omniauth prefix](#initializer-settings) setting defined by this app. **This will be different than the omniauth route that is used by your client application**.
189
+
190
+ For example, the demo app uses the default `omniauth_prefix` setting `/omniauth`, so the "Authorization callback URL" for github must be set to "http://devise-token-auth-demo.herokuapp.com**/omniauth**/github/callback".
191
+
192
+ **Github example for the demo site**:
193
+ ![password reset flow](https://github.com/lynndylanhurley/devise_token_auth/raw/master/test/dummy/app/assets/images/omniauth-provider-settings.png)
194
+
195
+ The url for github authentication will be different for the client. The client should visit the API at `/[MOUNT_PATH]/:provider` for omniauth authentication.
196
+
197
+ For example, given that the app is mounted using the following settings:
198
+
199
+ ~~~ruby
200
+ # config/routes.rb
201
+ mount_devise_token_auth_for 'User', at: '/auth'
202
+ ~~~
203
+
204
+ The client configuration for github should look like this:
205
+
206
+ **Angular.js setting for authenticating using github**:
207
+ ~~~javascript
208
+ angular.module('myApp', ['ng-token-auth'])
209
+ .config(function($authProvider) {
210
+ $authProvider.configure({
211
+ apiUrl: 'http://api.example.com'
212
+ authProviderPaths: {
213
+ github: '/auth/github' // <-- note that this is different than what was set with github
214
+ }
215
+ });
216
+ });
217
+ ~~~
218
+
219
+ This incongruence is necessary to support multiple user classes and mounting points.
220
+
221
+ #### Note for [pow](http://pow.cx/) and [xip.io](http://xip.io) users
222
+
223
+ If you receive `redirect-uri-mismatch` errors from your provider when using pow or xip.io urls, set the following in your development config:
224
+
225
+ ~~~ruby
226
+ # config/environments/development.rb
227
+
228
+ # when using pow
229
+ OmniAuth.config.full_host = "http://app-name.dev"
230
+
231
+ # when using xip.io
232
+ OmniAuth.config.full_host = "http://xxx.xxx.xxx.app-name.xip.io"
233
+ ~~~
234
+
235
+ ## Email authentication
236
+ If you wish to use email authentication, you must configure your Rails application to send email. [Read here](http://guides.rubyonrails.org/action_mailer_basics.html) for more information.
237
+
238
+ I recommend using [mailcatcher](http://mailcatcher.me/) for development.
239
+
240
+ ##### mailcatcher development example configuration:
241
+ ~~~ruby
242
+ # config/environments/development.rb
243
+ Rails.application.configure do
244
+ config.action_mailer.default_url_options = { :host => 'your-dev-host.dev' }
245
+ config.action_mailer.delivery_method = :smtp
246
+ config.action_mailer.smtp_settings = { :address => 'your-dev-host.dev', :port => 1025 }
247
+ end
248
+ ~~~
249
+
250
+ ## CORS
251
+
252
+ If your API and client live on different domains, you will need to configure your Rails API to allow [cross origin requests](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing). The [rack-cors](https://github.com/cyu/rack-cors) gem can be used to accomplish this.
253
+
254
+ The following **dangerous** example will allow cross domain requests from **any** domain. Make sure to whitelist only the needed domains.
255
+
256
+ ##### Example rack-cors configuration:
257
+ ~~~ruby
258
+ # gemfile
259
+ gem 'rack-cors', :require => 'rack/cors'
260
+
261
+ # config/application.rb
262
+ module YourApp
263
+ class Application < Rails::Application
264
+ config.middleware.use Rack::Cors do
265
+ allow do
266
+ origins '*'
267
+ resource '*',
268
+ :headers => :any,
269
+ :expose => ['access-token', 'expiry', 'token-type', 'uid', 'client'],
270
+ :methods => [:get, :post, :options, :delete, :put]
271
+ end
272
+ end
273
+ end
274
+ end
275
+ ~~~
276
+
277
+ Make extra sure that the `Access-Control-Expose-Headers` includes `access-token`, `expiry`, `token-type`, `uid`, and `client` (as is set in the example above by the`:expose` param). If your client experiences erroneous 401 responses, this is likely the cause.
278
+
279
+ CORS may not be possible with older browsers (IE8, IE9). I usually set up a proxy for those browsers. See the [ng-token-auth readme](https://github.com/lynndylanhurley/ng-token-auth) for more information.
280
+
281
+ # Usage cont.
282
+
283
+ ## Mounting Routes
284
+
285
+ The authentication routes must be mounted to your project. This gem includes a route helper for this purpose:
286
+
287
+ **`mount_devise_token_auth_for`** - similar to `devise_for`, this method is used to append the routes necessary for user authentication. This method accepts the following arguments:
288
+
289
+ | Argument | Type | Default | Description |
290
+ |---|---|---|---|
291
+ |`class_name`| string | 'User' | The name of the class to use for authentication. This class must include the [model concern described here](#model-concerns). |
292
+ | `options` | object | {at: '/auth'} | The [routes to be used for authentication](#usage) will be prefixed by the path specified in the `at` param of this object. |
293
+
294
+ **Example**:
295
+ ~~~ruby
296
+ # config/routes.rb
297
+ mount_devise_token_auth_for 'User', at: '/auth'
298
+ ~~~
299
+
300
+ Any model class can be used, but the class will need to include [`DeviseTokenAuth::Concerns::User`](#model-concerns) for authentication to work properly.
301
+
302
+ You can mount this engine to any route that you like. `/auth` is used by default to conform with the defaults of the [ng-token-auth](https://github.com/lynndylanhurley/ng-token-auth) module.
303
+
304
+
305
+ ## Controller Methods
306
+
307
+ ### Concerns
308
+
309
+ This gem includes a [Rails concern](http://api.rubyonrails.org/classes/ActiveSupport/Concern.html) called `DeviseTokenAuth::Concerns::SetUserByToken`. Include this concern to provide access to [controller methods](#controller-methods) such as [`authenticate_user!`](#authenticate-user), [`user_signed_in?`](#user-signed-in), etc.
310
+
311
+ The concern also runs an [after_action](http://guides.rubyonrails.org/action_controller_overview.html#filters) that changes the auth token after each request.
312
+
313
+ It is recommended to include the concern in your base `ApplicationController` so that all children of that controller include the concern as well.
314
+
315
+ ##### Concern example:
316
+
317
+ ~~~ruby
318
+ # app/controllers/application_controller.rb
319
+ class ApplicationController < ActionController::Base
320
+ include DeviseTokenAuth::Concerns::SetUserByToken
321
+ end
322
+ ~~~
323
+
324
+ ### Methods
325
+
326
+ This gem provides access to all of the following [devise helpers](https://github.com/plataformatec/devise#controller-filters-and-helpers):
327
+
328
+ | Method | Description |
329
+ |---|---|
330
+ | **`before_action :authenticate_user!`** | Returns a 401 error unless a `User` is signed-in. |
331
+ | **`current_user`** | Returns the currently signed-in `User`, or `nil` if unavailable. |
332
+ | **`user_signed_in?`** | Returns `true` if a `User` is signed in, otherwise `false`. |
333
+ | **`devise_token_auth_group`** | Operate on multiple user classes as a group. [Read more](#group-access) |
334
+
335
+ Note that if the model that you're trying to access isn't called `User`, the helper method names will change. For example, if the user model is called `Admin`, the methods would look like this:
336
+
337
+ * `before_action :authenticate_admin!`
338
+ * `admin_signed_in?`
339
+ * `current_admin`
340
+
341
+
342
+ ##### Example: limit access to authenticated users
343
+ ~~~ruby
344
+ # app/controllers/test_controller.rb
345
+ class TestController < ApplicationController
346
+ before_action :authenticate_user!
347
+
348
+ def members_only
349
+ render json: {
350
+ data: {
351
+ message: "Welcome #{current_user.name}",
352
+ user: current_user
353
+ }
354
+ }, status: 200
355
+ end
356
+ end
357
+ ~~~
358
+
359
+ ### Token Header Format
360
+
361
+ The authentication information should be included by the client in the headers of each request. The headers follow the [RFC 6750 Bearer Token](http://tools.ietf.org/html/rfc6750) format:
362
+
363
+ ##### Authentication headers example:
364
+ ~~~
365
+ "access_token": "wwwww",
366
+ "token_type": "Bearer",
367
+ "client": "xxxxx",
368
+ "expiry": "yyyyy",
369
+ "uid": "zzzzz"
370
+ ~~~
371
+
372
+ The authentication headers consists of the following params:
373
+
374
+ | param | description |
375
+ |---|---|
376
+ | **`access_token`** | This serves as the user's password for each request. A hashed version of this value is stored in the database for later comparison. This value should be changed on each request. |
377
+ | **`client`** | This enables the use of multiple simultaneous sessions on different clients. (For example, a user may want to be authenticated on both their phone and their laptop at the same time.) |
378
+ | **`expiry`** | The date at which the current session will expire. This can be used by clients to invalidate expired tokens without the need for an API request. |
379
+ | **`uid`** | A unique value that is used to identify the user. This is necessary because searching the DB for users by their access token will make the API susceptible to [timing attacks](http://codahale.com/a-lesson-in-timing-attacks/). |
380
+
381
+ The authentication headers required for each request will be available in the response from the previous request. If you are using the [ng-token-auth](https://github.com/lynndylanhurley/ng-token-auth) module for angular.js, this functionality is already provided.
382
+
383
+ ## Model Concerns
384
+
385
+ ##### DeviseTokenAuth::Concerns::User
386
+
387
+ Typical use of this gem will not require the use of any of the following model methods. All authentication should be handled invisibly by the [controller concerns](#controller-concerns) described above.
388
+
389
+ Models that include the `DeviseTokenAuth::Concerns::User` concern will have access to the following public methods (read the above section for context on `token` and `client`):
390
+
391
+ * **`valid_token?`**: check if an authentication token is valid. Accepts a `token` and `client` as arguments. Returns a boolean.
392
+
393
+ **Example**:
394
+ ~~~ruby
395
+ # extract token + client_id from auth header
396
+ client_id = request.headers['client']
397
+ token = request.headers['access_token']
398
+
399
+ @user.valid_token?(token, client_id)
400
+ ~~~
401
+
402
+ * **`create_new_auth_token`**: creates a new auth token with all of the necessary metadata. Accepts `client` as an optional argument. Will generate a new `client` if none is provided. Returns the authentication headers that should be sent by the client as an object.
403
+
404
+ **Example**:
405
+ ~~~ruby
406
+ # extract client_id from auth header
407
+ client_id = request.headers['client']
408
+
409
+ # update token, generate updated auth headers for response
410
+ new_auth_header = @user.create_new_auth_token(client_id)
411
+
412
+ # update response with the header that will be required by the next request
413
+ response.headers.merge!(new_auth_header)
414
+ ~~~
415
+
416
+ * **`build_auth_header`**: generates the auth header that should be sent to the client with the next request. Accepts `token` and `client` as arguments. Returns a string.
417
+
418
+ **Example**:
419
+ ~~~ruby
420
+ # create client id and token
421
+ client_id = SecureRandom.urlsafe_base64(nil, false)
422
+ token = SecureRandom.urlsafe_base64(nil, false)
423
+
424
+ # store client + token in user's token hash
425
+ @user.tokens[client_id] = {
426
+ token: BCrypt::Password.create(token),
427
+ expiry: (Time.now + DeviseTokenAuth.token_lifespan).to_i
428
+ }
429
+
430
+ # generate auth headers for response
431
+ new_auth_header = @user.build_auth_header(token, client_id)
432
+
433
+ # update response with the header that will be required by the next request
434
+ response.headers.merge!(new_auth_header)
435
+ ~~~
436
+
437
+ ## Using multiple models
438
+
439
+ ### [View Live Multi-User Demo](http://ng-token-auth-demo.herokuapp.com/multi-user)
440
+
441
+ This gem supports the use of multiple user models. One possible use case is to authenticate visitors using a model called `User`, and to authenticate administrators with a model called `Admin`. Take the following steps to add another authentication model to your app:
442
+
443
+ 1. Run the install generator for the new model.
444
+ ~~~
445
+ rails g devise_token_auth:install Admin admin_auth
446
+ ~~~
447
+
448
+ This will create the `Admin` model and define the model's authentication routes with the base path `/admin_auth`.
449
+
450
+ 1. Define the routes to be used by the `Admin` user within a [`devise_scope`](https://github.com/plataformatec/devise#configuring-routes).
451
+
452
+ **Example**:
453
+ ~~~ruby
454
+ Rails.application.routes.draw do
455
+ # when using multiple models, controllers will default to the first available
456
+ # devise mapping. routes for subsequent devise mappings will need to defined
457
+ # within a `devise_scope` block
458
+
459
+ # define :users as the first devise mapping:
460
+ mount_devise_token_auth_for 'User', at: '/auth'
461
+
462
+ # define :admins as the second devise mapping. routes using this class will
463
+ # need to be defined within a devise_scope as shown below
464
+ mount_devise_token_auth_for "Admin", at: '/admin_auth'
465
+
466
+ # this route will authorize requests using the User class
467
+ get 'demo/members_only', to: 'demo#members_only'
468
+
469
+ # routes within this block will authorize requests using the Admin class
470
+ devise_scope :admin do
471
+ get 'demo/admins_only', to: 'demo#admins_only'
472
+ end
473
+ end
474
+ ~~~
475
+
476
+ 1. Configure any `Admin` restricted controllers. Controllers will now have access to the methods [described here](#methods):
477
+ * `before_action: :authenticate_admin!`
478
+ * `current_admin`
479
+ * `admin_signed_in?`
480
+
481
+
482
+ ### Group access
483
+
484
+ It is also possible to control access to multiple user types at the same time using groups. The following example shows how to limit controller access to both `User` and `Admin` users.
485
+
486
+ ##### Example: group authentication
487
+
488
+ ~~~ruby
489
+ class DemoGroupController < ApplicationController
490
+ devise_token_auth_group :member, contains: [:user, :admin]
491
+ before_action :authenticate_member!
492
+
493
+ def members_only
494
+ render json: {
495
+ data: {
496
+ message: "Welcome #{current_member.name}",
497
+ user: current_member
498
+ }
499
+ }, status: 200
500
+ end
501
+ end
502
+ ~~~
503
+
504
+ In the above example, the following methods will be available (in addition to `current_user`, `current_admin`, etc.):
505
+
506
+ * `before_action: :authenticate_member!`
507
+ * `current_member`
508
+ * `member_signed_in?`
509
+
510
+ ## Skip Confirmation Upon Email Registration
511
+
512
+ By default, an email is sent containing a link that the user must visit to activate their account. This measure is in place to ensure that users cannot register other people for accounts.
513
+
514
+ To bypass this measure, add `before_create :skip_confirmation!` to your `User` model (or equivalent).
515
+
516
+ ##### Example: bypass email confirmation
517
+
518
+ ~~~ruby
519
+ class User < ActiveRecord::Base
520
+ include DeviseTokenAuth::Concerns::User
521
+ before_create :skip_confirmation!
522
+ end
523
+ ~~~
524
+
525
+ ##### Note for ng-token-auth users:
526
+
527
+ If this `before_create :skip_confirmation!` callback is in place, the `$auth.submitRegistration` method will both register and authenticate users in a single step.
528
+
529
+ ## Custom Controller Overrides
530
+
531
+ The built-in controllers can be overridden with your own custom controllers.
532
+
533
+ For example, the default behavior of the [`validate_token`](https://github.com/lynndylanhurley/devise_token_auth/blob/8a33d25deaedb4809b219e557e82ec7ec61bf940/app/controllers/devise_token_auth/token_validations_controller.rb#L6) method of the [`TokenValidationController`](https://github.com/lynndylanhurley/devise_token_auth/blob/8a33d25deaedb4809b219e557e82ec7ec61bf940/app/controllers/devise_token_auth/token_validations_controller.rb) is to return the `User` object as json (sans password and token data). The following example shows how to override the `validate_token` action to include a model method as well.
534
+
535
+ ##### Example: controller overrides
536
+
537
+ ~~~ruby
538
+ # config/routes.rb
539
+ Rails.application.routes.draw do
540
+ ...
541
+ mount_devise_token_auth_for 'User', at: '/auth', controllers: {
542
+ token_validations: 'overrides/token_validations'
543
+ }
544
+ end
545
+
546
+ # app/controllers/overrides/token_validations_controller.rb
547
+ module Overrides
548
+ class TokenValidationsController < DeviseTokenAuth::TokenValidationsController
549
+
550
+ def validate_token
551
+ # @user will have been set by set_user_by_token concern
552
+ if @user
553
+ render json: {
554
+ data: @user.as_json(methods: :calculate_operating_thetan)
555
+ }
556
+ else
557
+ render json: {
558
+ success: false,
559
+ errors: ["Invalid login credentials"]
560
+ }, status: 401
561
+ end
562
+ end
563
+ end
564
+ end
565
+ ~~~
566
+
567
+ ##### Example: all :controller options with default settings:
568
+
569
+ ~~~ruby
570
+ mount_devise_token_auth_for 'User', at: '/auth', controllers: {
571
+ confirmations: 'devise_token_auth/confirmations',
572
+ passwords: 'devise_token_auth/passwords',
573
+ omniauth_callbacks: 'devise_token_auth/omniauth_callbacks',
574
+ registrations: 'devise_token_auth/registrations',
575
+ sessions: 'devise_token_auth/sessions',
576
+ token_validations: 'devise_token_auth/token_validations'
577
+ }
578
+ ~~~
579
+
580
+ **Note:** Controller overrides must implement the expected actions of the controllers that they replace.
581
+
582
+ ## Email Template Overrides
583
+
584
+ You will probably want to override the default email templates for email sign-up and password-reset confirmation. Run the following command to copy the email templates into your app:
585
+
586
+ ~~~bash
587
+ rails generate devise_token_auth:install_views
588
+ ~~~
589
+
590
+ This will create two new files:
591
+
592
+ * `app/views/devise/mailer/reset_password_instructions.html.erb`
593
+ * `app/views/devise/mailer/confirmation_instructions.html.erb`
594
+
595
+ These files may be edited to suit your taste.
596
+
597
+ **Note:** if you choose to modify these templates, do not modify the `link_to` blocks unless you absolutely know what you are doing.
598
+
599
+ # Conceptual
600
+
601
+ None of the following information is required to use this gem, but read on if you're curious.
602
+
603
+ ## About token management
604
+
605
+ Tokens should be invalidated after each request to the API. The following diagram illustrates this concept:
606
+
607
+ ![password reset flow](https://github.com/lynndylanhurley/ng-token-auth/raw/master/test/app/images/flow/token-update-detail.jpg)
608
+
609
+ During each request, a new token is generated. The `access_token` header that should be used in the next request is returned in the `access_token` header of the response to the previous request. The last request in the diagram fails because it tries to use a token that was invalidated by the previous request.
610
+
611
+ The only case where an expired token is allowed is during [batch requests](#about-batch-requests).
612
+
613
+ These measures are taken by default when using this gem.
614
+
615
+ ## About batch requests
616
+
617
+ By default, the API should update the auth token for each request ([read more](#about-token-management)). But sometimes it's neccessary to make several concurrent requests to the API, for example:
618
+
619
+ #####Batch request example
620
+ ~~~javascript
621
+ $scope.getResourceData = function() {
622
+
623
+ $http.get('/api/restricted_resource_1').success(function(resp) {
624
+ // handle response
625
+ $scope.resource1 = resp.data;
626
+ });
627
+
628
+ $http.get('/api/restricted_resource_2').success(function(resp) {
629
+ // handle response
630
+ $scope.resource2 = resp.data;
631
+ });
632
+ };
633
+ ~~~
634
+
635
+ In this case, it's impossible to update the `access_token` header for the second request with the `access_token` header of the first response because the second request will begin before the first one is complete. The server must allow these batches of concurrent requests to share the same auth token. This diagram illustrates how batch requests are identified by the server:
636
+
637
+ ![batch request overview](https://github.com/lynndylanhurley/ng-token-auth/raw/master/test/app/images/flow/batch-request-overview.jpg)
638
+
639
+ The "5 second" buffer in the diagram is the default used this gem.
640
+
641
+ The following diagram details the relationship between the client, server, and access tokens used over time when dealing with batch requests:
642
+
643
+ ![batch request detail](https://github.com/lynndylanhurley/ng-token-auth/raw/master/test/app/images/flow/batch-request-detail.jpg)
644
+
645
+ Note that when the server identifies that a request is part of a batch request, the user's auth token is not updated. The auth token will be updated for the first request in the batch, and then that same token will be returned in the responses for each subsequent request in the batch (as shown in the diagram).
646
+
647
+ This gem automatically manages batch requests. You can change the time buffer for what is considered a batch request using the `batch_request_buffer_throttle` parameter in `config/initializers/devise_token_auth.rb`.
648
+
649
+
650
+ # Security
651
+
652
+ This gem takes the following steps to ensure security.
653
+
654
+ This gem uses auth tokens that are:
655
+ * [changed after every request](#about-token-management),
656
+ * [of cryptographic strength](http://ruby-doc.org/stdlib-2.1.0/libdoc/securerandom/rdoc/SecureRandom.html),
657
+ * hashed using [BCrypt](https://github.com/codahale/bcrypt-ruby) (not stored in plain-text),
658
+ * securely compared (to protect against timing attacks),
659
+ * invalidated after 2 weeks (thus requiring users to login again)
660
+
661
+ These measures were inspired by [this stackoverflow post](http://stackoverflow.com/questions/18605294/is-devises-token-authenticatable-secure).
662
+
663
+ This gem further mitigates timing attacks by using [this technique](https://gist.github.com/josevalim/fb706b1e933ef01e4fb6).
664
+
665
+ But the most important step is to use HTTPS. You are on the hook for that.
666
+
667
+
668
+ # Contributing
669
+
670
+ 1. Create a feature branch with your changes.
671
+ 2. Write some test cases.
672
+ 3. Make all the tests pass.
673
+ 4. Issue a pull request.
674
+
675
+ I will grant you commit access if you send quality pull requests.
676
+
677
+ To run the test suite do the following:
678
+
679
+ 1. Clone this repo
680
+ 2. Run `bundle install`
681
+ 3. Run `rake db:migrate`
682
+ 4. Run `RAILS_ENV=test rake db:migrate`
683
+ 5. Run `guard`.
684
+
685
+ The last command will open the [guard](https://github.com/guard/guard) test-runner. Guard will re-run each test suite when changes are made to its corresponding files.
686
+
687
+ # License
688
+ This project uses the WTFPL