Example #1
0
    def get_raw_token(self, header):
        """
        Extracts an unvalidated JSON web token from the given "Authorization"
        header value.
        """
        parts = header.split()

        if len(parts) == 0:
            # Empty AUTHORIZATION header sent
            return None

        if parts[0].decode(HTTP_HEADER_ENCODING) != "Server":
            # Assume the header does not contain a JSON web token
            raise AuthenticationFailed(
                _('Authorization not from server'),
                code='bad_authorization_header',
            )

        if len(parts) != 2:
            raise AuthenticationFailed(
                _('Authorization header must contain two space-delimited values'),
                code='bad_authorization_header',
            )

        return parts[1]
Example #2
0
    def get_user(self, validated_token):
        """
        Attempts to find and return a user using the given validated token.
        """
        try:
            user_id = validated_token[api_settings.USER_ID_CLAIM]
        except KeyError:
            raise InvalidToken(
                _('Token contained no recognizable user identification'))

        try:
            user = User.objects.get(**{api_settings.USER_ID_FIELD: user_id})
        except User.DoesNotExist:
            raise AuthenticationFailed(_('User not found'),
                                       code='user_not_found')

        if not user.is_active:
            raise AuthenticationFailed(_('User is inactive'),
                                       code='user_inactive')

        if not user.password[-10:] == validated_token['hash']:
            raise AuthenticationFailed(_('User changed password'),
                                       code='user_inactive')

        return user
    def get_user(self, validated_token):
        """
        Attempts to find and return a user using the given validated token.
        """
        try:
            user_id = validated_token[api_settings.USER_ID_CLAIM]
        except KeyError:
            raise InvalidToken(
                _("Token contained no recognizable user identification"))

        try:
            user = User.objects.get(**{api_settings.USER_ID_FIELD: user_id})
        except User.DoesNotExist:
            raise AuthenticationFailed(_("User not found"),
                                       code="user_not_found")

        if not user.is_active:
            raise AuthenticationFailed(_("User is inactive"),
                                       code="user_inactive")

        if not "access_token_secret" in validated_token:
            raise AuthenticationFailed(
                _("Bad Token used. Get new access Token"),
                code="get_new_access_token")

        if (not user.profile.access_token_secret
                == validated_token["access_token_secret"]):
            raise AuthenticationFailed(
                _("Bad Token used. Get new access Token"),
                code="get_new_access_token")

        return user
    def get_user(self, validated_token):
        """
        Attempts to find and return a user using the given validated token.
        """
        try:
            user_id = validated_token[api_settings.USER_ID_CLAIM]
        except KeyError:
            raise InvalidToken(
                _('Token contained no recognizable user identification'))

        try:
            values = {api_settings.USER_ID_FIELD: user_id}
            user = User.objects.get(**values)
        except User.DoesNotExist:
            if settings.SIMPLE_JWT.get('CREATE_USER', False):
                user = User.objects.create(password=str(uuid4()), **values)
            else:
                raise AuthenticationFailed(_('User not found'),
                                           code='user_not_found')

        if not user.is_active:
            raise AuthenticationFailed(_('User is inactive'),
                                       code='user_inactive')

        return user
Example #5
0
    def get_user(self, validated_token):
        """
        Attempts to find and return a user using the given validated token.
        """
        try:
            user_id = validated_token[api_settings.USER_ID_CLAIM]
        except KeyError:
            raise InvalidToken(
                _('Token contained no recognizable user identification')) from KeyError

        user_model = get_user_model()
        try:
            user = user_model.objects.get(
                **{api_settings.USER_ID_FIELD: user_id})
        except user_model.DoesNotExist:
            raise AuthenticationFailed(
                _('User not found'), code='user_not_found') from user_model.DoesNotExist

        if not user.is_active:
            raise AuthenticationFailed(
                _('User is inactive'), code='user_inactive')

        if not user.has_finished_onboarding and not user.is_admin:
            raise HasNotFinishedOnboarding(detail={
                'detail': 'User hasn\'t finished the onboarding',
                'onboarding_session': user.onboarding_session
            })

        return user
    def get_user(self, validated_token):
        """
        Attempts to find and return a user using the given validated token.
        """
        try:
            user_id = validated_token[api_settings.USER_ID_CLAIM]
        except KeyError:
            raise InvalidToken(_('Token contained no recognizable user identification'))

        print(user_id)
        print(type(user_id))

        try:
            print(api_settings.USER_ID_FIELD)
            print("we printed the user_id field")
            user = User.objects.get(**{api_settings.USER_ID_FIELD: user_id})
        except User.DoesNotExist:
            print("heuhreuhrue??")
            raise AuthenticationFailed(_('User not found'), code='user_not_found')

        if not user.is_active:
            raise AuthenticationFailed(_('User is inactive'), code='user_inactive')

        print("we are returning the user??")
        return user
