devise_token_auth 0.1.37.beta3 → 0.1.37.beta4

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of devise_token_auth might be problematic. Click here for more details.

checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: ffa6f5208f809271811e8f10ad47f507a6be3ac3
4
- data.tar.gz: 43213799e05d5e563942857af0c3cbfa2f615c9d
3
+ metadata.gz: 0c1401be1479787b9115c2aa8fd04adab21776de
4
+ data.tar.gz: 4bf54ad1a795451ae573144a78ba1b414437b223
5
5
  SHA512:
6
- metadata.gz: 51e5c2023671a2de2a8c02c516e0520e1f6f3024c49db891855c6fd76df4cf0525baa560229d7e23ead186457a1ebc5d02dd9ab223312ce7e5b7017f1ec5bb63
7
- data.tar.gz: 0dd625a07cf22e41c990a1c1bbb7b00ef9572ead21eb7ac7067acb1c90de3e0c376e2a44ee6db74996c64bb706fe159df41074ee4a97763794c813b463928e91
6
+ metadata.gz: 701cb424a22649841c9c3ece6a60417a1b31869c0b10fab9e38a6861090707cd379aa9cfe4b0d3f85308026ec247445df3347f49f19858a9a78ba48b7752522e
7
+ data.tar.gz: a94ca49f3d48a15c8af51e4ef502c428059c510088e32f63d3f29a0a4488a4ebab635c0cc8201470044a3bd4089d229b614c6f9ed5bcb3270e0e95fd90c7d101
data/README.md CHANGED
@@ -164,6 +164,8 @@ The following settings are available for configuration in `config/initializers/d
164
164
  | **`default_confirm_success_url`** | `nil` | By default this value is expected to be sent by the client so that the API knows where to redirect users after successful email confirmation. If this param is set, the API will redirect to this value when no value is provided by the cilent. |
165
165
  | **`default_password_reset_url`** | `nil` | By default this value is expected to be sent by the client so that the API knows where to redirect users after successful password resets. If this param is set, the API will redirect to this value when no value is provided by the cilent. |
166
166
  | **`redirect_whitelist`** | `nil` | As an added security measure, you can limit the URLs to which the API will redirect after email token validation (password reset, email confirmation, etc.). This value should be an array containing exact matches to the client URLs to be visited after validation. |
167
+ | **`enable_standard_devise_support`** | `false` | By default, only Bearer Token authentication is implemented out of the box. If, however, you wish to integrate with legacy Devise authentication, you can do so by enabling this flag. NOTE: This feature is highly experimental! |
168
+
167
169
 
168
170
  Additionally, you can configure other aspects of devise by manually creating the traditional devise.rb file at `config/initializers/devise.rb`. Here are some examples of what you can do in this file:
169
171
 
@@ -773,8 +775,16 @@ When posting issues, please include the following information to speed up the tr
773
775
 
774
776
  ### Can I use this gem alongside standard Devise?
775
777
 
776
- Yes! But you will need to use separate routes for standard Devise. So do something like this:
778
+ Yes! But you will need to enable the support use separate routes for standard Devise. So do something like this:
779
+
780
+ #### config/initializers/devise_token_auth.rb
781
+ ~~~ruby
782
+ DeviseTokenAuth.setup do |config|
783
+ # enable_standard_devise_support = false
784
+ end
785
+ ~~~
777
786
 
787
+ #### config/routes.rb
778
788
  ~~~ruby
779
789
  Rails.application.routes.draw do
780
790
 
@@ -31,12 +31,14 @@ module DeviseTokenAuth::Concerns::SetUserByToken
31
31
  # client_id isn't required, set to 'default' if absent
32
32
  @client_id ||= 'default'
33
33
 
34
- # check for an existing user, authenticated via warden/devise
35
- devise_warden_user = warden.user(rc.to_s.underscore.to_sym)
36
- if devise_warden_user && devise_warden_user.tokens[@client_id].nil?
37
- @used_auth_by_token = false
38
- @resource = devise_warden_user
39
- @resource.create_new_auth_token
34
+ # check for an existing user, authenticated via warden/devise, if enabled
35
+ if DeviseTokenAuth.enable_standard_devise_support
36
+ devise_warden_user = warden.user(rc.to_s.underscore.to_sym)
37
+ if devise_warden_user && devise_warden_user.tokens[@client_id].nil?
38
+ @used_auth_by_token = false
39
+ @resource = devise_warden_user
40
+ @resource.create_new_auth_token
41
+ end
40
42
  end
41
43
 
42
44
  # user has already been found and authenticated
@@ -54,7 +56,7 @@ module DeviseTokenAuth::Concerns::SetUserByToken
54
56
  user = uid && rc.find_by_uid(uid)
55
57
 
56
58
  if user && user.valid_token?(@token, @client_id)
57
- sign_in(:user, user, store: false, bypass: false)
59
+ sign_in(:user, user, store: false, bypass: true)
58
60
  return @resource = user
59
61
  else
60
62
  # zero all values previously set values
@@ -103,7 +103,7 @@ module DeviseTokenAuth
103
103
  config: params[:config]
104
104
  }))
105
105
  else
106
- raise ActionController::RoutingError.new('Not Found')
106
+ render_edit_error
107
107
  end
108
108
  end
109
109
 
@@ -179,6 +179,10 @@ module DeviseTokenAuth
179
179
  }, status: @error_status
180
180
  end
181
181
 
182
+ def render_edit_error
183
+ raise ActionController::RoutingError.new('Not Found')
184
+ end
185
+
182
186
  def render_update_error_unauthorized
183
187
  render json: {
184
188
  success: false,
@@ -178,6 +178,12 @@ module DeviseTokenAuth::Concerns::User
178
178
  last_token: last_token,
179
179
  updated_at: Time.now
180
180
  }
181
+
182
+ max_clients = DeviseTokenAuth.max_number_of_devices
183
+ while self.tokens.keys.length > 0 and max_clients < self.tokens.keys.length
184
+ oldest_token = self.tokens.min_by { |cid, v| v[:expiry] || v["expiry"] }
185
+ self.tokens.delete(oldest_token.first)
186
+ end
181
187
 
182
188
  self.save!
183
189
 
@@ -1,7 +1,21 @@
1
1
  class EmailValidator < ActiveModel::EachValidator
2
2
  def validate_each(record, attribute, value)
3
3
  unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
4
- record.errors[attribute] << (options[:message] || I18n.t("errors.not_email"))
4
+ record.errors[attribute] << email_invalid_message
5
5
  end
6
6
  end
7
- end
7
+
8
+ private
9
+
10
+ def email_invalid_message
11
+ # Try strictly set message:
12
+ message = options[:message]
13
+
14
+ if message.nil?
15
+ # Try DeviceTokenAuth translations or fallback to ActiveModel translations
16
+ message = I18n.t(:'errors.not_email', default: :'errors.messages.invalid')
17
+ end
18
+
19
+ message
20
+ end
21
+ end
@@ -1,5 +1,5 @@
1
- <p>Welcome <%= @email %>!</p>
1
+ <p><%= t(:welcome).capitalize + ' ' + @email %>!</p>
2
2
 
3
- <p>You can confirm your account email through the link below:</p>
3
+ <p><%= t '.confirm_link_msg' %> </p>
4
4
 
5
- <p><%= link_to 'Confirm my account', confirmation_url(@resource, {confirmation_token: @token, config: message['client-config'].to_s, redirect_url: message['redirect-url']}).html_safe %></p>
5
+ <p><%= link_to t('.confirm_account_link'), confirmation_url(@resource, {confirmation_token: @token, config: message['client-config'].to_s, redirect_url: message['redirect-url']}).html_safe %></p>
@@ -1,8 +1,8 @@
1
- <p>Hello <%= @resource.email %>!</p>
1
+ <p><%= t(:hello).capitalize %> <%= @resource.email %>!</p>
2
2
 
3
- <p>Someone has requested a link to change your password. You can do this through the link below.</p>
3
+ <p><%= t '.request_reset_link_msg' %></p>
4
4
 
5
- <p><%= link_to 'Change my password', edit_password_url(@resource, reset_password_token: @token, config: message['client-config'].to_s, redirect_url: message['redirect-url'].to_s).html_safe %></p>
5
+ <p><%= link_to t('.password_change_link'), edit_password_url(@resource, reset_password_token: @token, config: message['client-config'].to_s, redirect_url: message['redirect-url'].to_s).html_safe %></p>
6
6
 
7
- <p>If you didn't request this, please ignore this email.</p>
8
- <p>Your password won't change until you access the link above and create a new one.</p>
7
+ <p><%= t '.ignore_mail_msg' %></p>
8
+ <p><%= t '.no_changes_msg' %></p>
@@ -1,7 +1,7 @@
1
- <p>Hello <%= @resource.email %>!</p>
1
+ <p><%= t :hello %> <%= @resource.email %>!</p>
2
2
 
3
- <p>Your account has been locked due to an excessive number of unsuccessful sign in attempts.</p>
3
+ <p><%= t '.account_lock_msg' %></p>
4
4
 
5
- <p>Click the link below to unlock your account:</p>
5
+ <p><%= t '.unlock_link_msg' %></p>
6
6
 
7
- <p><%= link_to 'Unlock my account', unlock_url(@resource, unlock_token: @token).html_safe %></p>
7
+ <p><%= link_to t('.unlock_link'), unlock_url(@resource, unlock_token: @token) %></p>
@@ -0,0 +1,50 @@
1
+ de:
2
+ devise_token_auth:
3
+ sessions:
4
+ not_confirmed: "Ein E-Mail zu Bestätigung wurde an Ihre Adresse %{email} gesendet. Sie müssen den Anleitungsschritten im E-Mail folgen, um Ihren Account zu aktivieren"
5
+ bad_credentials: "Ungültige Anmeldeinformationen. Bitte versuchen Sie es erneut."
6
+ not_supported: "Verwenden Sie POST /sign_in zur Anmeldung. GET wird nicht unterstützt."
7
+ user_not_found: "Benutzer wurde nicht gefunden oder konnte nicht angemeldet werden."
8
+ token_validations:
9
+ invalid: "Ungültige Anmeldeinformationen"
10
+ registrations:
11
+ missing_confirm_success_url: "Fehlender Paramter `confirm_success_url`."
12
+ redirect_url_not_allowed: "Weiterleitung zu %{redirect_url} ist nicht gestattet."
13
+ email_already_exists: "Es gibt bereits einen Account für %{email}."
14
+ account_with_uid_destroyed: "Account mit der uid %{uid} wurde gelöscht."
15
+ account_to_destroy_not_found: "Der Account, der gelöscht werden soll, kann nicht gefunden werden."
16
+ user_not_found: "Benutzer kann nicht gefunden werden."
17
+ passwords:
18
+ missing_email: "Sie müssen eine E-Mail Adresse angeben."
19
+ missing_redirect_url: "Es fehlt der URL zu Weiterleitung."
20
+ not_allowed_redirect_url: "Weiterleitung zu %{redirect_url} ist nicht gestattet."
21
+ sended: "Ein E-Mail mit Anleitung zum Rücksetzen Ihres Passwortes wurde an %{email} gesendet."
22
+ user_not_found: "Der Benutzer mit E-Mail-Adresse '%{email}' kann nicht gefunden werden."
23
+ password_not_required: "Dieser Account benötigt kein Passwort. Melden Sie Sich stattdessen über Ihren Account bei %{provider} an."
24
+ missing_passwords: 'Sie müssen die Felder "Passwort" and "Passwortbestätigung" ausfüllen.'
25
+ successfully_updated: "Ihr Passwort wurde erfolgreich aktualisiert."
26
+ errors:
27
+ validate_sign_up_params: "Bitte übermitteln sie vollständige Anmeldeinformationen im Body des Requests."
28
+ validate_account_update_params: "Bitte übermitteln sie vollständige Informationen zur Aktualisierung im Body des Requests."
29
+ not_email: "ist keine E-Mail Adresse"
30
+ messages:
31
+ already_in_use: "bereits in Verwendung"
32
+ devise:
33
+ mailer:
34
+ confirmation_instructions:
35
+ subject: "Bestätigungs-"
36
+ confirm_link_msg: "Sie können Ihr Konto E-Mail über den untenstehenden Link bestätigen:"
37
+ confirm_account_link: "Ihr Konto zu bestätigen"
38
+ reset_password_instructions:
39
+ subject: "Wiederherstellungskennwort Anweisungen"
40
+ request_reset_link_msg: "Jemand hat einen Link auf Ihr Kennwort zu ändern angefordert. Sie können dies durch den folgenden Link tun:"
41
+ password_change_link: "Kennwort ändern"
42
+ ignore_mail_msg: "Wenn Sie nicht angefordert haben diese , ignorieren Sie bitte diese E-Mail:"
43
+ no_changes_msg: "Ihr Passwort wird nicht geändert , bis Sie auf den obigen Link zugreifen und eine neue erstellen ."
44
+ unlock_instructions:
45
+ subject: "entsperren Anweisungen"
46
+ account_lock_msg: "Ihr Konto wurde aufgrund einer übermäßigen Anzahl von erfolglosen Zeichen in Versuchen gesperrt."
47
+ unlock_link_msg: "Klicken Sie auf den Link unten , um Ihr Konto zu entsperren :"
48
+ unlock_link: "Entsperren Sie Ihr Konto "
49
+ hello: "hallo"
50
+ welcome: "willkommen"
@@ -23,10 +23,25 @@ en:
23
23
  password_not_required: "This account does not require a password. Sign in using your %{provider} account instead."
24
24
  missing_passwords: 'You must fill out the fields labeled "password" and "password confirmation".'
25
25
  successfully_updated: "Your password has been successfully updated."
26
-
27
26
  errors:
28
27
  validate_sign_up_params: "Please submit proper sign up data in request body."
29
28
  validate_account_update_params: "Please submit proper account update data in request body."
30
29
  not_email: "is not an email"
31
- message:
32
- already_in_use: already in use
30
+ messages:
31
+ already_in_use: already in use
32
+ devise:
33
+ mailer:
34
+ confirmation_instructions:
35
+ confirm_link_msg: "You can confirm your account email through the link below:"
36
+ confirm_account_link: Confirm my account
37
+ reset_password_instructions:
38
+ request_reset_link_msg: "Someone has requested a link to change your password. You can do this through the link below."
39
+ password_change_link: Change my password
40
+ ignore_mail_msg: "If you didn't request this, please ignore this email."
41
+ no_changes_msg: "Your password won't change until you access the link above and create a new one."
42
+ unlock_instructions:
43
+ account_lock_msg: Your account has been locked due to an excessive number of unsuccessful sign in attempts.
44
+ unlock_link_msg: "Click the link below to unlock your account:"
45
+ unlock_link: Unlock my account
46
+ hello: hello
47
+ welcome: welcome
@@ -23,10 +23,28 @@ es:
23
23
  password_not_required: "Esta cuenta no requiere contraseña. Iniciar sesión utilizando %{provider}."
24
24
  missing_passwords: 'Debe llenar los campos "contraseña" y "confirmación de contraseña".'
25
25
  successfully_updated: "Su contraseña ha sido actualizada con éxito."
26
-
27
26
  errors:
28
27
  validate_sign_up_params: "Los datos introducidos en la solicitud de acceso no son válidos."
29
28
  validate_account_update_params: "Los datos introducidos en la solicitud de actualización no son válidos."
30
29
  not_email: "no es un correo electrónico"
31
30
  messages:
32
- already_in_use: ya ha sido ocupado
31
+ already_in_use: ya ha sido ocupado
32
+ devise:
33
+ mailer:
34
+ confirmation_instructions:
35
+ subject: Instrucciones de confirmación
36
+ confirm_link_msg: "Para confirmar su cuenta ingrese en el siguiente link:"
37
+ confirm_account_link: Confirmar cuenta
38
+ reset_password_instructions:
39
+ subject: Instrucciones para restablecer su contraseña
40
+ request_reset_link_msg: "Ha solicitado un cambio de contraseña. Para continuar ingrese en el siguiente link:"
41
+ password_change_link: Cambiar contraseña
42
+ ignore_mail_msg: Por favor ignore este mensaje si no ha solicitado esta acción.
43
+ no_changes_msg: "Importante: Su contraseña no será actualizada a menos que ingrese en el link."
44
+ unlock_instructions:
45
+ subject: Instrucciones de desbloqueo
46
+ account_lock_msg: Su cuenta ha sido bloqueada debido a sucesivos intentos de ingresos fallidos
47
+ unlock_link_msg: "Para desbloquear su cuenta ingrese en el siguiente link:"
48
+ unlock_link: Desbloquear cuenta
49
+ hello: hola
50
+ welcome: bienvenido
@@ -1,7 +1,7 @@
1
1
  fr:
2
2
  devise_token_auth:
3
3
  sessions:
4
- not_confirmed: "Une email de confirmation de votre compte a été envoyé à %{email}. Merci de suivre les instructions afin de valider votre compte"
4
+ not_confirmed: "Un e-mail de confirmation de votre compte a été envoyé à %{email}. Merci de suivre les instructions afin de valider votre compte"
5
5
  bad_credentials: "Mot de passe ou identifiant invalide."
6
6
  not_supported: "Utilisez POST /sign_in pour la connexion. GET n'est pas supporté."
7
7
  user_not_found: "L'utilisateur est inconnu ou n'est pas connecté."
@@ -10,21 +10,41 @@ fr:
10
10
  registrations:
11
11
  missing_confirm_success_url: "Le paramètre `confirm_success_url` est manquant."
12
12
  redirect_url_not_allowed: "Redirection vers %{redirect_url} n'est pas autorisée."
13
- email_already_exists: "Un compte existe déjà avec cet email: %{email}"
13
+ email_already_exists: "Un compte existe déjà avec cette addresse e-mail: %{email}"
14
14
  account_with_uid_destroyed: "Le compte avec l'identifiant %{uid} a été supprimé."
15
- account_to_destroy_not_found: "Impossible de trouver le compte à supprimer."
16
- user_not_found: "Utilisateur non trouvé."
15
+ account_to_destroy_not_found: "Le compte à supprimer est introuvable."
16
+ user_not_found: "Utilisateur introuvable."
17
17
  passwords:
18
- missing_email: "Vous devez soumettre un email."
19
- missing_redirect_url: "Url de redirection manquante."
18
+ missing_email: "Vous devez soumettre un e-mail."
19
+ missing_redirect_url: "URL de redirection manquante."
20
20
  not_allowed_redirect_url: "Redirection vers %{redirect_url} n'est pas autorisée."
21
- sended: "Un email a été envoyé à %{email} avec les instructions pour réinitialiser votre mot de passe."
22
- user_not_found: "Impossible de trouver un utilisateur avec cet email: '%{email}'."
23
- password_not_required: "Ce compte ne demande pas de mot de passe. Connectez vous plutôt en utilisant %{provider}."
24
- missing_passwords: 'Vous devez remplir les champs "mt de passe" et "confirmation de mot de passe".'
21
+ sended: "Un e-mail a été envoyé à %{email} avec les instructions de réinitialisation du mot de passe."
22
+ user_not_found: "Impossible de trouver l'utilisateur avec l'adresse e-mail: '%{email}'."
23
+ password_not_required: "Ce compte ne demande pas de mot de passe. Connectez vous en utilisant %{provider}."
24
+ missing_passwords: 'Vous devez remplir les champs "mot de passe" et "confirmation de mot de passe".'
25
25
  successfully_updated: "Votre mot de passe a été correctement mis à jour."
26
-
27
26
  errors:
28
- validate_sign_up_params: "Les données de l'inscription dans le corps de la requête ne sont pas valides."
27
+ validate_sign_up_params: "Les données d'inscription dans le corps de la requête ne sont pas valides."
29
28
  validate_account_update_params: "Les données de mise à jour dans le corps de la requête ne sont pas valides."
30
- not_email: "n'est pas un email"
29
+ not_email: "n'est pas une adresse e-mail"
30
+ messages:
31
+ already_in_use: "déjà utilisé"
32
+ devise:
33
+ mailer:
34
+ confirmation_instructions:
35
+ subject: "Instructions de confirmation"
36
+ confirm_link_msg: "Vous pouvez confirmer votre compte e-mail via le lien ci-dessous :"
37
+ confirm_account_link: "Confirmer mon compte"
38
+ reset_password_instructions:
39
+ subject: "Instructions de récupération de mot de passe"
40
+ request_reset_link_msg: "Quelqu'un a demandé un lien pour changer votre mot de passe. Pour procéder ainsi, suivez le lien ci-dessous."
41
+ password_change_link: "Changer mon mot de passe"
42
+ ignore_mail_msg: "Si vous n'avez pas demandé cela, veuillez ignorer cet e-mail."
43
+ no_changes_msg: "Votre mot de passe ne changera pas tant que vous n'accédez pas au lien ci-dessus pour en créer un nouveau."
44
+ unlock_instructions:
45
+ subject: "Instructions de déblocage"
46
+ account_lock_msg: "Votre compte a été bloqué en raison de nombreuses tentatives de connection erronées."
47
+ unlock_link_msg: "Cliquez sur le lien ci-dessous pour déverrouiller votre compte:"
48
+ unlock_link: "Déverrouiller mon compte"
49
+ hello: bonjour
50
+ welcome: bienvenue
@@ -23,8 +23,28 @@ pl:
23
23
  password_not_required: "To konto nie wymaga podania hasła. Zaloguj się używając konta %{provider}."
24
24
  missing_passwords: 'Musisz wypełnić wszystkie pola z etykietą "hasło" oraz "potwierdzenie hasła".'
25
25
  successfully_updated: "Twoje hasło zostało zaktualizowane."
26
-
27
26
  errors:
28
27
  validate_sign_up_params: "Proszę dostarczyć odpowiednie dane logowania w ciele zapytania."
29
28
  validate_account_update_params: "Proszę dostarczyć odpowiednie dane aktualizacji konta w ciele zapytania."
30
29
  not_email: "nie jest prawidłowym adresem e-mail"
30
+ messages:
31
+ already_in_use: "już w użyciu"
32
+ devise:
33
+ mailer:
34
+ confirmation_instructions:
35
+ subject: "Instrukcji potwierdzania"
36
+ confirm_link_msg: "Możesz potwierdzić swój e-mail konta poprzez link poniżej :"
37
+ confirm_account_link: "Potwierdź swoje konto"
38
+ reset_password_instructions:
39
+ subject: "Instrukcje resetowania hasła"
40
+ request_reset_link_msg: "Ktoś o link do zmiany hasła . Można to zrobić za pośrednictwem linku poniżej ."
41
+ password_change_link: "Zmień hasło"
42
+ ignore_mail_msg: "Jeśli jej nie potrzebuję , zignoruj ​​tę wiadomość."
43
+ no_changes_msg: "Twoje hasło nie zmieni , dopóki dostęp powyższy link i utwórz nowy ."
44
+ unlock_instructions:
45
+ subject: "Instrukcje do odblokowania"
46
+ account_lock_msg: "Twoje konto zostało zablokowane z powodu zbyt dużej liczby nieudanych znak w próbach ."
47
+ unlock_link_msg: "Kliknij poniższy link, aby odblokować konto :"
48
+ unlock_link: "Odblokować konto"
49
+ hello: halo
50
+ welcome: witam
@@ -23,8 +23,28 @@ pt-BR:
23
23
  password_not_required: "Esta conta não necessita de uma senha. Faça login utilizando %{provider}."
24
24
  missing_passwords: 'Preencha a senha e a confirmação de senha.'
25
25
  successfully_updated: "Senha atualizada com sucesso."
26
-
27
26
  errors:
28
27
  validate_sign_up_params: "Os dados submetidos na requisição de cadastro são inválidos."
29
28
  validate_account_update_params: "Os dados submetidos para atualização de conta são inválidos."
30
29
  not_email: "não é um e-mail"
30
+ messages:
31
+ already_in_use: "em uso"
32
+ devise:
33
+ mailer:
34
+ confirmation_instructions:
35
+ subject: "Instruções de confirmação"
36
+ confirm_link_msg: "Você pode confirmar a sua conta de e-mail através do link abaixo :"
37
+ confirm_account_link: "Confirme conta"
38
+ reset_password_instructions:
39
+ subject: "Instruções para redefinir sua senha"
40
+ request_reset_link_msg: "Alguém pediu um link para mudar sua senha. Você pode fazer isso através do link abaixo "
41
+ password_change_link: "Alterar a senha"
42
+ ignore_mail_msg: "Se você não pediu isso, por favor, ignore este e-mail."
43
+ no_changes_msg: "Sua senha não será alterada até que você acessar o link acima e criar um novo."
44
+ unlock_instructions:
45
+ subject: "Instruções de desbloqueio"
46
+ account_lock_msg: "A sua conta foi bloqueada devido a um número excessivo de sinal de sucesso em tentativas."
47
+ unlock_link_msg: "Clique no link abaixo para desbloquear sua conta:"
48
+ unlock_link: "Desbloquear minha conta"
49
+ hello: "olá"
50
+ welcome: "bem-vindo"
@@ -1,4 +1,4 @@
1
- pt-PT:
1
+ pt:
2
2
  devise_token_auth:
3
3
  sessions:
4
4
  not_confirmed: "Uma mensagem com um link de confirmação foi enviado para seu endereço de e-mail. Você precisa confirmar sua conta antes de continuar."
@@ -23,8 +23,28 @@ pt-PT:
23
23
  password_not_required: "Esta conta não necessita de uma senha. Faça login utilizando %{provider}."
24
24
  missing_passwords: 'Preencha a senha e a confirmação de senha.'
25
25
  successfully_updated: "Senha atualizada com sucesso."
26
-
27
26
  errors:
28
27
  validate_sign_up_params: "Os dados submetidos na requisição de registo são inválidos."
29
28
  validate_account_update_params: "Os dados submetidos para atualização de conta são inválidos."
30
- not_email: "não é um e-mail"
29
+ not_email: "não é um e-mail"
30
+ messages:
31
+ already_in_use: "em uso"
32
+ devise:
33
+ mailer:
34
+ confirmation_instructions:
35
+ subject: "Instruções de confirmação"
36
+ confirm_link_msg: "Você pode confirmar a sua conta de e-mail através do link abaixo :"
37
+ confirm_account_link: "Confirme conta"
38
+ reset_password_instructions:
39
+ subject: "Instruções para redefinir sua senha"
40
+ request_reset_link_msg: "Alguém pediu um link para mudar sua senha. Você pode fazer isso através do link abaixo "
41
+ password_change_link: "Alterar a senha"
42
+ ignore_mail_msg: "Se você não pediu isso, por favor, ignore este e-mail."
43
+ no_changes_msg: "Sua senha não será alterada até que você acessar o link acima e criar um novo."
44
+ unlock_instructions:
45
+ subject: "Instruções de desbloqueio"
46
+ account_lock_msg: "A sua conta foi bloqueada devido a um número excessivo de sinal de sucesso em tentativas."
47
+ unlock_link_msg: "Clique no link abaixo para desbloquear sua conta:"
48
+ unlock_link: "Desbloquear minha conta"
49
+ hello: "olá"
50
+ welcome: "bem-vindo"
@@ -0,0 +1,51 @@
1
+ ru:
2
+ devise_token_auth:
3
+ sessions:
4
+ not_confirmed: "Письмо с подтверждением Вашей учетной записи %{email} отправлено на электронную почту. Вы должны следовать инструкциям, приведенным в письме, прежде чем Ваша учетная запись сможет быть активирована"
5
+ bad_credentials: "Неверные логин или пароль. Пожалуйста, попробуйте еще раз."
6
+ not_supported: "Используйте POST /sign_in для входа. GET запросы не поддерживаются."
7
+ user_not_found: "Пользователь не найден или не вошел."
8
+ token_validations:
9
+ invalid: "Неверные данные для входа"
10
+ registrations:
11
+ missing_confirm_success_url: "Отсутствует параметр `confirm_success_url`."
12
+ redirect_url_not_allowed: "Переадресация на %{redirect_url} не разрешена."
13
+ email_already_exists: "Учетная запись для %{email} уже существует"
14
+ account_with_uid_destroyed: "Учетная запись с uid %{uid} удалена."
15
+ account_to_destroy_not_found: "Не удается найти учетную запись для удаления."
16
+ user_not_found: "Пользователь не найден."
17
+ passwords:
18
+ missing_email: "Вы должны указать адрес электронной почты."
19
+ missing_redirect_url: "Отсутствует адрес переадресации."
20
+ not_allowed_redirect_url: "Переадресация на %{redirect_url} не разрешена."
21
+ sended: "Инструкция по восстановлению пароля отправлена на Вашу электронную почту %{email}."
22
+ user_not_found: "Не удается найти пользователя с электронной почтой '%{email}'."
23
+ password_not_required: "Эта учетная запись не требует пароля. Войдите используя учетную запись %{provider}."
24
+ missing_passwords: 'Вы должны заполнить поля "пароль" и "повторите пароль".'
25
+ successfully_updated: "Ваш пароль успешно обновлён."
26
+ errors:
27
+ validate_sign_up_params: "Пожалуйста, укажите надлежащие данные для регистрации в теле запроса."
28
+ validate_account_update_params: "Пожалуйста, укажите надлежащие данные для обновления учетной записи в теле запроса."
29
+ not_email: "не является электронной почтой"
30
+ messages:
31
+ already_in_use: "уже используется"
32
+ devise:
33
+ mailer:
34
+ confirmation_instructions:
35
+ subject: "Инструкции подтверждения"
36
+ confirm_link_msg: "Вы можете подтвердить ваш адрес электронной почты через ссылку ниже :"
37
+ confirm_account_link: Подтвердите свой ​​счет
38
+ reset_password_instructions:
39
+ subject: "Инструкции для восстановления пароля"
40
+ request_reset_link_msg: "Кто-то просил ссылку , чтобы изменить пароль . Вы можете сделать это через ссылку ниже."
41
+ password_change_link: "Изменить пароль"
42
+ ignore_mail_msg: "If you didn't request this, please ignore this email."
43
+ no_changes_msg: "Ваш пароль не изменится, пока вы не открыть ссылку выше и создать новый."
44
+ unlock_instructions:
45
+ subject: "Разблокировать Инструкции"
46
+ account_lock_msg: "Ваш аккаунт был заблокирован из-за чрезмерного количества неудачных попыток в знак ."
47
+ unlock_link_msg: "Нажмите на ссылку ниже, чтобы разблокировать свой ​​аккаунт :"
48
+ unlock_link: "Открой свой ​​аккаунт"
49
+ hello: "Здравствуйте"
50
+ welcome: "Добро пожаловат"
51
+
@@ -10,15 +10,18 @@ module DeviseTokenAuth
10
10
  end
11
11
 
12
12
  mattr_accessor :change_headers_on_each_request,
13
+ :max_number_of_devices,
13
14
  :token_lifespan,
14
15
  :batch_request_buffer_throttle,
15
16
  :omniauth_prefix,
16
17
  :default_confirm_success_url,
17
18
  :default_password_reset_url,
18
19
  :redirect_whitelist,
19
- :check_current_password_before_update
20
+ :check_current_password_before_update,
21
+ :enable_standard_devise_support
20
22
 
21
23
  self.change_headers_on_each_request = true
24
+ self.max_number_of_devices = 10
22
25
  self.token_lifespan = 2.weeks
23
26
  self.batch_request_buffer_throttle = 5.seconds
24
27
  self.omniauth_prefix = '/omniauth'
@@ -26,6 +29,7 @@ module DeviseTokenAuth
26
29
  self.default_password_reset_url = nil
27
30
  self.redirect_whitelist = nil
28
31
  self.check_current_password_before_update = false
32
+ self.enable_standard_devise_support = false
29
33
 
30
34
  def self.setup(&block)
31
35
  yield self
@@ -33,7 +37,7 @@ module DeviseTokenAuth
33
37
  Rails.application.config.after_initialize do
34
38
  if defined?(::OmniAuth)
35
39
  ::OmniAuth::config.path_prefix = Devise.omniauth_path_prefix = self.omniauth_prefix
36
-
40
+
37
41
 
38
42
  # Omniauth currently does not pass along omniauth.params upon failure redirect
39
43
  # see also: https://github.com/intridea/omniauth/issues/626
@@ -5,8 +5,9 @@ module DeviseTokenAuth::Url
5
5
 
6
6
  res = "#{uri.scheme}://#{uri.host}"
7
7
  res += ":#{uri.port}" if (uri.port and uri.port != 80 and uri.port != 443)
8
- res += "#{uri.path}" if uri.path
9
- res += "?#{params.to_query}"
8
+ res += "#{uri.path}" if uri.path
9
+ query = [uri.query, params.to_query].reject(&:blank?).join('&')
10
+ res += "?#{query}"
10
11
  res += "##{uri.fragment}" if uri.fragment
11
12
 
12
13
  return res
@@ -1,3 +1,3 @@
1
1
  module DeviseTokenAuth
2
- VERSION = "0.1.37.beta3"
2
+ VERSION = "0.1.37.beta4"
3
3
  end
@@ -3,26 +3,35 @@ DeviseTokenAuth.setup do |config|
3
3
  # client is responsible for keeping track of the changing tokens. Change
4
4
  # this to false to prevent the Authorization header from changing after
5
5
  # each request.
6
- #config.change_headers_on_each_request = true
6
+ # config.change_headers_on_each_request = true
7
7
 
8
8
  # By default, users will need to re-authenticate after 2 weeks. This setting
9
9
  # determines how long tokens will remain valid after they are issued.
10
- #config.token_lifespan = 2.weeks
10
+ # config.token_lifespan = 2.weeks
11
+
12
+ # Sets the max number of concurrent devices per user, which is 10 by default.
13
+ # After this limit is reached, the oldest tokens will be removed.
14
+ # config.max_number_of_devices = 10
11
15
 
12
16
  # Sometimes it's necessary to make several requests to the API at the same
13
17
  # time. In this case, each request in the batch will need to share the same
14
18
  # auth token. This setting determines how far apart the requests can be while
15
19
  # still using the same auth token.
16
- #config.batch_request_buffer_throttle = 5.seconds
20
+ # config.batch_request_buffer_throttle = 5.seconds
17
21
 
18
22
  # This route will be the prefix for all oauth2 redirect callbacks. For
19
23
  # example, using the default '/omniauth', the github oauth2 provider will
20
24
  # redirect successful authentications to '/omniauth/github/callback'
21
- #config.omniauth_prefix = "/omniauth"
25
+ # config.omniauth_prefix = "/omniauth"
22
26
 
23
27
  # By defult sending current password is not needed for the password update.
24
28
  # Uncomment to enforce current_password param to be checked before all
25
29
  # attribute updates. Set it to :password if you want it to be checked only if
26
30
  # password is updated.
27
31
  # config.check_current_password_before_update = :attributes
28
- end
32
+
33
+ # By default, only Bearer Token authentication is implemented out of the box.
34
+ # If, however, you wish to integrate with legacy Devise authentication, you can
35
+ # do so by enabling this flag. NOTE: This feature is highly experimental!
36
+ # enable_standard_devise_support = false
37
+ end
@@ -284,14 +284,25 @@ class DemoUserControllerTest < ActionDispatch::IntegrationTest
284
284
  end
285
285
  end
286
286
 
287
- describe 'existing Warden authentication with ignored token data' do
287
+ end
288
+
289
+ describe 'enable_standard_devise_support' do
290
+
291
+ before do
292
+ @resource = users(:confirmed_email_user)
293
+ @auth_headers = @resource.create_new_auth_token
294
+ DeviseTokenAuth.enable_standard_devise_support = true
295
+ end
296
+
297
+ describe 'Existing Warden authentication' do
288
298
  before do
289
299
  @resource = users(:second_confirmed_email_user)
290
300
  @resource.skip_confirmation!
291
301
  @resource.save!
292
302
  login_as( @resource, :scope => :user)
293
303
 
294
- get '/demo/members_only', {}, @auth_headers
304
+ # no auth headers sent, testing that warden authenticates correctly.
305
+ get '/demo/members_only', {}, nil
295
306
 
296
307
  @resp_token = response.headers['access-token']
297
308
  @resp_client_id = response.headers['client']
@@ -311,6 +322,19 @@ class DemoUserControllerTest < ActionDispatch::IntegrationTest
311
322
  it 'should not define current_mang' do
312
323
  refute_equal @resource, @controller.current_mang
313
324
  end
325
+
326
+
327
+ it 'should increase the number of tokens by a factor of 2 up to 11' do
328
+ @first_token = @resource.tokens.keys.first
329
+
330
+ DeviseTokenAuth.max_number_of_devices = 11
331
+ (1..10).each do |n|
332
+ assert_equal [11, 2*n].min, @resource.reload.tokens.keys.length
333
+ get '/demo/members_only', {}, nil
334
+ end
335
+
336
+ assert_not_includes @resource.reload.tokens.keys, @first_token
337
+ end
314
338
  end
315
339
 
316
340
  it 'should return success status' do
@@ -329,69 +353,69 @@ class DemoUserControllerTest < ActionDispatch::IntegrationTest
329
353
  assert @resp_client_id
330
354
  end
331
355
 
332
- it "should not use the existing token's client" do
333
- refute_equal @auth_headers['client'], @resp_client_id
334
- end
335
-
336
356
  it "should return the user's uid in the auth header" do
337
357
  assert @resp_uid
338
358
  end
359
+ end
339
360
 
340
- it "should not return the token user's uid in the auth header" do
341
- refute_equal @resp_uid, @auth_headers['uid']
361
+ describe 'existing Warden authentication with ignored token data' do
362
+ before do
363
+ @resource = users(:second_confirmed_email_user)
364
+ @resource.skip_confirmation!
365
+ @resource.save!
366
+ login_as( @resource, :scope => :user)
367
+
368
+ get '/demo/members_only', {}, @auth_headers
369
+
370
+ @resp_token = response.headers['access-token']
371
+ @resp_client_id = response.headers['client']
372
+ @resp_expiry = response.headers['expiry']
373
+ @resp_uid = response.headers['uid']
342
374
  end
343
- end
344
- end
345
375
 
346
- describe 'Existing Warden authentication' do
347
- before do
348
- @resource = users(:second_confirmed_email_user)
349
- @resource.skip_confirmation!
350
- @resource.save!
351
- login_as( @resource, :scope => :user)
376
+ describe 'devise mappings' do
377
+ it 'should define current_user' do
378
+ assert_equal @resource, @controller.current_user
379
+ end
352
380
 
353
- # no auth headers sent, testing that warden authenticates correctly.
354
- get '/demo/members_only', {}, nil
381
+ it 'should define user_signed_in?' do
382
+ assert @controller.user_signed_in?
383
+ end
355
384
 
356
- @resp_token = response.headers['access-token']
357
- @resp_client_id = response.headers['client']
358
- @resp_expiry = response.headers['expiry']
359
- @resp_uid = response.headers['uid']
360
- end
385
+ it 'should not define current_mang' do
386
+ refute_equal @resource, @controller.current_mang
387
+ end
388
+ end
361
389
 
362
- describe 'devise mappings' do
363
- it 'should define current_user' do
364
- assert_equal @resource, @controller.current_user
390
+ it 'should return success status' do
391
+ assert_equal 200, response.status
365
392
  end
366
393
 
367
- it 'should define user_signed_in?' do
368
- assert @controller.user_signed_in?
394
+ it 'should receive new token after successful request' do
395
+ assert @resp_token
369
396
  end
370
397
 
371
- it 'should not define current_mang' do
372
- refute_equal @resource, @controller.current_mang
398
+ it 'should set the token expiry in the auth header' do
399
+ assert @resp_expiry
373
400
  end
374
- end
375
401
 
376
- it 'should return success status' do
377
- assert_equal 200, response.status
378
- end
402
+ it 'should return the client id in the auth header' do
403
+ assert @resp_client_id
404
+ end
379
405
 
380
- it 'should receive new token after successful request' do
381
- assert @resp_token
382
- end
406
+ it "should not use the existing token's client" do
407
+ refute_equal @auth_headers['client'], @resp_client_id
408
+ end
383
409
 
384
- it 'should set the token expiry in the auth header' do
385
- assert @resp_expiry
386
- end
410
+ it "should return the user's uid in the auth header" do
411
+ assert @resp_uid
412
+ end
387
413
 
388
- it 'should return the client id in the auth header' do
389
- assert @resp_client_id
414
+ it "should not return the token user's uid in the auth header" do
415
+ refute_equal @resp_uid, @auth_headers['uid']
416
+ end
390
417
  end
391
418
 
392
- it "should return the user's uid in the auth header" do
393
- assert @resp_uid
394
- end
395
419
  end
396
420
 
397
421
  end
@@ -763,13 +763,15 @@ class DeviseTokenAuth::RegistrationsControllerTest < ActionDispatch::Integration
763
763
  end
764
764
 
765
765
  test "Mang should be destroyed" do
766
+ @resource.skip_confirmation!
767
+ @resource.save!
766
768
  @auth_headers = @resource.create_new_auth_token
767
769
  @client_id = @auth_headers['client']
768
770
 
769
771
  # ensure request is not treated as batch request
770
772
  age_token(@resource, @client_id)
771
773
 
772
- delete "/mangs", {}, @auth_headers
774
+ xhr :delete, "/mangs", {}, @auth_headers
773
775
 
774
776
  assert_equal 200, response.status
775
777
  refute Mang.where(id: @resource.id).first
@@ -7,5 +7,22 @@ class DeviseTokenAuth::UrlTest < ActiveSupport::TestCase
7
7
  url = 'http://example.com#fragment'
8
8
  assert_equal DeviseTokenAuth::Url.send(:generate, url, params), "http://example.com?client_id=123#fragment"
9
9
  end
10
+
11
+ describe 'with existing query params' do
12
+ test 'should preserve existing query params' do
13
+ url = 'http://example.com?a=1'
14
+ assert_equal DeviseTokenAuth::Url.send(:generate, url), "http://example.com?a=1"
15
+ end
16
+
17
+ test 'should marge existing query params with new ones' do
18
+ params = {client_id: 123}
19
+ url = 'http://example.com?a=1'
20
+ assert_equal DeviseTokenAuth::Url.send(:generate, url, params), "http://example.com?a=1&client_id=123"
21
+ end
22
+
23
+
24
+ end
25
+
26
+
10
27
  end
11
28
  end
data/test/test_helper.rb CHANGED
@@ -40,13 +40,17 @@ class ActiveSupport::TestCase
40
40
  # Add more helper methods to be used by all tests here...
41
41
 
42
42
  def age_token(user, client_id)
43
- user.tokens[client_id]['updated_at'] = Time.now - (DeviseTokenAuth.batch_request_buffer_throttle + 10.seconds)
44
- user.save!
43
+ if user.tokens[client_id]
44
+ user.tokens[client_id]['updated_at'] = Time.now - (DeviseTokenAuth.batch_request_buffer_throttle + 10.seconds)
45
+ user.save!
46
+ end
45
47
  end
46
48
 
47
49
  def expire_token(user, client_id)
48
- user.tokens[client_id]['expiry'] = (Time.now - (DeviseTokenAuth.token_lifespan.to_f + 10.seconds)).to_i
49
- user.save!
50
+ if user.tokens[client_id]
51
+ user.tokens[client_id]['expiry'] = (Time.now - (DeviseTokenAuth.token_lifespan.to_f + 10.seconds)).to_i
52
+ user.save!
53
+ end
50
54
  end
51
55
  end
52
56
 
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: devise_token_auth
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.37.beta3
4
+ version: 0.1.37.beta4
5
5
  platform: ruby
6
6
  authors:
7
7
  - Lynn Hurley
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2015-10-27 00:00:00.000000000 Z
11
+ date: 2015-12-10 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: rails
@@ -90,7 +90,6 @@ files:
90
90
  - LICENSE
91
91
  - README.md
92
92
  - Rakefile
93
- - app/controllers/devise_token_auth/CHANGELOG.md
94
93
  - app/controllers/devise_token_auth/application_controller.rb
95
94
  - app/controllers/devise_token_auth/concerns/set_user_by_token.rb
96
95
  - app/controllers/devise_token_auth/confirmations_controller.rb
@@ -106,12 +105,14 @@ files:
106
105
  - app/views/devise/mailer/unlock_instructions.html.erb
107
106
  - app/views/devise_token_auth/omniauth_external_window.html.erb
108
107
  - config/initializers/devise.rb
108
+ - config/locales/de.yml
109
109
  - config/locales/en.yml
110
110
  - config/locales/es.yml
111
111
  - config/locales/fr.yml
112
112
  - config/locales/pl.yml
113
113
  - config/locales/pt-BR.yml
114
- - config/locales/pt-PT.yml
114
+ - config/locales/pt.yml
115
+ - config/locales/ru.yml
115
116
  - lib/devise_token_auth.rb
116
117
  - lib/devise_token_auth/controllers/helpers.rb
117
118
  - lib/devise_token_auth/controllers/url_helpers.rb
@@ -209,7 +210,7 @@ files:
209
210
  - test/dummy/lib/migration_database_helper.rb
210
211
  - test/dummy/tmp/generators/app/models/user.rb
211
212
  - test/dummy/tmp/generators/config/initializers/devise_token_auth.rb
212
- - test/dummy/tmp/generators/db/migrate/20151025020205_devise_token_auth_create_users.rb
213
+ - test/dummy/tmp/generators/db/migrate/20151027080542_devise_token_auth_create_users.rb
213
214
  - test/integration/navigation_test.rb
214
215
  - test/lib/devise_token_auth/url_test.rb
215
216
  - test/lib/generators/devise_token_auth/install_generator_test.rb
@@ -325,7 +326,7 @@ test_files:
325
326
  - test/dummy/README.rdoc
326
327
  - test/dummy/tmp/generators/app/models/user.rb
327
328
  - test/dummy/tmp/generators/config/initializers/devise_token_auth.rb
328
- - test/dummy/tmp/generators/db/migrate/20151025020205_devise_token_auth_create_users.rb
329
+ - test/dummy/tmp/generators/db/migrate/20151027080542_devise_token_auth_create_users.rb
329
330
  - test/integration/navigation_test.rb
330
331
  - test/lib/devise_token_auth/url_test.rb
331
332
  - test/lib/generators/devise_token_auth/install_generator_test.rb
@@ -1,10 +0,0 @@
1
- +<a name="0.1.33"></a>
2
- +# 0.1.33 (2015-??-??)
3
- +
4
- +## Features
5
- +
6
- +- **Improved OAuth Flow**: Supports new OAuth window flows, allowing options for `sameWindow`, `newWindow`, and `inAppBrowser`
7
- +
8
- +## Breaking Changes
9
- +
10
- +- The new OAuth redirect behavior now defaults to `sameWindow` mode, whereas the previous implementation mimicked the functionality of `newWindow`. This was changed due to limitations with the `postMessage` API support in popular browsers, as well as feedback from user-experience testing.