You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

435 lines
13 KiB

Add WebAuthn as an alternative 2FA method (#14466) * feat: add possibility of adding WebAuthn security keys to use as 2FA This adds a basic UI for enabling WebAuthn 2FA. We did a little refactor to the Settings page for editing the 2FA methods – now it will list the methods that are available to the user (TOTP and WebAuthn) and from there they'll be able to add or remove any of them. Also, it's worth mentioning that for enabling WebAuthn it's required to have TOTP enabled, so the first time that you go to the 2FA Settings page, you'll be asked to set it up. This work was inspired by the one donde by Github in their platform, and despite it could be approached in different ways, we decided to go with this one given that we feel that this gives a great UX. Co-authored-by: Facundo Padula <facundo.padula@cedarcode.com> * feat: add request for WebAuthn as second factor at login if enabled This commits adds the feature for using WebAuthn as a second factor for login when enabled. If users have WebAuthn enabled, now a page requesting for the use of a WebAuthn credential for log in will appear, although a link redirecting to the old page for logging in using a two-factor code will also be present. Co-authored-by: Facundo Padula <facundo.padula@cedarcode.com> * feat: add possibility of deleting WebAuthn Credentials Co-authored-by: Facundo Padula <facundo.padula@cedarcode.com> * feat: disable WebAuthn when an Admin disables 2FA for a user Co-authored-by: Facundo Padula <facundo.padula@cedarcode.com> * feat: remove ability to disable TOTP leaving only WebAuthn as 2FA Following examples form other platforms like Github, we decided to make Webauthn 2FA secondary to 2FA with TOTP, so that we removed the possibility of removing TOTP authentication only, leaving users with just WEbAuthn as 2FA. Instead, users will have to click on 'Disable 2FA' in order to remove second factor auth. The reason for WebAuthn being secondary to TOPT is that in that way, users will still be able to log in using their code from their phone's application if they don't have their security keys with them – or maybe even lost them. * We had to change a little the flow for setting up TOTP, given that now it's possible to setting up again if you already had TOTP, in order to let users modify their authenticator app – given that now it's not possible for them to disable TOTP and set it up again with another authenticator app. So, basically, now instead of storing the new `otp_secret` in the user, we store it in the session until the process of set up is finished. This was because, as it was before, when users clicked on 'Edit' in the new two-factor methods lists page, but then went back without finishing the flow, their `otp_secret` had been changed therefore invalidating their previous authenticator app, making them unable to log in again using TOTP. Co-authored-by: Facundo Padula <facundo.padula@cedarcode.com> * refactor: fix eslint errors The PR build was failing given that linting returning some errors. This commit attempts to fix them. * refactor: normalize i18n translations The build was failing given that i18n translations files were not normalized. This commits fixes that. * refactor: avoid having the webauthn gem locked to a specific version * refactor: use symbols for routes without '/' * refactor: avoid sending webauthn disabled email when 2FA is disabled When an admins disable 2FA for users, we were sending two mails to them, one notifying that 2FA was disabled and the other to notify that WebAuthn was disabled. As the second one is redundant since the first email includes it, we can remove it and send just one email to users. * refactor: avoid creating new env variable for webauthn_origin config * refactor: improve flash error messages for webauthn pages Co-authored-by: Facundo Padula <facundo.padula@cedarcode.com>
3 years ago
Add WebAuthn as an alternative 2FA method (#14466) * feat: add possibility of adding WebAuthn security keys to use as 2FA This adds a basic UI for enabling WebAuthn 2FA. We did a little refactor to the Settings page for editing the 2FA methods – now it will list the methods that are available to the user (TOTP and WebAuthn) and from there they'll be able to add or remove any of them. Also, it's worth mentioning that for enabling WebAuthn it's required to have TOTP enabled, so the first time that you go to the 2FA Settings page, you'll be asked to set it up. This work was inspired by the one donde by Github in their platform, and despite it could be approached in different ways, we decided to go with this one given that we feel that this gives a great UX. Co-authored-by: Facundo Padula <facundo.padula@cedarcode.com> * feat: add request for WebAuthn as second factor at login if enabled This commits adds the feature for using WebAuthn as a second factor for login when enabled. If users have WebAuthn enabled, now a page requesting for the use of a WebAuthn credential for log in will appear, although a link redirecting to the old page for logging in using a two-factor code will also be present. Co-authored-by: Facundo Padula <facundo.padula@cedarcode.com> * feat: add possibility of deleting WebAuthn Credentials Co-authored-by: Facundo Padula <facundo.padula@cedarcode.com> * feat: disable WebAuthn when an Admin disables 2FA for a user Co-authored-by: Facundo Padula <facundo.padula@cedarcode.com> * feat: remove ability to disable TOTP leaving only WebAuthn as 2FA Following examples form other platforms like Github, we decided to make Webauthn 2FA secondary to 2FA with TOTP, so that we removed the possibility of removing TOTP authentication only, leaving users with just WEbAuthn as 2FA. Instead, users will have to click on 'Disable 2FA' in order to remove second factor auth. The reason for WebAuthn being secondary to TOPT is that in that way, users will still be able to log in using their code from their phone's application if they don't have their security keys with them – or maybe even lost them. * We had to change a little the flow for setting up TOTP, given that now it's possible to setting up again if you already had TOTP, in order to let users modify their authenticator app – given that now it's not possible for them to disable TOTP and set it up again with another authenticator app. So, basically, now instead of storing the new `otp_secret` in the user, we store it in the session until the process of set up is finished. This was because, as it was before, when users clicked on 'Edit' in the new two-factor methods lists page, but then went back without finishing the flow, their `otp_secret` had been changed therefore invalidating their previous authenticator app, making them unable to log in again using TOTP. Co-authored-by: Facundo Padula <facundo.padula@cedarcode.com> * refactor: fix eslint errors The PR build was failing given that linting returning some errors. This commit attempts to fix them. * refactor: normalize i18n translations The build was failing given that i18n translations files were not normalized. This commits fixes that. * refactor: avoid having the webauthn gem locked to a specific version * refactor: use symbols for routes without '/' * refactor: avoid sending webauthn disabled email when 2FA is disabled When an admins disable 2FA for users, we were sending two mails to them, one notifying that 2FA was disabled and the other to notify that WebAuthn was disabled. As the second one is redundant since the first email includes it, we can remove it and send just one email to users. * refactor: avoid creating new env variable for webauthn_origin config * refactor: improve flash error messages for webauthn pages Co-authored-by: Facundo Padula <facundo.padula@cedarcode.com>
3 years ago
Fix “Email changed” notification sometimes having wrong e-mail (#13475) * Fix “Email changed” notification sometimes having wrong e-mail Fixes #6778 The root of the issue is that `send_devise_notification` was called before the changes were properly commited to the database, causing the mailer to pick previous values if running too early. Devise's documentation provides guidance on how to handle that[1][2], however, I have found it to not be working, as the following happens, in that order: - `send_devise_notification` is called for the `email_changed` notification. In that case, `changed?` is false and `saved_changes?` is true, so if we use the former, we have the same issue. - the `after_commit` hook is called - `send_devise_notification` is called for the `confirmation_instructions` notification. In that case, `changed?` is still false, and `saved_changes?` still true, so if we use the latter, that second notification email is simply not going to be sent (as we would be queuing the notification *after* executing the after_commit hook). This is because it may be called from either an `after_update` or `after_commit` hook, the difference not being a call to `save` but the transaction actually being committed to the database. This may arguably be a bug in Devise, or Devise's notification. The proposed workaround is inspired by Devise's documentation but checks whether a transaction is open to make the call whether to immediately send the notification or defer it to the `after_commit` hook. [1]: https://www.rubydoc.info/github/plataformatec/devise/Devise%2FModels%2FAuthenticatable:send_devise_notification [2]: https://github.com/heartcombo/devise/blob/406915cb781e38255a30ad2a0609e33952b9ec50/lib/devise/models/authenticatable.rb#L133-L194 * Fix cases when sending notifications without changing the model * Defer sending if and only if in transaction including current record
4 years ago
Add WebAuthn as an alternative 2FA method (#14466) * feat: add possibility of adding WebAuthn security keys to use as 2FA This adds a basic UI for enabling WebAuthn 2FA. We did a little refactor to the Settings page for editing the 2FA methods – now it will list the methods that are available to the user (TOTP and WebAuthn) and from there they'll be able to add or remove any of them. Also, it's worth mentioning that for enabling WebAuthn it's required to have TOTP enabled, so the first time that you go to the 2FA Settings page, you'll be asked to set it up. This work was inspired by the one donde by Github in their platform, and despite it could be approached in different ways, we decided to go with this one given that we feel that this gives a great UX. Co-authored-by: Facundo Padula <facundo.padula@cedarcode.com> * feat: add request for WebAuthn as second factor at login if enabled This commits adds the feature for using WebAuthn as a second factor for login when enabled. If users have WebAuthn enabled, now a page requesting for the use of a WebAuthn credential for log in will appear, although a link redirecting to the old page for logging in using a two-factor code will also be present. Co-authored-by: Facundo Padula <facundo.padula@cedarcode.com> * feat: add possibility of deleting WebAuthn Credentials Co-authored-by: Facundo Padula <facundo.padula@cedarcode.com> * feat: disable WebAuthn when an Admin disables 2FA for a user Co-authored-by: Facundo Padula <facundo.padula@cedarcode.com> * feat: remove ability to disable TOTP leaving only WebAuthn as 2FA Following examples form other platforms like Github, we decided to make Webauthn 2FA secondary to 2FA with TOTP, so that we removed the possibility of removing TOTP authentication only, leaving users with just WEbAuthn as 2FA. Instead, users will have to click on 'Disable 2FA' in order to remove second factor auth. The reason for WebAuthn being secondary to TOPT is that in that way, users will still be able to log in using their code from their phone's application if they don't have their security keys with them – or maybe even lost them. * We had to change a little the flow for setting up TOTP, given that now it's possible to setting up again if you already had TOTP, in order to let users modify their authenticator app – given that now it's not possible for them to disable TOTP and set it up again with another authenticator app. So, basically, now instead of storing the new `otp_secret` in the user, we store it in the session until the process of set up is finished. This was because, as it was before, when users clicked on 'Edit' in the new two-factor methods lists page, but then went back without finishing the flow, their `otp_secret` had been changed therefore invalidating their previous authenticator app, making them unable to log in again using TOTP. Co-authored-by: Facundo Padula <facundo.padula@cedarcode.com> * refactor: fix eslint errors The PR build was failing given that linting returning some errors. This commit attempts to fix them. * refactor: normalize i18n translations The build was failing given that i18n translations files were not normalized. This commits fixes that. * refactor: avoid having the webauthn gem locked to a specific version * refactor: use symbols for routes without '/' * refactor: avoid sending webauthn disabled email when 2FA is disabled When an admins disable 2FA for users, we were sending two mails to them, one notifying that 2FA was disabled and the other to notify that WebAuthn was disabled. As the second one is redundant since the first email includes it, we can remove it and send just one email to users. * refactor: avoid creating new env variable for webauthn_origin config * refactor: improve flash error messages for webauthn pages Co-authored-by: Facundo Padula <facundo.padula@cedarcode.com>
3 years ago
Add WebAuthn as an alternative 2FA method (#14466) * feat: add possibility of adding WebAuthn security keys to use as 2FA This adds a basic UI for enabling WebAuthn 2FA. We did a little refactor to the Settings page for editing the 2FA methods – now it will list the methods that are available to the user (TOTP and WebAuthn) and from there they'll be able to add or remove any of them. Also, it's worth mentioning that for enabling WebAuthn it's required to have TOTP enabled, so the first time that you go to the 2FA Settings page, you'll be asked to set it up. This work was inspired by the one donde by Github in their platform, and despite it could be approached in different ways, we decided to go with this one given that we feel that this gives a great UX. Co-authored-by: Facundo Padula <facundo.padula@cedarcode.com> * feat: add request for WebAuthn as second factor at login if enabled This commits adds the feature for using WebAuthn as a second factor for login when enabled. If users have WebAuthn enabled, now a page requesting for the use of a WebAuthn credential for log in will appear, although a link redirecting to the old page for logging in using a two-factor code will also be present. Co-authored-by: Facundo Padula <facundo.padula@cedarcode.com> * feat: add possibility of deleting WebAuthn Credentials Co-authored-by: Facundo Padula <facundo.padula@cedarcode.com> * feat: disable WebAuthn when an Admin disables 2FA for a user Co-authored-by: Facundo Padula <facundo.padula@cedarcode.com> * feat: remove ability to disable TOTP leaving only WebAuthn as 2FA Following examples form other platforms like Github, we decided to make Webauthn 2FA secondary to 2FA with TOTP, so that we removed the possibility of removing TOTP authentication only, leaving users with just WEbAuthn as 2FA. Instead, users will have to click on 'Disable 2FA' in order to remove second factor auth. The reason for WebAuthn being secondary to TOPT is that in that way, users will still be able to log in using their code from their phone's application if they don't have their security keys with them – or maybe even lost them. * We had to change a little the flow for setting up TOTP, given that now it's possible to setting up again if you already had TOTP, in order to let users modify their authenticator app – given that now it's not possible for them to disable TOTP and set it up again with another authenticator app. So, basically, now instead of storing the new `otp_secret` in the user, we store it in the session until the process of set up is finished. This was because, as it was before, when users clicked on 'Edit' in the new two-factor methods lists page, but then went back without finishing the flow, their `otp_secret` had been changed therefore invalidating their previous authenticator app, making them unable to log in again using TOTP. Co-authored-by: Facundo Padula <facundo.padula@cedarcode.com> * refactor: fix eslint errors The PR build was failing given that linting returning some errors. This commit attempts to fix them. * refactor: normalize i18n translations The build was failing given that i18n translations files were not normalized. This commits fixes that. * refactor: avoid having the webauthn gem locked to a specific version * refactor: use symbols for routes without '/' * refactor: avoid sending webauthn disabled email when 2FA is disabled When an admins disable 2FA for users, we were sending two mails to them, one notifying that 2FA was disabled and the other to notify that WebAuthn was disabled. As the second one is redundant since the first email includes it, we can remove it and send just one email to users. * refactor: avoid creating new env variable for webauthn_origin config * refactor: improve flash error messages for webauthn pages Co-authored-by: Facundo Padula <facundo.padula@cedarcode.com>
3 years ago
Add WebAuthn as an alternative 2FA method (#14466) * feat: add possibility of adding WebAuthn security keys to use as 2FA This adds a basic UI for enabling WebAuthn 2FA. We did a little refactor to the Settings page for editing the 2FA methods – now it will list the methods that are available to the user (TOTP and WebAuthn) and from there they'll be able to add or remove any of them. Also, it's worth mentioning that for enabling WebAuthn it's required to have TOTP enabled, so the first time that you go to the 2FA Settings page, you'll be asked to set it up. This work was inspired by the one donde by Github in their platform, and despite it could be approached in different ways, we decided to go with this one given that we feel that this gives a great UX. Co-authored-by: Facundo Padula <facundo.padula@cedarcode.com> * feat: add request for WebAuthn as second factor at login if enabled This commits adds the feature for using WebAuthn as a second factor for login when enabled. If users have WebAuthn enabled, now a page requesting for the use of a WebAuthn credential for log in will appear, although a link redirecting to the old page for logging in using a two-factor code will also be present. Co-authored-by: Facundo Padula <facundo.padula@cedarcode.com> * feat: add possibility of deleting WebAuthn Credentials Co-authored-by: Facundo Padula <facundo.padula@cedarcode.com> * feat: disable WebAuthn when an Admin disables 2FA for a user Co-authored-by: Facundo Padula <facundo.padula@cedarcode.com> * feat: remove ability to disable TOTP leaving only WebAuthn as 2FA Following examples form other platforms like Github, we decided to make Webauthn 2FA secondary to 2FA with TOTP, so that we removed the possibility of removing TOTP authentication only, leaving users with just WEbAuthn as 2FA. Instead, users will have to click on 'Disable 2FA' in order to remove second factor auth. The reason for WebAuthn being secondary to TOPT is that in that way, users will still be able to log in using their code from their phone's application if they don't have their security keys with them – or maybe even lost them. * We had to change a little the flow for setting up TOTP, given that now it's possible to setting up again if you already had TOTP, in order to let users modify their authenticator app – given that now it's not possible for them to disable TOTP and set it up again with another authenticator app. So, basically, now instead of storing the new `otp_secret` in the user, we store it in the session until the process of set up is finished. This was because, as it was before, when users clicked on 'Edit' in the new two-factor methods lists page, but then went back without finishing the flow, their `otp_secret` had been changed therefore invalidating their previous authenticator app, making them unable to log in again using TOTP. Co-authored-by: Facundo Padula <facundo.padula@cedarcode.com> * refactor: fix eslint errors The PR build was failing given that linting returning some errors. This commit attempts to fix them. * refactor: normalize i18n translations The build was failing given that i18n translations files were not normalized. This commits fixes that. * refactor: avoid having the webauthn gem locked to a specific version * refactor: use symbols for routes without '/' * refactor: avoid sending webauthn disabled email when 2FA is disabled When an admins disable 2FA for users, we were sending two mails to them, one notifying that 2FA was disabled and the other to notify that WebAuthn was disabled. As the second one is redundant since the first email includes it, we can remove it and send just one email to users. * refactor: avoid creating new env variable for webauthn_origin config * refactor: improve flash error messages for webauthn pages Co-authored-by: Facundo Padula <facundo.padula@cedarcode.com>
3 years ago
Web Push Notifications (#3243) * feat: Register push subscription * feat: Notify when mentioned * feat: Boost, favourite, reply, follow, follow request * feat: Notification interaction * feat: Handle change of public key * feat: Unsubscribe if things go wrong * feat: Do not send normal notifications if push is enabled * feat: Focus client if open * refactor: Move push logic to WebPushSubscription * feat: Better title and body * feat: Localize messages * chore: Fix lint errors * feat: Settings * refactor: Lazy load * fix: Check if push settings exist * feat: Device-based preferences * refactor: Simplify logic * refactor: Pull request feedback * refactor: Pull request feedback * refactor: Create /api/web/push_subscriptions endpoint * feat: Spec PushSubscriptionController * refactor: WebPushSubscription => Web::PushSubscription * feat: Spec Web::PushSubscription * feat: Display first media attachment * feat: Support direction * fix: Stuff broken while rebasing * refactor: Integration with session activations * refactor: Cleanup * refactor: Simplify implementation * feat: Set VAPID keys via environment * chore: Comments * fix: Crash when no alerts * fix: Set VAPID keys in testing environment * fix: Follow link * feat: Notification actions * fix: Delete previous subscription * chore: Temporary logs * refactor: Move migration to a later date * fix: Fetch the correct session activation and misc bugs * refactor: Move migration to a later date * fix: Remove follow request (no notifications) * feat: Send administrator contact to push service * feat: Set time-to-live * fix: Do not show sensitive images * fix: Reducer crash in error handling * feat: Add badge * chore: Fix lint error * fix: Checkbox label overlap * fix: Check for payload support * fix: Rename action "type" (crash in latest Chrome) * feat: Action to expand notification * fix: Lint errors * fix: Unescape notification body * fix: Do not allow boosting if the status is hidden * feat: Add VAPID keys to the production sample environment * fix: Strip HTML tags from status * refactor: Better error messages * refactor: Handle browser not implementing the VAPID protocol (Samsung Internet) * fix: Error when target_status is nil * fix: Handle lack of image * fix: Delete reference to invalid subscriptions * feat: Better error handling * fix: Unescape HTML characters after tags are striped * refactor: Simpify code * fix: Modify to work with #4091 * Sort strings alphabetically * i18n: Updated Polish translation it annoys me that it's not fully localized :P * refactor: Use current_session in PushSubscriptionController * fix: Rebase mistake * fix: Set cacheName to mastodon * refactor: Pull request feedback * refactor: Remove logging statements * chore(yarn): Fix conflicts with master * chore(yarn): Copy latest from master * chore(yarn): Readd offline-plugin * refactor: Use save! and update! * refactor: Send notifications async * fix: Allow retry when push fails * fix: Save track for failed pushes * fix: Minify sw.js * fix: Remove account_id from fabricator
6 years ago
Web Push Notifications (#3243) * feat: Register push subscription * feat: Notify when mentioned * feat: Boost, favourite, reply, follow, follow request * feat: Notification interaction * feat: Handle change of public key * feat: Unsubscribe if things go wrong * feat: Do not send normal notifications if push is enabled * feat: Focus client if open * refactor: Move push logic to WebPushSubscription * feat: Better title and body * feat: Localize messages * chore: Fix lint errors * feat: Settings * refactor: Lazy load * fix: Check if push settings exist * feat: Device-based preferences * refactor: Simplify logic * refactor: Pull request feedback * refactor: Pull request feedback * refactor: Create /api/web/push_subscriptions endpoint * feat: Spec PushSubscriptionController * refactor: WebPushSubscription => Web::PushSubscription * feat: Spec Web::PushSubscription * feat: Display first media attachment * feat: Support direction * fix: Stuff broken while rebasing * refactor: Integration with session activations * refactor: Cleanup * refactor: Simplify implementation * feat: Set VAPID keys via environment * chore: Comments * fix: Crash when no alerts * fix: Set VAPID keys in testing environment * fix: Follow link * feat: Notification actions * fix: Delete previous subscription * chore: Temporary logs * refactor: Move migration to a later date * fix: Fetch the correct session activation and misc bugs * refactor: Move migration to a later date * fix: Remove follow request (no notifications) * feat: Send administrator contact to push service * feat: Set time-to-live * fix: Do not show sensitive images * fix: Reducer crash in error handling * feat: Add badge * chore: Fix lint error * fix: Checkbox label overlap * fix: Check for payload support * fix: Rename action "type" (crash in latest Chrome) * feat: Action to expand notification * fix: Lint errors * fix: Unescape notification body * fix: Do not allow boosting if the status is hidden * feat: Add VAPID keys to the production sample environment * fix: Strip HTML tags from status * refactor: Better error messages * refactor: Handle browser not implementing the VAPID protocol (Samsung Internet) * fix: Error when target_status is nil * fix: Handle lack of image * fix: Delete reference to invalid subscriptions * feat: Better error handling * fix: Unescape HTML characters after tags are striped * refactor: Simpify code * fix: Modify to work with #4091 * Sort strings alphabetically * i18n: Updated Polish translation it annoys me that it's not fully localized :P * refactor: Use current_session in PushSubscriptionController * fix: Rebase mistake * fix: Set cacheName to mastodon * refactor: Pull request feedback * refactor: Remove logging statements * chore(yarn): Fix conflicts with master * chore(yarn): Copy latest from master * chore(yarn): Readd offline-plugin * refactor: Use save! and update! * refactor: Send notifications async * fix: Allow retry when push fails * fix: Save track for failed pushes * fix: Minify sw.js * fix: Remove account_id from fabricator
6 years ago
Fix “Email changed” notification sometimes having wrong e-mail (#13475) * Fix “Email changed” notification sometimes having wrong e-mail Fixes #6778 The root of the issue is that `send_devise_notification` was called before the changes were properly commited to the database, causing the mailer to pick previous values if running too early. Devise's documentation provides guidance on how to handle that[1][2], however, I have found it to not be working, as the following happens, in that order: - `send_devise_notification` is called for the `email_changed` notification. In that case, `changed?` is false and `saved_changes?` is true, so if we use the former, we have the same issue. - the `after_commit` hook is called - `send_devise_notification` is called for the `confirmation_instructions` notification. In that case, `changed?` is still false, and `saved_changes?` still true, so if we use the latter, that second notification email is simply not going to be sent (as we would be queuing the notification *after* executing the after_commit hook). This is because it may be called from either an `after_update` or `after_commit` hook, the difference not being a call to `save` but the transaction actually being committed to the database. This may arguably be a bug in Devise, or Devise's notification. The proposed workaround is inspired by Devise's documentation but checks whether a transaction is open to make the call whether to immediately send the notification or defer it to the `after_commit` hook. [1]: https://www.rubydoc.info/github/plataformatec/devise/Devise%2FModels%2FAuthenticatable:send_devise_notification [2]: https://github.com/heartcombo/devise/blob/406915cb781e38255a30ad2a0609e33952b9ec50/lib/devise/models/authenticatable.rb#L133-L194 * Fix cases when sending notifications without changing the model * Defer sending if and only if in transaction including current record
4 years ago
Fix “Email changed” notification sometimes having wrong e-mail (#13475) * Fix “Email changed” notification sometimes having wrong e-mail Fixes #6778 The root of the issue is that `send_devise_notification` was called before the changes were properly commited to the database, causing the mailer to pick previous values if running too early. Devise's documentation provides guidance on how to handle that[1][2], however, I have found it to not be working, as the following happens, in that order: - `send_devise_notification` is called for the `email_changed` notification. In that case, `changed?` is false and `saved_changes?` is true, so if we use the former, we have the same issue. - the `after_commit` hook is called - `send_devise_notification` is called for the `confirmation_instructions` notification. In that case, `changed?` is still false, and `saved_changes?` still true, so if we use the latter, that second notification email is simply not going to be sent (as we would be queuing the notification *after* executing the after_commit hook). This is because it may be called from either an `after_update` or `after_commit` hook, the difference not being a call to `save` but the transaction actually being committed to the database. This may arguably be a bug in Devise, or Devise's notification. The proposed workaround is inspired by Devise's documentation but checks whether a transaction is open to make the call whether to immediately send the notification or defer it to the `after_commit` hook. [1]: https://www.rubydoc.info/github/plataformatec/devise/Devise%2FModels%2FAuthenticatable:send_devise_notification [2]: https://github.com/heartcombo/devise/blob/406915cb781e38255a30ad2a0609e33952b9ec50/lib/devise/models/authenticatable.rb#L133-L194 * Fix cases when sending notifications without changing the model * Defer sending if and only if in transaction including current record
4 years ago
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: users
  5. #
  6. # id :bigint(8) not null, primary key
  7. # email :string default(""), not null
  8. # created_at :datetime not null
  9. # updated_at :datetime not null
  10. # encrypted_password :string default(""), not null
  11. # reset_password_token :string
  12. # reset_password_sent_at :datetime
  13. # remember_created_at :datetime
  14. # sign_in_count :integer default(0), not null
  15. # current_sign_in_at :datetime
  16. # last_sign_in_at :datetime
  17. # current_sign_in_ip :inet
  18. # last_sign_in_ip :inet
  19. # admin :boolean default(FALSE), not null
  20. # confirmation_token :string
  21. # confirmed_at :datetime
  22. # confirmation_sent_at :datetime
  23. # unconfirmed_email :string
  24. # locale :string
  25. # encrypted_otp_secret :string
  26. # encrypted_otp_secret_iv :string
  27. # encrypted_otp_secret_salt :string
  28. # consumed_timestep :integer
  29. # otp_required_for_login :boolean default(FALSE), not null
  30. # last_emailed_at :datetime
  31. # otp_backup_codes :string is an Array
  32. # filtered_languages :string default([]), not null, is an Array
  33. # account_id :bigint(8) not null
  34. # disabled :boolean default(FALSE), not null
  35. # moderator :boolean default(FALSE), not null
  36. # invite_id :bigint(8)
  37. # remember_token :string
  38. # chosen_languages :string is an Array
  39. # created_by_application_id :bigint(8)
  40. # approved :boolean default(TRUE), not null
  41. # sign_in_token :string
  42. # sign_in_token_sent_at :datetime
  43. # webauthn_id :string
  44. #
  45. class User < ApplicationRecord
  46. include Settings::Extend
  47. include UserRoles
  48. # The home and list feeds will be stored in Redis for this amount
  49. # of time, and status fan-out to followers will include only people
  50. # within this time frame. Lowering the duration may improve performance
  51. # if lots of people sign up, but not a lot of them check their feed
  52. # every day. Raising the duration reduces the amount of expensive
  53. # RegenerationWorker jobs that need to be run when those people come
  54. # to check their feed
  55. ACTIVE_DURATION = ENV.fetch('USER_ACTIVE_DAYS', 7).to_i.days.freeze
  56. devise :two_factor_authenticatable,
  57. otp_secret_encryption_key: Rails.configuration.x.otp_secret
  58. devise :two_factor_backupable,
  59. otp_number_of_backup_codes: 10
  60. devise :registerable, :recoverable, :rememberable, :trackable, :validatable,
  61. :confirmable
  62. include Omniauthable
  63. include PamAuthenticable
  64. include LdapAuthenticable
  65. belongs_to :account, inverse_of: :user
  66. belongs_to :invite, counter_cache: :uses, optional: true
  67. belongs_to :created_by_application, class_name: 'Doorkeeper::Application', optional: true
  68. accepts_nested_attributes_for :account
  69. has_many :applications, class_name: 'Doorkeeper::Application', as: :owner
  70. has_many :backups, inverse_of: :user
  71. has_many :invites, inverse_of: :user
  72. has_many :markers, inverse_of: :user, dependent: :destroy
  73. has_many :webauthn_credentials, dependent: :destroy
  74. has_one :invite_request, class_name: 'UserInviteRequest', inverse_of: :user, dependent: :destroy
  75. accepts_nested_attributes_for :invite_request, reject_if: ->(attributes) { attributes['text'].blank? }
  76. validates :locale, inclusion: I18n.available_locales.map(&:to_s), if: :locale?
  77. validates_with BlacklistedEmailValidator, on: :create
  78. validates_with EmailMxValidator, if: :validate_email_dns?
  79. validates :agreement, acceptance: { allow_nil: false, accept: [true, 'true', '1'] }, on: :create
  80. scope :recent, -> { order(id: :desc) }
  81. scope :pending, -> { where(approved: false) }
  82. scope :approved, -> { where(approved: true) }
  83. scope :confirmed, -> { where.not(confirmed_at: nil) }
  84. scope :enabled, -> { where(disabled: false) }
  85. scope :disabled, -> { where(disabled: true) }
  86. scope :inactive, -> { where(arel_table[:current_sign_in_at].lt(ACTIVE_DURATION.ago)) }
  87. scope :active, -> { confirmed.where(arel_table[:current_sign_in_at].gteq(ACTIVE_DURATION.ago)).joins(:account).where(accounts: { suspended_at: nil }) }
  88. scope :matches_email, ->(value) { where(arel_table[:email].matches("#{value}%")) }
  89. scope :matches_ip, ->(value) { left_joins(:session_activations).where('users.current_sign_in_ip <<= ?', value).or(left_joins(:session_activations).where('users.last_sign_in_ip <<= ?', value)).or(left_joins(:session_activations).where('session_activations.ip <<= ?', value)) }
  90. scope :emailable, -> { confirmed.enabled.joins(:account).merge(Account.searchable) }
  91. before_validation :sanitize_languages
  92. before_create :set_approved
  93. after_commit :send_pending_devise_notifications
  94. # This avoids a deprecation warning from Rails 5.1
  95. # It seems possible that a future release of devise-two-factor will
  96. # handle this itself, and this can be removed from our User class.
  97. attribute :otp_secret
  98. has_many :session_activations, dependent: :destroy
  99. delegate :auto_play_gif, :default_sensitive, :unfollow_modal, :boost_modal, :delete_modal,
  100. :reduce_motion, :system_font_ui, :noindex, :theme, :display_media, :hide_network,
  101. :expand_spoilers, :default_language, :aggregate_reblogs, :show_application,
  102. :advanced_layout, :use_blurhash, :use_pending_items, :trends, :crop_images,
  103. to: :settings, prefix: :setting, allow_nil: false
  104. attr_reader :invite_code, :sign_in_token_attempt
  105. attr_writer :external
  106. def confirmed?
  107. confirmed_at.present?
  108. end
  109. def invited?
  110. invite_id.present?
  111. end
  112. def valid_invitation?
  113. invite_id.present? && invite.valid_for_use?
  114. end
  115. def disable!
  116. update!(disabled: true)
  117. end
  118. def enable!
  119. update!(disabled: false)
  120. end
  121. def confirm
  122. new_user = !confirmed?
  123. self.approved = true if open_registrations?
  124. super
  125. if new_user && approved?
  126. prepare_new_user!
  127. elsif new_user
  128. notify_staff_about_pending_account!
  129. end
  130. end
  131. def confirm!
  132. new_user = !confirmed?
  133. self.approved = true if open_registrations?
  134. skip_confirmation!
  135. save!
  136. prepare_new_user! if new_user && approved?
  137. end
  138. def pending?
  139. !approved?
  140. end
  141. def active_for_authentication?
  142. true
  143. end
  144. def suspicious_sign_in?(ip)
  145. !otp_required_for_login? && current_sign_in_at.present? && current_sign_in_at < 2.weeks.ago && !recent_ip?(ip)
  146. end
  147. def functional?
  148. confirmed? && approved? && !disabled? && !account.suspended? && account.moved_to_account_id.nil?
  149. end
  150. def unconfirmed_or_pending?
  151. !(confirmed? && approved?)
  152. end
  153. def inactive_message
  154. !approved? ? :pending : super
  155. end
  156. def approve!
  157. return if approved?
  158. update!(approved: true)
  159. prepare_new_user!
  160. end
  161. def update_tracked_fields!(request)
  162. super
  163. prepare_returning_user!
  164. end
  165. def otp_enabled?
  166. otp_required_for_login
  167. end
  168. def webauthn_enabled?
  169. webauthn_credentials.any?
  170. end
  171. def two_factor_enabled?
  172. otp_required_for_login? || webauthn_credentials.any?
  173. end
  174. def disable_two_factor!
  175. self.otp_required_for_login = false
  176. self.otp_secret = nil
  177. otp_backup_codes&.clear
  178. webauthn_credentials.destroy_all if webauthn_enabled?
  179. save!
  180. end
  181. def setting_default_privacy
  182. settings.default_privacy || (account.locked? ? 'private' : 'public')
  183. end
  184. def allows_digest_emails?
  185. settings.notification_emails['digest']
  186. end
  187. def allows_report_emails?
  188. settings.notification_emails['report']
  189. end
  190. def allows_pending_account_emails?
  191. settings.notification_emails['pending_account']
  192. end
  193. def allows_trending_tag_emails?
  194. settings.notification_emails['trending_tag']
  195. end
  196. def hides_network?
  197. @hides_network ||= settings.hide_network
  198. end
  199. def aggregates_reblogs?
  200. @aggregates_reblogs ||= settings.aggregate_reblogs
  201. end
  202. def shows_application?
  203. @shows_application ||= settings.show_application
  204. end
  205. # rubocop:disable Naming/MethodParameterName
  206. def token_for_app(a)
  207. return nil if a.nil? || a.owner != self
  208. Doorkeeper::AccessToken.find_or_create_by(application_id: a.id, resource_owner_id: id) do |t|
  209. t.scopes = a.scopes
  210. t.expires_in = Doorkeeper.configuration.access_token_expires_in
  211. t.use_refresh_token = Doorkeeper.configuration.refresh_token_enabled?
  212. end
  213. end
  214. # rubocop:enable Naming/MethodParameterName
  215. def activate_session(request)
  216. session_activations.activate(session_id: SecureRandom.hex,
  217. user_agent: request.user_agent,
  218. ip: request.remote_ip).session_id
  219. end
  220. def clear_other_sessions(id)
  221. session_activations.exclusive(id)
  222. end
  223. def session_active?(id)
  224. session_activations.active? id
  225. end
  226. def web_push_subscription(session)
  227. session.web_push_subscription.nil? ? nil : session.web_push_subscription
  228. end
  229. def invite_code=(code)
  230. self.invite = Invite.find_by(code: code) if code.present?
  231. @invite_code = code
  232. end
  233. def password_required?
  234. return false if external?
  235. super
  236. end
  237. def external_or_valid_password?(compare_password)
  238. # If encrypted_password is blank, we got the user from LDAP or PAM,
  239. # so credentials are already valid
  240. encrypted_password.blank? || valid_password?(compare_password)
  241. end
  242. def send_reset_password_instructions
  243. return false if encrypted_password.blank?
  244. super
  245. end
  246. def reset_password!(new_password, new_password_confirmation)
  247. return false if encrypted_password.blank?
  248. super
  249. end
  250. def show_all_media?
  251. setting_display_media == 'show_all'
  252. end
  253. def hide_all_media?
  254. setting_display_media == 'hide_all'
  255. end
  256. def recent_ips
  257. @recent_ips ||= begin
  258. arr = []
  259. session_activations.each do |session_activation|
  260. arr << [session_activation.updated_at, session_activation.ip]
  261. end
  262. arr << [current_sign_in_at, current_sign_in_ip] if current_sign_in_ip.present?
  263. arr << [last_sign_in_at, last_sign_in_ip] if last_sign_in_ip.present?
  264. arr.sort_by { |pair| pair.first || Time.now.utc }.uniq(&:last).reverse!
  265. end
  266. end
  267. def sign_in_token_expired?
  268. sign_in_token_sent_at.nil? || sign_in_token_sent_at < 5.minutes.ago
  269. end
  270. def generate_sign_in_token
  271. self.sign_in_token = Devise.friendly_token(6)
  272. self.sign_in_token_sent_at = Time.now.utc
  273. end
  274. protected
  275. def send_devise_notification(notification, *args)
  276. # This method can be called in `after_update` and `after_commit` hooks,
  277. # but we must make sure the mailer is actually called *after* commit,
  278. # otherwise it may work on stale data. To do this, figure out if we are
  279. # within a transaction.
  280. if ActiveRecord::Base.connection.current_transaction.try(:records)&.include?(self)
  281. pending_devise_notifications << [notification, args]
  282. else
  283. render_and_send_devise_message(notification, *args)
  284. end
  285. end
  286. private
  287. def recent_ip?(ip)
  288. recent_ips.any? { |(_, recent_ip)| recent_ip == ip }
  289. end
  290. def send_pending_devise_notifications
  291. pending_devise_notifications.each do |notification, args|
  292. render_and_send_devise_message(notification, *args)
  293. end
  294. # Empty the pending notifications array because the
  295. # after_commit hook can be called multiple times which
  296. # could cause multiple emails to be sent.
  297. pending_devise_notifications.clear
  298. end
  299. def pending_devise_notifications
  300. @pending_devise_notifications ||= []
  301. end
  302. def render_and_send_devise_message(notification, *args)
  303. devise_mailer.send(notification, self, *args).deliver_later
  304. end
  305. def set_approved
  306. self.approved = open_registrations? || valid_invitation? || external?
  307. end
  308. def open_registrations?
  309. Setting.registrations_mode == 'open'
  310. end
  311. def external?
  312. !!@external
  313. end
  314. def sanitize_languages
  315. return if chosen_languages.nil?
  316. chosen_languages.reject!(&:blank?)
  317. self.chosen_languages = nil if chosen_languages.empty?
  318. end
  319. def prepare_new_user!
  320. BootstrapTimelineWorker.perform_async(account_id)
  321. ActivityTracker.increment('activity:accounts:local')
  322. UserMailer.welcome(self).deliver_later
  323. end
  324. def prepare_returning_user!
  325. ActivityTracker.record('activity:logins', id)
  326. regenerate_feed! if needs_feed_update?
  327. end
  328. def notify_staff_about_pending_account!
  329. User.staff.includes(:account).find_each do |u|
  330. next unless u.allows_pending_account_emails?
  331. AdminMailer.new_pending_account(u.account, self).deliver_later
  332. end
  333. end
  334. def regenerate_feed!
  335. return unless Redis.current.setnx("account:#{account_id}:regeneration", true)
  336. Redis.current.expire("account:#{account_id}:regeneration", 1.day.seconds)
  337. RegenerationWorker.perform_async(account_id)
  338. end
  339. def needs_feed_update?
  340. last_sign_in_at < ACTIVE_DURATION.ago
  341. end
  342. def validate_email_dns?
  343. email_changed? && !(Rails.env.test? || Rails.env.development?)
  344. end
  345. end