xing_backend_token_auth 0.1.31

Sign up to get free protection for your applications and to get access to all the features.
Files changed (122) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +13 -0
  3. data/README.md +679 -0
  4. data/Rakefile +34 -0
  5. data/app/controllers/devise_token_auth/application_controller.rb +22 -0
  6. data/app/controllers/devise_token_auth/concerns/set_user_by_token.rb +110 -0
  7. data/app/controllers/devise_token_auth/confirmations_controller.rb +31 -0
  8. data/app/controllers/devise_token_auth/omniauth_callbacks_controller.rb +169 -0
  9. data/app/controllers/devise_token_auth/passwords_controller.rb +107 -0
  10. data/app/controllers/devise_token_auth/registrations_controller.rb +99 -0
  11. data/app/controllers/devise_token_auth/sessions_controller.rb +50 -0
  12. data/app/controllers/devise_token_auth/token_validations_controller.rb +22 -0
  13. data/app/serializers/devise_token_auth/error_messages_serializer.rb +16 -0
  14. data/app/serializers/devise_token_auth/resource_errors_serializer.rb +24 -0
  15. data/app/serializers/devise_token_auth/resource_serializer.rb +17 -0
  16. data/app/serializers/devise_token_auth/success_message_serializer.rb +15 -0
  17. data/app/views/devise/mailer/confirmation_instructions.html.erb +5 -0
  18. data/app/views/devise/mailer/reset_password_instructions.html.erb +8 -0
  19. data/app/views/devise/mailer/unlock_instructions.html.erb +7 -0
  20. data/app/views/devise_token_auth/omniauth_failure.html.erb +2 -0
  21. data/app/views/devise_token_auth/omniauth_success.html.erb +8 -0
  22. data/app/views/layouts/omniauth_response.html.erb +31 -0
  23. data/config/initializers/devise.rb +207 -0
  24. data/config/initializers/token_auth_failure_app.rb +7 -0
  25. data/config/locales/devise.en.yml +59 -0
  26. data/config/routes.rb +5 -0
  27. data/lib/devise_token_auth.rb +9 -0
  28. data/lib/devise_token_auth/controllers/helpers.rb +129 -0
  29. data/lib/devise_token_auth/controllers/url_helpers.rb +8 -0
  30. data/lib/devise_token_auth/engine.rb +32 -0
  31. data/lib/devise_token_auth/models/token_authenticatable.rb +195 -0
  32. data/lib/devise_token_auth/rails/routes.rb +65 -0
  33. data/lib/generators/devise_token_auth/USAGE +31 -0
  34. data/lib/generators/devise_token_auth/install_generator.rb +100 -0
  35. data/lib/generators/devise_token_auth/install_views_generator.rb +16 -0
  36. data/lib/generators/devise_token_auth/templates/devise_token_auth.rb +22 -0
  37. data/lib/generators/devise_token_auth/templates/devise_token_auth_add_token_info_to_users.rb.erb +14 -0
  38. data/lib/tasks/devise_token_auth_tasks.rake +4 -0
  39. data/lib/xing_backend_token_auth.rb +1 -0
  40. data/test/controllers/demo_group_controller_test.rb +126 -0
  41. data/test/controllers/demo_mang_controller_test.rb +263 -0
  42. data/test/controllers/demo_user_controller_test.rb +262 -0
  43. data/test/controllers/devise_token_auth/confirmations_controller_test.rb +107 -0
  44. data/test/controllers/devise_token_auth/omniauth_callbacks_controller_test.rb +144 -0
  45. data/test/controllers/devise_token_auth/passwords_controller_test.rb +275 -0
  46. data/test/controllers/devise_token_auth/registrations_controller_test.rb +405 -0
  47. data/test/controllers/devise_token_auth/registrations_controller_test.rb.orig +494 -0
  48. data/test/controllers/devise_token_auth/sessions_controller_test.rb +169 -0
  49. data/test/controllers/overrides/confirmations_controller_test.rb +44 -0
  50. data/test/controllers/overrides/omniauth_callbacks_controller_test.rb +44 -0
  51. data/test/controllers/overrides/passwords_controller_test.rb +64 -0
  52. data/test/controllers/overrides/registrations_controller_test.rb +42 -0
  53. data/test/controllers/overrides/sessions_controller_test.rb +35 -0
  54. data/test/controllers/overrides/token_validations_controller_test.rb +38 -0
  55. data/test/dummy/README.rdoc +28 -0
  56. data/test/dummy/Rakefile +6 -0
  57. data/test/dummy/app/assets/images/logo.jpg +0 -0
  58. data/test/dummy/app/assets/images/omniauth-provider-settings.png +0 -0
  59. data/test/dummy/app/assets/javascripts/application.js +13 -0
  60. data/test/dummy/app/assets/stylesheets/application.css +15 -0
  61. data/test/dummy/app/controllers/application_controller.rb +16 -0
  62. data/test/dummy/app/controllers/demo_group_controller.rb +13 -0
  63. data/test/dummy/app/controllers/demo_mang_controller.rb +12 -0
  64. data/test/dummy/app/controllers/demo_user_controller.rb +12 -0
  65. data/test/dummy/app/controllers/overrides/confirmations_controller.rb +32 -0
  66. data/test/dummy/app/controllers/overrides/omniauth_callbacks_controller.rb +14 -0
  67. data/test/dummy/app/controllers/overrides/passwords_controller.rb +39 -0
  68. data/test/dummy/app/controllers/overrides/registrations_controller.rb +27 -0
  69. data/test/dummy/app/controllers/overrides/sessions_controller.rb +26 -0
  70. data/test/dummy/app/controllers/overrides/token_validations_controller.rb +23 -0
  71. data/test/dummy/app/controllers/registrations_controller.rb +2 -0
  72. data/test/dummy/app/helpers/application_helper.rb +1065 -0
  73. data/test/dummy/app/models/evil_user.rb +5 -0
  74. data/test/dummy/app/models/mang.rb +5 -0
  75. data/test/dummy/app/models/user.rb +20 -0
  76. data/test/dummy/app/views/layouts/application.html.erb +14 -0
  77. data/test/dummy/bin/bundle +3 -0
  78. data/test/dummy/bin/rails +8 -0
  79. data/test/dummy/bin/rake +8 -0
  80. data/test/dummy/bin/spring +18 -0
  81. data/test/dummy/config.ru +16 -0
  82. data/test/dummy/config/application.rb +23 -0
  83. data/test/dummy/config/boot.rb +5 -0
  84. data/test/dummy/config/database.yml +31 -0
  85. data/test/dummy/config/environment.rb +5 -0
  86. data/test/dummy/config/environments/development.rb +44 -0
  87. data/test/dummy/config/environments/production.rb +82 -0
  88. data/test/dummy/config/environments/test.rb +40 -0
  89. data/test/dummy/config/initializers/assets.rb +8 -0
  90. data/test/dummy/config/initializers/backtrace_silencers.rb +7 -0
  91. data/test/dummy/config/initializers/cookies_serializer.rb +3 -0
  92. data/test/dummy/config/initializers/devise_token_auth.rb +22 -0
  93. data/test/dummy/config/initializers/figaro.rb +1 -0
  94. data/test/dummy/config/initializers/filter_parameter_logging.rb +4 -0
  95. data/test/dummy/config/initializers/inflections.rb +16 -0
  96. data/test/dummy/config/initializers/mime_types.rb +4 -0
  97. data/test/dummy/config/initializers/omniauth.rb +8 -0
  98. data/test/dummy/config/initializers/session_store.rb +3 -0
  99. data/test/dummy/config/initializers/wrap_parameters.rb +14 -0
  100. data/test/dummy/config/locales/en.yml +23 -0
  101. data/test/dummy/config/routes.rb +32 -0
  102. data/test/dummy/config/secrets.yml +22 -0
  103. data/test/dummy/config/spring.rb +1 -0
  104. data/test/dummy/db/migrate/20140715061447_devise_token_auth_create_users.rb +56 -0
  105. data/test/dummy/db/migrate/20140715061805_devise_token_auth_create_mangs.rb +56 -0
  106. data/test/dummy/db/migrate/20140829044006_add_operating_thetan_to_user.rb +6 -0
  107. data/test/dummy/db/migrate/20140916224624_add_favorite_color_to_mangs.rb +5 -0
  108. data/test/dummy/db/migrate/20140928231203_devise_token_auth_create_evil_users.rb +57 -0
  109. data/test/dummy/db/schema.rb +111 -0
  110. data/test/dummy/public/404.html +67 -0
  111. data/test/dummy/public/422.html +67 -0
  112. data/test/dummy/public/500.html +66 -0
  113. data/test/dummy/public/favicon.ico +0 -0
  114. data/test/fixtures/evil_users.yml +29 -0
  115. data/test/fixtures/mangs.yml +29 -0
  116. data/test/fixtures/users.yml +29 -0
  117. data/test/integration/navigation_test.rb +10 -0
  118. data/test/lib/generators/devise_token_auth/install_generator_test.rb +131 -0
  119. data/test/lib/generators/devise_token_auth/install_views_generator_test.rb +23 -0
  120. data/test/models/user_test.rb +81 -0
  121. data/test/test_helper.rb +60 -0
  122. metadata +320 -0
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 0bc73583cf4638b349d57c4d07d19324e5f9d345
4
+ data.tar.gz: 7f9a8e12d300fe7dff246f9775adf9ab8ddc077b
5
+ SHA512:
6
+ metadata.gz: fcc2e3864b6c1d638804f421855da5a9a42f8603c77f874a72e06c320aa8cd4351e81d7079491e5b9379e1c24548df9308bb9e845c0078c9e3daa71bea2af24e
7
+ data.tar.gz: c6d038a007f2ea5397ef24cf79914e78fdab3d9dc09ac9195c62810716ddb151159eadcb288ac68ead7dc7028c0210bc15715a0afa1ad68dcd3946a8ba42d7e1
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,679 @@
1
+ # XingTokenAuth
2
+ ### forked from DeviseTokenAuth
3
+
4
+ DeviseTokenAuth makes a number of assumptions about how underlying
5
+ authentication tasks should be handled which are incompatible with some of the
6
+ underlying principles of Xing. Over the next few weeks, expect XingTokenAuth
7
+ (and it's yet to be released companion JS module) to diverge significantly from
8
+ the Devise/NgTokenAuth approach.
9
+
10
+ _the remainder of this README are near-verbatim from DeviseTokenAuth_
11
+
12
+ _as a result, there may be errors due to an incomplete tranfer - please issue an MR!_
13
+
14
+ ## Simple, secure token based authentication for Rails.
15
+
16
+ This gem provides the following features:
17
+
18
+ * 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).
19
+ * Oauth2 authentication using [OmniAuth](https://github.com/intridea/omniauth).
20
+ * Email authentication using [Devise](https://github.com/plataformatec/devise), including:
21
+ * User registration
22
+ * Password reset
23
+ * Account updates
24
+ * Account deletion
25
+ * Support for [multiple user models](https://github.com/lynndylanhurley/devise_token_auth#using-multiple-models).
26
+ * It is [secure](#security).
27
+
28
+ # [Live Demo](http://ng-token-auth-demo.herokuapp.com/)
29
+
30
+ [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.
31
+
32
+ The fully configured api used in the demo can be found [here](https://github.com/lynndylanhurley/devise_token_auth_demo).
33
+
34
+ # Table of Contents
35
+
36
+ * [Dependencies](#dependencies)
37
+ * [Configuration TL;DR](#configuration-tldr)
38
+ * [Usage TL;DR](#usage-tldr)
39
+ * [Configuration Continued](#configuration-cont)
40
+ * [Initializer Settings](#initializer-settings)
41
+ * [OmniAuth Authentication](#omniauth-authentication)
42
+ * [OmniAuth Provider Settings](#omniauth-provider-settings)
43
+ * [Email Authentication](#email-authentication)
44
+ * [Cross Origin Requests (CORS)](#cors)
45
+ * [Usage Continued](#usage-cont)
46
+ * [Mounting Routes](#mounting-routes)
47
+ * [Controller Integration](#controller-concerns)
48
+ * [Model Integration](#model-concerns)
49
+ * [Using Multiple User Classes](#using-multiple-models)
50
+ * [Skip Confirmation Upon Email Registration](#skip-confirmation-upon-registration)
51
+ * [Custom Controller Overrides](#custom-controller-overrides)
52
+ * [Email Template Overrides](#email-template-overrides)
53
+ * [Conceptual Diagrams](#conceptual)
54
+ * [Token Management](#about-token-management)
55
+ * [Batch Requests](#about-batch-requests)
56
+ * [Security](#security)
57
+ * [Contribution Guidelines](#contributing)
58
+
59
+ # Dependencies
60
+ This project leverages the following gems:
61
+
62
+ * [Devise](https://github.com/plataformatec/devise)
63
+ * [OmniAuth](https://github.com/intridea/omniauth)
64
+
65
+ # Installation
66
+ Add the following to your `Gemfile`:
67
+
68
+ ~~~ruby
69
+ gem 'xing_backend_token_auth'
70
+ ~~~
71
+
72
+ Then install the gem using bundle:
73
+
74
+ ~~~bash
75
+ bundle install
76
+ ~~~
77
+
78
+ # Configuration TL;DR
79
+
80
+ 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:
81
+
82
+ ~~~bash
83
+ rails g devise_token_auth:install [USER_CLASS] [MOUNT_PATH]
84
+ ~~~
85
+
86
+ **Example**:
87
+
88
+ ~~~bash
89
+ rails g devise_token_auth:install User /auth
90
+ ~~~
91
+
92
+ This generator accepts the following optional arguments:
93
+
94
+ | Argument | Default | Description |
95
+ |---|---|---|
96
+ | USER_CLASS | `User` | The name of the class to use for user authentication. |
97
+ | MOUNT_PATH | `/auth` | The path at which to mount the authentication routes. [Read more](#usage). |
98
+
99
+ The following events will take place when using the install generator:
100
+
101
+ * An initializer will be created at `config/initializers/devise_token_auth.rb`. [Read more](#initializer-settings).
102
+
103
+ * 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).
104
+
105
+ * Routes will be appended to file at `config/routes.rb`. [Read more](#mounting-routes).
106
+
107
+ * A concern will be included by your application controller at `app/controllers/application_controller.rb`. [Read more](#controller-concerns).
108
+
109
+ * 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:
110
+
111
+ ~~~bash
112
+ rake db:migrate
113
+ ~~~
114
+
115
+ You may also need to configure the following items:
116
+
117
+ * **OmniAuth providers** when using 3rd party oauth2 authentication. [Read more](#omniauth-authentication).
118
+ * **Cross Origin Request Settings** when using cross-domain clients. [Read more](#cors).
119
+ * **Email** when using email registration. [Read more](#email-authentication).
120
+ * **Multiple model support** may require additional steps. [Read more](#using-multiple-models).
121
+
122
+ [Jump here](#configuration-cont) for more configuration information.
123
+
124
+ # Usage TL;DR
125
+
126
+ 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.
127
+
128
+ | path | method | purpose |
129
+ |:-----|:-------|:--------|
130
+ | / | 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. |
131
+ | / | DELETE | Account deletion. This route will destroy users identified by their **`uid`** and **`auth_token`** headers. |
132
+ | / | 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. |
133
+ | /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. |
134
+ | /sign_out | DELETE | Use this route to end the user's current session. This route will invalidate the user's authentication token. |
135
+ | /: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). |
136
+ | /: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). |
137
+ | /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. |
138
+ | /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. |
139
+ | /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). |
140
+ | /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. |
141
+
142
+ [Jump here](#usage-cont) for more usage information.
143
+
144
+ # Configuration cont.
145
+
146
+ ## Initializer settings
147
+
148
+ The following settings are available for configuration in `config/initializers/devise_token_auth.rb`:
149
+
150
+ | Name | Default | Description|
151
+ |---|---|---|
152
+ | **`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). |
153
+ | **`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. |
154
+ | **`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). |
155
+ | **`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). |
156
+
157
+
158
+ ## OmniAuth authentication
159
+
160
+ If you wish to use omniauth authentication, add all of your desired authentication provider gems to your `Gemfile`.
161
+
162
+ **OmniAuth example using github, facebook, and google**:
163
+ ~~~ruby
164
+ gem 'omniauth-github'
165
+ gem 'omniauth-facebook'
166
+ gem 'omniauth-google-oauth2'
167
+ ~~~
168
+
169
+ Then run `bundle install`.
170
+
171
+ [List of oauth2 providers](https://github.com/intridea/omniauth/wiki/List-of-Strategies)
172
+
173
+ ## OmniAuth provider settings
174
+
175
+ In `config/initializers/omniauth.rb`, add the settings for each of your providers.
176
+
177
+ These settings must be obtained from the providers themselves.
178
+
179
+ **Example using github, facebook, and google**:
180
+ ~~~ruby
181
+ # config/initializers/omniauth.rb
182
+ Rails.application.config.middleware.use OmniAuth::Builder do
183
+ provider :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET'], scope: 'email,profile'
184
+ provider :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET']
185
+ provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET']
186
+ end
187
+ ~~~
188
+
189
+ 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.
190
+
191
+ #### OmniAuth callback settings
192
+
193
+ 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**.
194
+
195
+ 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".
196
+
197
+ **Github example for the demo site**:
198
+ ![password reset flow](https://github.com/lynndylanhurley/devise_token_auth/raw/master/test/dummy/app/assets/images/omniauth-provider-settings.png)
199
+
200
+ The url for github authentication will be different for the client. The client should visit the API at `/[MOUNT_PATH]/:provider` for omniauth authentication.
201
+
202
+ For example, given that the app is mounted using the following settings:
203
+
204
+ ~~~ruby
205
+ # config/routes.rb
206
+ mount_devise_token_auth_for 'User', at: '/auth'
207
+ ~~~
208
+
209
+ The client configuration for github should look like this:
210
+
211
+ **Angular.js setting for authenticating using github**:
212
+ ~~~javascript
213
+ angular.module('myApp', ['ng-token-auth'])
214
+ .config(function($authProvider) {
215
+ $authProvider.configure({
216
+ apiUrl: 'http://api.example.com'
217
+ authProviderPaths: {
218
+ github: '/auth/github' // <-- note that this is different than what was set with github
219
+ }
220
+ });
221
+ });
222
+ ~~~
223
+
224
+ This incongruence is necessary to support multiple user classes and mounting points.
225
+
226
+ #### Note for [pow](http://pow.cx/) and [xip.io](http://xip.io) users
227
+
228
+ If you receive `redirect-uri-mismatch` errors from your provider when using pow or xip.io urls, set the following in your development config:
229
+
230
+ ~~~ruby
231
+ # config/environments/development.rb
232
+
233
+ # when using pow
234
+ OmniAuth.config.full_host = "http://app-name.dev"
235
+
236
+ # when using xip.io
237
+ OmniAuth.config.full_host = "http://xxx.xxx.xxx.app-name.xip.io"
238
+ ~~~
239
+
240
+ ## Email authentication
241
+ 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.
242
+
243
+ I recommend using [mailcatcher](http://mailcatcher.me/) for development.
244
+
245
+ ##### mailcatcher development example configuration:
246
+ ~~~ruby
247
+ # config/environments/development.rb
248
+ Rails.application.configure do
249
+ config.action_mailer.default_url_options = { :host => 'your-dev-host.dev' }
250
+ config.action_mailer.delivery_method = :smtp
251
+ config.action_mailer.smtp_settings = { :address => 'your-dev-host.dev', :port => 1025 }
252
+ end
253
+ ~~~
254
+
255
+ ## CORS
256
+
257
+ 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.
258
+
259
+ The following **dangerous** example will allow cross domain requests from **any** domain. Make sure to whitelist only the needed domains.
260
+
261
+ ##### Example rack-cors configuration:
262
+ ~~~ruby
263
+ # gemfile
264
+ gem 'rack-cors', :require => 'rack/cors'
265
+
266
+ # config/application.rb
267
+ module YourApp
268
+ class Application < Rails::Application
269
+ config.middleware.use Rack::Cors do
270
+ allow do
271
+ origins '*'
272
+ resource '*',
273
+ :headers => :any,
274
+ :expose => ['access-token', 'expiry', 'token-type', 'uid', 'client'],
275
+ :methods => [:get, :post, :options, :delete, :put]
276
+ end
277
+ end
278
+ end
279
+ end
280
+ ~~~
281
+
282
+ 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.
283
+
284
+ 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.
285
+
286
+ # Usage cont.
287
+
288
+ ## Mounting Routes
289
+
290
+ The authentication routes must be mounted to your project. This gem includes a route helper for this purpose:
291
+
292
+ **`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:
293
+
294
+ | Argument | Type | Default | Description |
295
+ |---|---|---|---|
296
+ |`class_name`| string | 'User' | The name of the class to use for authentication. This class must include the [model concern described here](#model-concerns). |
297
+ | `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. |
298
+
299
+ **Example**:
300
+ ~~~ruby
301
+ # config/routes.rb
302
+ mount_devise_token_auth_for 'User', at: '/auth'
303
+ ~~~
304
+
305
+ Any model class can be used, but the class will need to include [`DeviseTokenAuth::Concerns::User`](#model-concerns) for authentication to work properly.
306
+
307
+ 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.
308
+
309
+
310
+ ## Controller Methods
311
+
312
+ ### Concerns
313
+
314
+ 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.
315
+
316
+ The concern also runs an [after_action](http://guides.rubyonrails.org/action_controller_overview.html#filters) that changes the auth token after each request.
317
+
318
+ It is recommended to include the concern in your base `ApplicationController` so that all children of that controller include the concern as well.
319
+
320
+ ##### Concern example:
321
+
322
+ ~~~ruby
323
+ # app/controllers/application_controller.rb
324
+ class ApplicationController < ActionController::Base
325
+ include DeviseTokenAuth::Concerns::SetUserByToken
326
+ end
327
+ ~~~
328
+
329
+ ### Methods
330
+
331
+ This gem provides access to all of the following [devise helpers](https://github.com/plataformatec/devise#controller-filters-and-helpers):
332
+
333
+ | Method | Description |
334
+ |---|---|
335
+ | **`before_action :authenticate_user!`** | Returns a 401 error unless a `User` is signed-in. |
336
+ | **`current_user`** | Returns the currently signed-in `User`, or `nil` if unavailable. |
337
+ | **`user_signed_in?`** | Returns `true` if a `User` is signed in, otherwise `false`. |
338
+ | **`devise_token_auth_group`** | Operate on multiple user classes as a group. [Read more](#group-access) |
339
+
340
+ 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:
341
+
342
+ * `before_action :authenticate_admin!`
343
+ * `admin_signed_in?`
344
+ * `current_admin`
345
+
346
+
347
+ ##### Example: limit access to authenticated users
348
+ ~~~ruby
349
+ # app/controllers/test_controller.rb
350
+ class TestController < ApplicationController
351
+ before_action :authenticate_user!
352
+
353
+ def members_only
354
+ render json: {
355
+ data: {
356
+ message: "Welcome #{current_user.name}",
357
+ user: current_user
358
+ }
359
+ }, status: 200
360
+ end
361
+ end
362
+ ~~~
363
+
364
+ ### Token Header Format
365
+
366
+ 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:
367
+
368
+ ##### Authentication headers example:
369
+ ~~~
370
+ "access_token": "wwwww",
371
+ "token_type": "Bearer",
372
+ "client": "xxxxx",
373
+ "expiry": "yyyyy",
374
+ "uid": "zzzzz"
375
+ ~~~
376
+
377
+ The authentication headers consists of the following params:
378
+
379
+ | param | description |
380
+ |---|---|
381
+ | **`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. |
382
+ | **`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.) |
383
+ | **`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. |
384
+ | **`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/). |
385
+
386
+ 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.
387
+
388
+ ## Model Concerns
389
+
390
+ ##### DeviseTokenAuth::Concerns::User
391
+
392
+ 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.
393
+
394
+ 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`):
395
+
396
+ * **`valid_token?`**: check if an authentication token is valid. Accepts a `token` and `client` as arguments. Returns a boolean.
397
+
398
+ **Example**:
399
+ ~~~ruby
400
+ # extract token + client_id from auth header
401
+ client_id = request.headers['client']
402
+ token = request.headers['access_token']
403
+
404
+ @user.valid_token?(token, client_id)
405
+ ~~~
406
+
407
+ * **`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.
408
+
409
+ **Example**:
410
+ ~~~ruby
411
+ # extract client_id from auth header
412
+ client_id = request.headers['client']
413
+
414
+ # update token, generate updated auth headers for response
415
+ new_auth_header = @user.create_new_auth_token(client_id)
416
+
417
+ # update response with the header that will be required by the next request
418
+ response.headers.merge!(new_auth_header)
419
+ ~~~
420
+
421
+ * **`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.
422
+
423
+ **Example**:
424
+ ~~~ruby
425
+ # create client id and token
426
+ client_id = SecureRandom.urlsafe_base64(nil, false)
427
+ token = SecureRandom.urlsafe_base64(nil, false)
428
+
429
+ # store client + token in user's token hash
430
+ @user.tokens[client_id] = {
431
+ token: BCrypt::Password.create(token),
432
+ expiry: (Time.now + DeviseTokenAuth.token_lifespan).to_i
433
+ }
434
+
435
+ # generate auth headers for response
436
+ new_auth_header = @user.build_auth_header(token, client_id)
437
+
438
+ # update response with the header that will be required by the next request
439
+ response.headers.merge!(new_auth_header)
440
+ ~~~
441
+
442
+ ## Using multiple models
443
+
444
+ ### [View Live Multi-User Demo](http://ng-token-auth-demo.herokuapp.com/multi-user)
445
+
446
+ 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:
447
+
448
+ 1. Run the install generator for the new model.
449
+ ~~~
450
+ rails g devise_token_auth:install Admin admin_auth
451
+ ~~~
452
+
453
+ This will create the `Admin` model and define the model's authentication routes with the base path `/admin_auth`.
454
+
455
+ 1. Define the routes to be used by the `Admin` user within a [`devise_scope`](https://github.com/plataformatec/devise#configuring-routes).
456
+
457
+ **Example**:
458
+ ~~~ruby
459
+ Rails.application.routes.draw do
460
+ # when using multiple models, controllers will default to the first available
461
+ # devise mapping. routes for subsequent devise mappings will need to defined
462
+ # within a `devise_scope` block
463
+
464
+ # define :users as the first devise mapping:
465
+ mount_devise_token_auth_for 'User', at: '/auth'
466
+
467
+ # define :admins as the second devise mapping. routes using this class will
468
+ # need to be defined within a devise_scope as shown below
469
+ mount_devise_token_auth_for "Admin", at: '/admin_auth'
470
+
471
+ # this route will authorize requests using the User class
472
+ get 'demo/members_only', to: 'demo#members_only'
473
+
474
+ # routes within this block will authorize requests using the Admin class
475
+ devise_scope :admin do
476
+ get 'demo/admins_only', to: 'demo#admins_only'
477
+ end
478
+ end
479
+ ~~~
480
+
481
+ 1. Configure any `Admin` restricted controllers. Controllers will now have access to the methods [described here](#methods):
482
+ * `before_action: :authenticate_admin!`
483
+ * `current_admin`
484
+ * `admin_signed_in?`
485
+
486
+
487
+ ### Group access
488
+
489
+ 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.
490
+
491
+ ##### Example: group authentication
492
+
493
+ ~~~ruby
494
+ class DemoGroupController < ApplicationController
495
+ devise_token_auth_group :member, contains: [:user, :admin]
496
+ before_action :authenticate_member!
497
+
498
+ def members_only
499
+ render json: {
500
+ data: {
501
+ message: "Welcome #{current_member.name}",
502
+ user: current_member
503
+ }
504
+ }, status: 200
505
+ end
506
+ end
507
+ ~~~
508
+
509
+ In the above example, the following methods will be available (in addition to `current_user`, `current_admin`, etc.):
510
+
511
+ * `before_action: :authenticate_member!`
512
+ * `current_member`
513
+ * `member_signed_in?`
514
+
515
+ ## Skip Confirmation Upon Email Registration
516
+
517
+ 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.
518
+
519
+ To bypass this measure, add `before_create :skip_confirmation!` to your `User` model (or equivalent).
520
+
521
+ ##### Example: bypass email confirmation
522
+
523
+ ~~~ruby
524
+ class User < ActiveRecord::Base
525
+ include DeviseTokenAuth::Concerns::User
526
+ before_create :skip_confirmation!
527
+ end
528
+ ~~~
529
+
530
+ ##### Note for ng-token-auth users:
531
+
532
+ If this `before_create :skip_confirmation!` callback is in place, the `$auth.submitRegistration` method will both register and authenticate users in a single step.
533
+
534
+ ## Custom Controller Overrides
535
+
536
+ The built-in controllers can be overridden with your own custom controllers.
537
+
538
+ 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.
539
+
540
+ ##### Example: controller overrides
541
+
542
+ ~~~ruby
543
+ # config/routes.rb
544
+ Rails.application.routes.draw do
545
+ ...
546
+ mount_devise_token_auth_for 'User', at: '/auth', controllers: {
547
+ token_validations: 'overrides/token_validations'
548
+ }
549
+ end
550
+
551
+ # app/controllers/overrides/token_validations_controller.rb
552
+ module Overrides
553
+ class TokenValidationsController < DeviseTokenAuth::TokenValidationsController
554
+
555
+ def validate_token
556
+ # @user will have been set by set_user_by_token concern
557
+ if @user
558
+ render json: {
559
+ data: @user.as_json(methods: :calculate_operating_thetan)
560
+ }
561
+ else
562
+ render json: {
563
+ success: false,
564
+ errors: ["Invalid login credentials"]
565
+ }, status: 401
566
+ end
567
+ end
568
+ end
569
+ end
570
+ ~~~
571
+
572
+ ##### Example: all :controller options with default settings:
573
+
574
+ ~~~ruby
575
+ mount_devise_token_auth_for 'User', at: '/auth', controllers: {
576
+ confirmations: 'devise_token_auth/confirmations',
577
+ passwords: 'devise_token_auth/passwords',
578
+ omniauth_callbacks: 'devise_token_auth/omniauth_callbacks',
579
+ registrations: 'devise_token_auth/registrations',
580
+ sessions: 'devise_token_auth/sessions',
581
+ token_validations: 'devise_token_auth/token_validations'
582
+ }
583
+ ~~~
584
+
585
+ **Note:** Controller overrides must implement the expected actions of the controllers that they replace.
586
+
587
+ ## Email Template Overrides
588
+
589
+ 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:
590
+
591
+ ~~~bash
592
+ rails generate devise_token_auth:install_views
593
+ ~~~
594
+
595
+ This will create two new files:
596
+
597
+ * `app/views/devise/mailer/reset_password_instructions.html.erb`
598
+ * `app/views/devise/mailer/confirmation_instructions.html.erb`
599
+
600
+ These files may be edited to suit your taste.
601
+
602
+ **Note:** if you choose to modify these templates, do not modify the `link_to` blocks unless you absolutely know what you are doing.
603
+
604
+ # Conceptual
605
+
606
+ None of the following information is required to use this gem, but read on if you're curious.
607
+
608
+ ## About token management
609
+
610
+ Tokens should be invalidated after each request to the API. The following diagram illustrates this concept:
611
+
612
+ ![password reset flow](https://github.com/lynndylanhurley/ng-token-auth/raw/master/test/app/images/flow/token-update-detail.jpg)
613
+
614
+ 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.
615
+
616
+ The only case where an expired token is allowed is during [batch requests](#about-batch-requests).
617
+
618
+ These measures are taken by default when using this gem.
619
+
620
+ ## About batch requests
621
+
622
+ 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:
623
+
624
+ #####Batch request example
625
+ ~~~javascript
626
+ $scope.getResourceData = function() {
627
+
628
+ $http.get('/api/restricted_resource_1').success(function(resp) {
629
+ // handle response
630
+ $scope.resource1 = resp.data;
631
+ });
632
+
633
+ $http.get('/api/restricted_resource_2').success(function(resp) {
634
+ // handle response
635
+ $scope.resource2 = resp.data;
636
+ });
637
+ };
638
+ ~~~
639
+
640
+ 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:
641
+
642
+ ![batch request overview](https://github.com/lynndylanhurley/ng-token-auth/raw/master/test/app/images/flow/batch-request-overview.jpg)
643
+
644
+ The "5 second" buffer in the diagram is the default used this gem.
645
+
646
+ The following diagram details the relationship between the client, server, and access tokens used over time when dealing with batch requests:
647
+
648
+ ![batch request detail](https://github.com/lynndylanhurley/ng-token-auth/raw/master/test/app/images/flow/batch-request-detail.jpg)
649
+
650
+ 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).
651
+
652
+ 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`.
653
+
654
+
655
+ # Security
656
+
657
+ This gem takes the following steps to ensure security.
658
+
659
+ This gem uses auth tokens that are:
660
+ * [changed after every request](#about-token-management),
661
+ * [of cryptographic strength](http://ruby-doc.org/stdlib-2.1.0/libdoc/securerandom/rdoc/SecureRandom.html),
662
+ * hashed using [BCrypt](https://github.com/codahale/bcrypt-ruby) (not stored in plain-text),
663
+ * securely compared (to protect against timing attacks),
664
+ * invalidated after 2 weeks (thus requiring users to login again)
665
+
666
+ These measures were inspired by [this stackoverflow post](http://stackoverflow.com/questions/18605294/is-devises-token-authenticatable-secure).
667
+
668
+ This gem further mitigates timing attacks by using [this technique](https://gist.github.com/josevalim/fb706b1e933ef01e4fb6).
669
+
670
+ But the most important step is to use HTTPS. You are on the hook for that.
671
+
672
+
673
+ # Contributing
674
+ Just send a pull request. I will grant you commit access if you send quality pull requests.
675
+
676
+ Guidelines will be posted if the need arises.
677
+
678
+ # License
679
+ This project uses the WTFPL