Example #7
0
    def validate(self, attrs):
        authenticate_kwargs = {
            self.username_field: attrs[self.username_field],
            "password": attrs["password"],
        }
        try:
            authenticate_kwargs["request"] = self.context["request"]
        except KeyError:
            pass
        if ratelimit(self.context["request"], "login", [authenticate_kwargs[self.username_field]]):
            raise CaptchaRequiredException(
                detail={"status": 429, "detail": "Too Many Requests Provide Captcha"},
                code=status.HTTP_429_TOO_MANY_REQUESTS,
            )
        self.user = authenticate(**authenticate_kwargs)

        # Prior to Django 1.10, inactive users could be authenticated with the
        # default `ModelBackend`.  As of Django 1.10, the `ModelBackend`
        # prevents inactive users from authenticating.  App designers can still
        # allow inactive users to authenticate by opting for the new
        # `AllowAllUsersModelBackend`.  However, we explicitly prevent inactive
        # users from authenticating to enforce a reasonable policy and provide
        # sensible backwards compatibility with older Django versions.
        if self.user is None or not self.user.is_active:
            raise AuthenticationFailed(
                self.error_messages["no_active_account"], "no_active_account",
            )

        return {}
Example #8
0
    def get_user(self, validated_token: Dict[str, AnyStr]) -> User:
        try:
            user_id = validated_token[api_settings.USER_ID_CLAIM]
        except KeyError:
            raise InvalidToken(
                'Token contained no recognizable user identification')

        try:
            user = User.objects.only(api_settings.USER_ID_FIELD).get(
                **{api_settings.USER_ID_FIELD: user_id})
        except User.DoesNotExist:
            raise AuthenticationFailed('User not found', code='user_not_found')

        if not user.is_active:
            raise AuthenticationFailed('User is inactive',
                                       code='user_inactive')
        return user
Example #9
0
 def authenticate(self, request) -> AbstractUser:  # type: ignore # pylint: disable=arguments-differ
     # in development, with DEBUG turned on, authenticate
     # as the user specified in the Authorization header
     username = request.META.get("HTTP_AUTHORIZATION")
     if not username:
         raise AuthenticationFailed()
     user, _ = User.objects.get_or_create(username=username.strip())
     return user
Example #10
0
    def validate(self, attrs):
        try:
            password = attrs.get('password')
            token = attrs.get('token')
            uidb64 = attrs.get('uidb64')

            uid = force_str(urlsafe_base64_decode(uidb64))
            user = User.objects.get(id=uid)
            if not PasswordResetTokenGenerator().check_token(user, token):
                raise AuthenticationFailed('The reset link is invalid 3', 401)

            user.set_password(password)
            user.save()

            return user

        except Exception as e:
            raise AuthenticationFailed('The reset link is invalid 4', 401)
