def all_interfaces_for_user(self, user, return_missing=False, ignore_backup=False): """Returns a correctly sorted list of all interfaces the user has enabled. If `return_missing` is set to `True` then all interfaces are returned even if not enabled. """ def _sort(x): return sorted(x, key=lambda x: (x.type == 0, x.type)) # Collect interfaces user is enrolled in ifaces = [ x.interface for x in Authenticator.objects.filter( user=user, type__in=[a.type for a in available_authenticators(ignore_backup=ignore_backup)], ) ] if return_missing: # Collect additional interfaces that the user # is not enrolled in rvm = dict(AUTHENTICATOR_INTERFACES) for iface in ifaces: rvm.pop(iface.interface_id, None) for iface_cls in rvm.values(): if iface_cls.is_available: ifaces.append(iface_cls()) return _sort(ifaces)
def user_has_2fa(self, user): """Checks if the user has any 2FA configured.""" return Authenticator.objects.filter( user=user, type__in=[ a.type for a in available_authenticators(ignore_backup=True) ]).exists()
def bulk_users_have_2fa(self, user_ids): """Checks if a list of user ids have 2FA configured. Returns a dict of {<id>: <has_2fa>} """ authenticators = set( Authenticator.objects.filter( user__in=user_ids, type__in=[a.type for a in available_authenticators(ignore_backup=True)], ) .distinct() .values_list("user_id", flat=True) ) return {id: id in authenticators for id in user_ids}
def auto_add_recovery_codes(self, user, force=False): """This automatically adds the recovery code backup interface in case no backup interface is currently set for the user. Returns the interface that was added. """ from sentry.auth.authenticators.recovery_code import RecoveryCodeInterface has_authenticators = False # If we're not forcing, check for a backup interface already setup # or if it's missing, we'll need to set it. if not force: for authenticator in Authenticator.objects.filter( user=user, type__in=[a.type for a in available_authenticators()] ): iface = authenticator.interface if iface.is_backup_interface: return has_authenticators = True if has_authenticators or force: interface = RecoveryCodeInterface() interface.enroll(user) return interface