def validate(self, attrs): user = self.context.get('request').user try: current_method = user.mfa_methods.get( is_primary=True, is_active=True, ) except ObjectDoesNotExist: self.fail('not_enabled') try: new_primary_method = user.mfa_methods.get( name=attrs.get('method'), is_active=True, ) except ObjectDoesNotExist: self.fail('missing_method') code = attrs.get('code') validated_backup_code = validate_backup_code( code, current_method.backup_codes, ) if validate_code(code, current_method): attrs.update(new_method=new_primary_method) attrs.update(old_method=current_method) return attrs elif validated_backup_code: attrs.update(new_method=new_primary_method) attrs.update(old_method=current_method) current_method.remove_backup_code(validated_backup_code) return attrs else: self.fail('invalid_code')
def _validate_code(self, value): if not value: self.fail('otp_code_missing') obj = self.context['obj'] validated_backup_code = validate_backup_code(value, obj.backup_codes) handler = get_mfa_handler(obj) validate_method = getattr(handler, self.handler_validation_method) if validate_method(value): return value if validated_backup_code: obj.remove_backup_code(validated_backup_code) return value self.fail('code_invalid_or_expired')
def _validate_code(self, value): if not value: self.fail('otp_code_missing') obj = self.context['obj'] validity_period = ( self.context['conf'].get('VALIDITY_PERIOD') or api_settings.DEFAULT_VALIDITY_PERIOD # noqa ) validated_backup_code = validate_backup_code(value, obj.backup_codes) if validate_code(value, obj, validity_period): return value if validated_backup_code: obj.remove_backup_code(validated_backup_code) return value self.fail('code_invalid_or_expired')
def validate(self, attrs): ephemeral_token = attrs.get('ephemeral_token') code = attrs.get('code') self.user = user_token_generator.check_token(ephemeral_token) if not self.user: self.fail('invalid_token') for auth_method in self.user.mfa_methods.filter(is_active=True): validated_backup_code = validate_backup_code( code, auth_method.backup_codes, ) if validate_code(code, auth_method): return attrs if validated_backup_code: auth_method.remove_backup_code(validated_backup_code) return attrs self.fail('invalid_code')