Example #11
0
def check_user_status(user):
    """
    check on user is_disabled and is_blocked status and
    raise appropriate error with detail messages for login to display
    """
    if not user:
        raise PermissionDenied(message="Failed to obtain user",
                               code="no_user_found")
    if user.is_blocked:
        raise AuthenticationFailed(
            'This user has been blocked. If you think this is a mistake, please contact Find Dining team to resolve it',
            'user_blocked',
        )
    elif not user.is_active:
        raise AuthenticationFailed(
            'This user is disabled.',
            'user_disabled',
        )
    def get_user(self, validated_token):
        User = get_user_model()
        try:
            user_id = validated_token[api_settings.USER_ID_CLAIM]
        except KeyError:
            raise InvalidToken(
                _("Token contained no recognizable user identification"))

        try:
            user = User.objects.get(**{api_settings.USER_ID_FIELD: user_id})
        except User.DoesNotExist:
            raise AuthenticationFailed(_("User not found"),
                                       code="user_not_found")

        if not user.confirmed:
            raise AuthenticationFailed(_("User not found"),
                                       code="user_not_found")

        return user
    def get_user(self, validated_token):
        """
        Attempts to find and return a user using the given validated token.
        """
        from rest_framework_simplejwt.exceptions import AuthenticationFailed
        from rest_framework_simplejwt.exceptions import InvalidToken
        from rest_framework_simplejwt.settings import api_settings

        try:
            user_id = validated_token[api_settings.USER_ID_CLAIM]
        except KeyError:
            raise InvalidToken(
                _('Token contained no recognizable user identification'))

        try:
            user_site = validated_token['site']
        except KeyError:
            raise InvalidToken(
                _('Token contained no recognizable site identification'))

        site = None
        if self.request:
            site = Site.objects.get_current(self.request)
        if site is None:
            raise AuthenticationFailed(_('Site not found'),
                                       code='user_not_found')
        if user_site != site.domain:
            raise AuthenticationFailed(_('Site is not match'),
                                       code='user_not_found')

        try:
            user = get_user_model().objects.get(
                **{api_settings.USER_ID_FIELD: user_id})
        except get_user_model().DoesNotExist:
            raise AuthenticationFailed(_('User not found'),
                                       code='user_not_found')

        if not user.is_active:
            raise AuthenticationFailed(_('User is inactive'),
                                       code='user_inactive')

        return user
Example #14
0
    def get_user(self, validated_token):
        try:
            user_id = validated_token[api_settings.USER_ID_CLAIM]
        except KeyError:
            raise InvalidToken(_('Token contained no recognizable user identification'))

        User = get_user_model()

        try:
            user = User.objects.get(**{api_settings.USER_ID_FIELD: user_id})
        except User.DoesNotExist:
            user = None
            if api_settings.NEW_USER_CALLBACK:
                user = api_settings.NEW_USER_CALLBACK(self.request, user_id)
            if user is None:
                raise AuthenticationFailed(_('User not found'), code='user_not_found')

        if not user.is_active:
            raise AuthenticationFailed(_('User is inactive'), code='user_inactive')

        return user
Example #15
0
    def validate(self, attrs):
        logger.info(f'token validating. username: {attrs[self.username_field]}, password: ***')
        user_queryset = KhumuUser.objects.filter(username=attrs[self.username_field])
        if not user_queryset.exists():
            raise AuthenticationFailed(detail="ID 혹은 Password가 잘못되었습니다.")
        self.user = user_queryset.first()

        if self.user.status == 'deleted':
            raise AuthenticationFailed(detail="탈퇴한 유저입니다.")

        # student kind가 아니면 password 그대로 인증
        if self.user.kind != 'student':
            if not self.user.check_password(attrs['password']):
                raise AuthenticationFailed(detail="ID 혹은 Password가 잘못되었습니다.")
            else:
                pass # 인증 성공
        # student kind라면 password로 info 21 인증
        else:
            auth_job = KhuAuthJob({
                'id': attrs[self.username_field],
                'password': attrs['password']
            })

            user_info = auth_job.process()

            if not user_info.verified:
                logger.error('알 수 없는 이유로 info21 로그인에 실패했습니다.')
                return {
                    'message': '알 수 없는 이유로 info21 로그인에 실패했습니다.'
                }

            self.user = KhumuUser.objects.get(username=attrs[self.username_field], student_number=user_info.student_num)

        result = {}
        refresh = self.get_token(self.user)

        result['refresh'] = str(refresh)
        result['access'] = str(refresh.access_token)
        return result
