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.

562 lines
16 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
Merge branch 'master' into glitch-soc/merge-upstream Conflicts: - `Gemfile.lock`: Not a real conflict, upstream updated dependencies that were too close to glitch-soc-only ones in the file. - `app/controllers/oauth/authorized_applications_controller.rb`: Upstream changed the logic surrounding suspended accounts. Minor conflict due to glitch-soc's theming system. Ported upstream changes. - `app/controllers/settings/base_controller.rb`: Upstream refactored and changed the logic surrounding suspended accounts. Minor conflict due to glitch-soc's theming system. Ported upstream changes. - `app/controllers/settings/sessions_controller.rb`: Upstream refactored and changed the logic surrounding suspended accounts. Minor conflict due to glitch-soc's theming system. Ported upstream changes. - `app/models/user.rb`: Upstream refactored and changed the logic surrounding suspended accounts. Minor conflict due to glitch-soc not preventing moved accounts from logging in. Ported upstream changes while keeping the ability for moved accounts to log in. - `app/policies/status_policy.rb`: Upstream refactored and changed the logic surrounding suspended accounts. Minor conflict due to glitch-soc's local-only toots. Ported upstream changes. - `app/serializers/rest/account_serializer.rb`: Upstream refactored and changed the logic surrounding suspended accounts. Minor conflict due to glitch-soc's ability to hide followers count. Ported upstream changes. - `app/services/process_mentions_service.rb`: Upstream refactored and changed the logic surrounding suspended accounts. Minor conflict due to glitch-soc's local-only toots. Ported upstream changes. - `package.json`: Not a real conflict, upstream updated dependencies that were too close to glitch-soc-only ones in the file.
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
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
7 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
7 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
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
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
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
3 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. # sign_in_count :integer default(0), not null
  14. # current_sign_in_at :datetime
  15. # last_sign_in_at :datetime
  16. # admin :boolean default(FALSE), not null
  17. # confirmation_token :string
  18. # confirmed_at :datetime
  19. # confirmation_sent_at :datetime
  20. # unconfirmed_email :string
  21. # locale :string
  22. # encrypted_otp_secret :string
  23. # encrypted_otp_secret_iv :string
  24. # encrypted_otp_secret_salt :string
  25. # consumed_timestep :integer
  26. # otp_required_for_login :boolean default(FALSE), not null
  27. # last_emailed_at :datetime
  28. # otp_backup_codes :string is an Array
  29. # account_id :bigint(8) not null
  30. # disabled :boolean default(FALSE), not null
  31. # moderator :boolean default(FALSE), not null
  32. # invite_id :bigint(8)
  33. # chosen_languages :string is an Array
  34. # created_by_application_id :bigint(8)
  35. # approved :boolean default(TRUE), not null
  36. # sign_in_token :string
  37. # sign_in_token_sent_at :datetime
  38. # webauthn_id :string
  39. # sign_up_ip :inet
  40. # role_id :bigint(8)
  41. #
  42. class User < ApplicationRecord
  43. self.ignored_columns = %w(
  44. remember_created_at
  45. remember_token
  46. current_sign_in_ip
  47. last_sign_in_ip
  48. skip_sign_in_token
  49. filtered_languages
  50. )
  51. include Settings::Extend
  52. include Redisable
  53. include LanguagesHelper
  54. # The home and list feeds will be stored in Redis for this amount
  55. # of time, and status fan-out to followers will include only people
  56. # within this time frame. Lowering the duration may improve performance
  57. # if lots of people sign up, but not a lot of them check their feed
  58. # every day. Raising the duration reduces the amount of expensive
  59. # RegenerationWorker jobs that need to be run when those people come
  60. # to check their feed
  61. ACTIVE_DURATION = ENV.fetch('USER_ACTIVE_DAYS', 7).to_i.days.freeze
  62. devise :two_factor_authenticatable,
  63. otp_secret_encryption_key: Rails.configuration.x.otp_secret
  64. devise :two_factor_backupable,
  65. otp_number_of_backup_codes: 10
  66. devise :registerable, :recoverable, :validatable,
  67. :confirmable
  68. include Omniauthable
  69. include PamAuthenticable
  70. include LdapAuthenticable
  71. belongs_to :account, inverse_of: :user
  72. belongs_to :invite, counter_cache: :uses, optional: true
  73. belongs_to :created_by_application, class_name: 'Doorkeeper::Application', optional: true
  74. belongs_to :role, class_name: 'UserRole', optional: true
  75. accepts_nested_attributes_for :account
  76. has_many :applications, class_name: 'Doorkeeper::Application', as: :owner
  77. has_many :backups, inverse_of: :user
  78. has_many :invites, inverse_of: :user
  79. has_many :markers, inverse_of: :user, dependent: :destroy
  80. has_many :webauthn_credentials, dependent: :destroy
  81. has_many :ips, class_name: 'UserIp', inverse_of: :user
  82. has_one :invite_request, class_name: 'UserInviteRequest', inverse_of: :user, dependent: :destroy
  83. accepts_nested_attributes_for :invite_request, reject_if: ->(attributes) { attributes['text'].blank? && !Setting.require_invite_text }
  84. validates :invite_request, presence: true, on: :create, if: :invite_text_required?
  85. validates :locale, inclusion: I18n.available_locales.map(&:to_s), if: :locale?
  86. validates_with BlacklistedEmailValidator, if: -> { ENV['EMAIL_DOMAIN_LISTS_APPLY_AFTER_CONFIRMATION'] == 'true' || !confirmed? }
  87. validates_with EmailMxValidator, if: :validate_email_dns?
  88. validates :agreement, acceptance: { allow_nil: false, accept: [true, 'true', '1'] }, on: :create
  89. # Honeypot/anti-spam fields
  90. attr_accessor :registration_form_time, :website, :confirm_password
  91. validates_with RegistrationFormTimeValidator, on: :create
  92. validates :website, absence: true, on: :create
  93. validates :confirm_password, absence: true, on: :create
  94. validate :validate_role_elevation
  95. scope :recent, -> { order(id: :desc) }
  96. scope :pending, -> { where(approved: false) }
  97. scope :approved, -> { where(approved: true) }
  98. scope :confirmed, -> { where.not(confirmed_at: nil) }
  99. scope :enabled, -> { where(disabled: false) }
  100. scope :disabled, -> { where(disabled: true) }
  101. scope :inactive, -> { where(arel_table[:current_sign_in_at].lt(ACTIVE_DURATION.ago)) }
  102. scope :active, -> { confirmed.where(arel_table[:current_sign_in_at].gteq(ACTIVE_DURATION.ago)).joins(:account).where(accounts: { suspended_at: nil }) }
  103. scope :matches_email, ->(value) { where(arel_table[:email].matches("#{value}%")) }
  104. scope :matches_ip, ->(value) { left_joins(:ips).where('user_ips.ip <<= ?', value).group('users.id') }
  105. scope :emailable, -> { confirmed.enabled.joins(:account).merge(Account.searchable) }
  106. before_validation :sanitize_languages
  107. before_validation :sanitize_role
  108. before_create :set_approved
  109. after_commit :send_pending_devise_notifications
  110. after_create_commit :trigger_webhooks
  111. # This avoids a deprecation warning from Rails 5.1
  112. # It seems possible that a future release of devise-two-factor will
  113. # handle this itself, and this can be removed from our User class.
  114. attribute :otp_secret
  115. has_many :session_activations, dependent: :destroy
  116. delegate :auto_play_gif, :default_sensitive, :unfollow_modal, :boost_modal, :favourite_modal, :delete_modal,
  117. :reduce_motion, :system_font_ui, :noindex, :flavour, :skin, :display_media, :hide_followers_count,
  118. :expand_spoilers, :default_language, :aggregate_reblogs, :show_application,
  119. :advanced_layout, :use_blurhash, :use_pending_items, :trends, :crop_images,
  120. :disable_swiping, :always_send_emails, :default_content_type, :system_emoji_font,
  121. to: :settings, prefix: :setting, allow_nil: false
  122. delegate :can?, to: :role
  123. attr_reader :invite_code
  124. attr_writer :external, :bypass_invite_request_check, :current_account
  125. def self.those_who_can(*any_of_privileges)
  126. matching_role_ids = UserRole.that_can(*any_of_privileges).map(&:id)
  127. if matching_role_ids.empty?
  128. none
  129. else
  130. where(role_id: matching_role_ids)
  131. end
  132. end
  133. def role
  134. if role_id.nil?
  135. UserRole.everyone
  136. else
  137. super
  138. end
  139. end
  140. def confirmed?
  141. confirmed_at.present?
  142. end
  143. def invited?
  144. invite_id.present?
  145. end
  146. def valid_invitation?
  147. invite_id.present? && invite.valid_for_use?
  148. end
  149. def disable!
  150. update!(disabled: true)
  151. end
  152. def enable!
  153. update!(disabled: false)
  154. end
  155. def to_log_human_identifier
  156. account.acct
  157. end
  158. def to_log_route_param
  159. account_id
  160. end
  161. def confirm
  162. new_user = !confirmed?
  163. self.approved = true if open_registrations? && !sign_up_from_ip_requires_approval?
  164. super
  165. if new_user
  166. # Avoid extremely unlikely race condition when approving and confirming
  167. # the user at the same time
  168. reload unless approved?
  169. if approved?
  170. prepare_new_user!
  171. else
  172. notify_staff_about_pending_account!
  173. end
  174. end
  175. end
  176. def confirm!
  177. new_user = !confirmed?
  178. self.approved = true if open_registrations?
  179. skip_confirmation!
  180. save!
  181. if new_user
  182. # Avoid extremely unlikely race condition when approving and confirming
  183. # the user at the same time
  184. reload unless approved?
  185. prepare_new_user! if approved?
  186. end
  187. end
  188. def update_sign_in!(new_sign_in: false)
  189. old_current = current_sign_in_at
  190. new_current = Time.now.utc
  191. self.last_sign_in_at = old_current || new_current
  192. self.current_sign_in_at = new_current
  193. if new_sign_in
  194. self.sign_in_count ||= 0
  195. self.sign_in_count += 1
  196. end
  197. save(validate: false) unless new_record?
  198. prepare_returning_user!
  199. end
  200. def pending?
  201. !approved?
  202. end
  203. def active_for_authentication?
  204. !account.memorial?
  205. end
  206. def functional?
  207. functional_or_moved?
  208. end
  209. def functional_or_moved?
  210. confirmed? && approved? && !disabled? && !account.suspended? && !account.memorial?
  211. end
  212. def unconfirmed?
  213. !confirmed?
  214. end
  215. def unconfirmed_or_pending?
  216. unconfirmed? || pending?
  217. end
  218. def inactive_message
  219. approved? ? super : :pending
  220. end
  221. def approve!
  222. return if approved?
  223. update!(approved: true)
  224. # Avoid extremely unlikely race condition when approving and confirming
  225. # the user at the same time
  226. reload unless confirmed?
  227. prepare_new_user! if confirmed?
  228. end
  229. def otp_enabled?
  230. otp_required_for_login
  231. end
  232. def webauthn_enabled?
  233. webauthn_credentials.any?
  234. end
  235. def two_factor_enabled?
  236. otp_required_for_login? || webauthn_credentials.any?
  237. end
  238. def disable_two_factor!
  239. self.otp_required_for_login = false
  240. self.otp_secret = nil
  241. otp_backup_codes&.clear
  242. webauthn_credentials.destroy_all if webauthn_enabled?
  243. save!
  244. end
  245. def prefers_noindex?
  246. setting_noindex
  247. end
  248. def preferred_posting_language
  249. valid_locale_cascade(settings.default_language, locale, I18n.locale)
  250. end
  251. def setting_default_privacy
  252. settings.default_privacy || (account.locked? ? 'private' : 'public')
  253. end
  254. def allows_report_emails?
  255. settings.notification_emails['report']
  256. end
  257. def allows_pending_account_emails?
  258. settings.notification_emails['pending_account']
  259. end
  260. def allows_appeal_emails?
  261. settings.notification_emails['appeal']
  262. end
  263. def allows_trending_tags_review_emails?
  264. settings.notification_emails['trending_tag']
  265. end
  266. def allows_trending_links_review_emails?
  267. settings.notification_emails['trending_link']
  268. end
  269. def allows_trending_statuses_review_emails?
  270. settings.notification_emails['trending_status']
  271. end
  272. def aggregates_reblogs?
  273. @aggregates_reblogs ||= settings.aggregate_reblogs
  274. end
  275. def shows_application?
  276. @shows_application ||= settings.show_application
  277. end
  278. def token_for_app(app)
  279. return nil if app.nil? || app.owner != self
  280. Doorkeeper::AccessToken.find_or_create_by(application_id: app.id, resource_owner_id: id) do |t|
  281. t.scopes = app.scopes
  282. t.expires_in = Doorkeeper.configuration.access_token_expires_in
  283. t.use_refresh_token = Doorkeeper.configuration.refresh_token_enabled?
  284. end
  285. end
  286. def activate_session(request)
  287. session_activations.activate(
  288. session_id: SecureRandom.hex,
  289. user_agent: request.user_agent,
  290. ip: request.remote_ip
  291. ).session_id
  292. end
  293. def clear_other_sessions(id)
  294. session_activations.exclusive(id)
  295. end
  296. def web_push_subscription(session)
  297. session.web_push_subscription.nil? ? nil : session.web_push_subscription
  298. end
  299. def invite_code=(code)
  300. self.invite = Invite.find_by(code: code) if code.present?
  301. @invite_code = code
  302. end
  303. def password_required?
  304. return false if external?
  305. super
  306. end
  307. def external_or_valid_password?(compare_password)
  308. # If encrypted_password is blank, we got the user from LDAP or PAM,
  309. # so credentials are already valid
  310. encrypted_password.blank? || valid_password?(compare_password)
  311. end
  312. def send_reset_password_instructions
  313. return false if encrypted_password.blank?
  314. super
  315. end
  316. def reset_password(new_password, new_password_confirmation)
  317. return false if encrypted_password.blank?
  318. super
  319. end
  320. def revoke_access!
  321. Doorkeeper::AccessGrant.by_resource_owner(self).update_all(revoked_at: Time.now.utc)
  322. Doorkeeper::AccessToken.by_resource_owner(self).in_batches do |batch|
  323. batch.update_all(revoked_at: Time.now.utc)
  324. Web::PushSubscription.where(access_token_id: batch).delete_all
  325. end
  326. end
  327. def reset_password!
  328. # First, change password to something random and deactivate all sessions
  329. transaction do
  330. update(password: SecureRandom.hex)
  331. session_activations.destroy_all
  332. end
  333. # Then, remove all authorized applications and connected push subscriptions
  334. revoke_access!
  335. # Finally, send a reset password prompt to the user
  336. send_reset_password_instructions
  337. end
  338. def show_all_media?
  339. setting_display_media == 'show_all'
  340. end
  341. def hide_all_media?
  342. setting_display_media == 'hide_all'
  343. end
  344. protected
  345. def send_devise_notification(notification, *args, **kwargs)
  346. # This method can be called in `after_update` and `after_commit` hooks,
  347. # but we must make sure the mailer is actually called *after* commit,
  348. # otherwise it may work on stale data. To do this, figure out if we are
  349. # within a transaction.
  350. # It seems like devise sends keyword arguments as a hash in the last
  351. # positional argument
  352. kwargs = args.pop if args.last.is_a?(Hash) && kwargs.empty?
  353. if ActiveRecord::Base.connection.current_transaction.try(:records)&.include?(self)
  354. pending_devise_notifications << [notification, args, kwargs]
  355. else
  356. render_and_send_devise_message(notification, *args, **kwargs)
  357. end
  358. end
  359. private
  360. def send_pending_devise_notifications
  361. pending_devise_notifications.each do |notification, args, kwargs|
  362. render_and_send_devise_message(notification, *args, **kwargs)
  363. end
  364. # Empty the pending notifications array because the
  365. # after_commit hook can be called multiple times which
  366. # could cause multiple emails to be sent.
  367. pending_devise_notifications.clear
  368. end
  369. def pending_devise_notifications
  370. @pending_devise_notifications ||= []
  371. end
  372. def render_and_send_devise_message(notification, *args, **kwargs)
  373. devise_mailer.send(notification, self, *args, **kwargs).deliver_later
  374. end
  375. def set_approved
  376. self.approved = begin
  377. if sign_up_from_ip_requires_approval?
  378. false
  379. else
  380. open_registrations? || valid_invitation? || external?
  381. end
  382. end
  383. end
  384. def sign_up_from_ip_requires_approval?
  385. !sign_up_ip.nil? && IpBlock.where(severity: :sign_up_requires_approval).where('ip >>= ?', sign_up_ip.to_s).exists?
  386. end
  387. def open_registrations?
  388. Setting.registrations_mode == 'open'
  389. end
  390. def external?
  391. !!@external
  392. end
  393. def bypass_invite_request_check?
  394. @bypass_invite_request_check
  395. end
  396. def sanitize_languages
  397. return if chosen_languages.nil?
  398. chosen_languages.reject!(&:blank?)
  399. self.chosen_languages = nil if chosen_languages.empty?
  400. end
  401. def sanitize_role
  402. return if role.nil?
  403. self.role = nil if role.everyone?
  404. end
  405. def prepare_new_user!
  406. BootstrapTimelineWorker.perform_async(account_id)
  407. ActivityTracker.increment('activity:accounts:local')
  408. ActivityTracker.record('activity:logins', id)
  409. UserMailer.welcome(self).deliver_later
  410. TriggerWebhookWorker.perform_async('account.approved', 'Account', account_id)
  411. end
  412. def prepare_returning_user!
  413. return unless confirmed?
  414. ActivityTracker.record('activity:logins', id)
  415. regenerate_feed! if needs_feed_update?
  416. end
  417. def notify_staff_about_pending_account!
  418. User.those_who_can(:manage_users).includes(:account).find_each do |u|
  419. next unless u.allows_pending_account_emails?
  420. AdminMailer.new_pending_account(u.account, self).deliver_later
  421. end
  422. end
  423. def regenerate_feed!
  424. RegenerationWorker.perform_async(account_id) if redis.set("account:#{account_id}:regeneration", true, nx: true, ex: 1.day.seconds)
  425. end
  426. def needs_feed_update?
  427. last_sign_in_at < ACTIVE_DURATION.ago
  428. end
  429. def validate_email_dns?
  430. email_changed? && !external? && !(Rails.env.test? || Rails.env.development?)
  431. end
  432. def validate_role_elevation
  433. errors.add(:role_id, :elevated) if defined?(@current_account) && role&.overrides?(@current_account&.user_role)
  434. end
  435. def invite_text_required?
  436. Setting.require_invite_text && !open_registrations? && !invited? && !external? && !bypass_invite_request_check?
  437. end
  438. def trigger_webhooks
  439. TriggerWebhookWorker.perform_async('account.created', 'Account', account_id)
  440. end
  441. end