Example #16
0
    def get_user(self, validated_token):
        """
        Attempts to find and return a user using the given validated token.
        """
        user_model = get_user_model()
        try:
            user_id = validated_token[api_settings.USER_ID_CLAIM]
        except KeyError:
            raise InvalidToken(
                'Token contained no recognizable user identification')

        try:
            user = user_model.objects.get(
                **{api_settings.USER_ID_FIELD: user_id})
        except user_model.DoesNotExist:
            raise AuthenticationFailed('User not found', code='user_not_found')

        if not user.is_active:
            raise AuthenticationFailed('User is inactive',
                                       code='user_inactive')

        return user
Example #17
0
 def authenticate(self, request: Request):
     try:
         jwt_access_token = request.COOKIES["JWT-access"]
         UntypedToken(jwt_access_token)
         decoded_data = jwt_decode(jwt_access_token,
                                   settings.SECRET_KEY,
                                   algorithms=["HS256"])
         user = get_user_model().objects.get(id=decoded_data["user_id"])
         return (user, None)
     except (InvalidToken, TokenError, KeyError,
             get_user_model().DoesNotExist):
         raise AuthenticationFailed("Authentication Failed.")
         return None
Example #18
0
    def authenticate(
            self,
            request: Request) -> Union[Tuple[User, Dict[str, AnyStr]], None]:
        try:
            user, validated_token = super().authenticate(request)
        except TypeError:
            return None
        if user.token_expired != validated_token.payload['exp']:
            raise AuthenticationFailed("User don't have valid token",
                                       code='invalid_token')

        user = self.get_typed_user(user)
        self.enforce_csrf(request)
        return user, validated_token
Example #19
0
    def validate(self, attr):
        email = attr.get('email')
        password = attr.get('password')
        # print(email)
        # print(password)

        user = authenticate(email=email, password=password)

        # print(user)

        if not user:
            raise AuthenticationFailed('Invalid Login Parameters')
        if not user.is_active:
            raise AuthenticationFailed(
                'Account has been disabled, please contact us for more info')
        if not user.is_verified:
            raise AuthenticationFailed('User is not verified')

        return {
            'email': user.email,
            'username': user.username,
            'tokens': user.get_tokens()
        }
    def get_user(self, validated_token):
        """
        Attempts to find and return a user using the given validated token.
        """
        try:
            user_id = validated_token[api_settings.USER_ID_CLAIM]
        except KeyError:
            raise InvalidToken('Token contained no recognizable user identification')

        user, created = User.objects.get_or_create(**{api_settings.USER_ID_FIELD: user_id})

        if not user.is_active:
            raise AuthenticationFailed('User is inactive', code='user_inactive')

        return user
Example #21
0
    def authenticate(self, request) -> AbstractUser:  # type: ignore # pylint: disable=arguments-differ
        if request.META.get("HTTP_X_SSL_CLIENT_VERIFY") != "SUCCESS":
            raise AuthenticationFailed()

        client_dn = request.META.get("HTTP_X_SSL_CLIENT_S_DN")

        # TODO: implement CRL check using client_cert (see issues #93 and #79)
        fields = self.parse_dn(client_dn)

        user, _ = User.objects.update_or_create(
            username=fields["username"],
            defaults={
                "first_name": fields["first_name"],
                "last_name": fields["last_name"],
            },
        )
        return user
Example #22
0
    def get_user(self, validated_token):
        """
        Attempts to find and return a user using the given validated token.
        """
        try:
            user_id = validated_token[api_settings.USER_ID_CLAIM]
        except KeyError:
            raise InvalidToken(
                _('Token contained no recognizable user identification'))

        user = self.get_token_user(user_id, validated_token['user_info'])

        if not user.is_active:
            raise AuthenticationFailed(_('User is inactive'),
                                       code='user_inactive')

        return user
    def get_user(self, validated_token):
        """
        Attempts to find and return a user using the given validated token.
        """
        try:
            user_id = validated_token[api_settings.USER_ID_CLAIM]
        except KeyError:
            raise InvalidToken(
                _('Token contained no recognizable user identification'))

        try:
            user = User.objects.get(**{api_settings.USER_ID_FIELD: user_id})
        except User.DoesNotExist:
            raise AuthenticationFailed(
                _('Истроия по данному пользователю не найдено'),
                code='user_not_found')

        return user
Example #24
0
    def authenticate(self, request):
        header = self.get_header(request)
        if header is None:
            return None

        raw_token = self.get_raw_token(header)
        if raw_token is None:
            return None

        validated_token = self.get_validated_token(raw_token)

        #@Ole: add extra validation for blacklist
        is_allowed = self.is_not_on_blacklist(raw_token, validated_token)

        if is_allowed:
            return self.get_user(validated_token), validated_token
        else: 
            raise AuthenticationFailed(_('User is logged out'), code='user_logged_out')
Example #25
0
    def get_header(self, request):
        """
        Extracts the header containing the JSON web token from the given
        request.
        """

        header = request.META.get("HTTP_USER_KEY")

        if not header:
            raise AuthenticationFailed(
                _("Authorization header must contain USER-KEY header param"),
                code="bad_authorization_header",
            )

        if isinstance(header, str):
            # Work around django test client oddness
            header = header.encode(HTTP_HEADER_ENCODING)

        return header
    def validate(self, attrs):
        """
        Validate the input, saves user if valid
        :param attrs:
        :raises AuthenticationFailed: If data is not valid
        :return: refresh access tokens
        """
        user_form = \
            CustomUserCreationForm(self.initial_data)

        if user_form.is_valid():
            user = user_form.save(commit=True)
        else:
            raise AuthenticationFailed(user_form.errors)

        refresh = RefreshToken.for_user(user)

        return {
            'refresh': str(refresh),
            'access': str(refresh.access_token),
        }
Example #27
0
    def validate(self, attrs):
        """
        simple check on user status before authenticate
        """
        username = attrs['username']

        try:
            user = UserModel.objects.get(
                Q(username__iexact=username) | Q(email__iexact=username))
            check_user_status(user)
        except UserModel.DoesNotExist:
            raise AuthenticationFailed(
                'User does not exist',
                'user_not_found',
            )
        except MultipleObjectsReturned:
            user = UserModel.objects.filter(
                Q(username__iexact=username)
                | Q(email__iexact=username)).order_by('id').first()
            check_user_status(user)

        return super().validate(attrs)
Example #28
0
    def get_raw_token(self, header):
        """
        Extracts an unvalidated JSON web token from the given "Authorization"
        header value.
        """
        parts = header.split()

        if len(parts) == 0:
            # Empty AUTHORIZATION header sent
            return None

        if parts[0] not in AUTH_HEADER_TYPE_BYTES:
            # Assume the header does not contain a JSON web token
            return None

        if len(parts) != 2:
            logger('errors').error(f'Authenticaion failed due to header {header}')
            raise AuthenticationFailed(
                _('Authorization header must contain two space-delimited values'),
                code='bad_authorization_header',
            )

        return parts[1]
Example #29
0
 def parse_dn(self, dn: Optional[str]) -> Dict[str, Any]:
     if dn is None or (match := self.CAC_DN_RE.search(dn)) is None:
         raise AuthenticationFailed()
Example #30
0
        User credentials acquisition is cached for 5 minutes.
        If the user is deleted, cache is invalidated.
        Timeout of cache cannot last more than access token lifetime.
        """
        try:
            user_id = validated_token[api_settings.USER_ID_CLAIM]
        except KeyError:
            raise InvalidToken(
                _('Token contained no recognizable user identification')
            )

        try:
            if cached := cache.get(f'jwt_user_{user_id}'):
                user = cached
            else:
                user = User.objects.get(
                    **{api_settings.USER_ID_FIELD: user_id}
                )
                cache.set(f'jwt_user_{user_id}', user)
        except User.DoesNotExist:
            raise AuthenticationFailed(
                _('User not found'), code='user_not_found'
            )

        if not user.is_active:
            raise AuthenticationFailed(
                _('User is inactive'), code='user_inactive'
            )

        return user