Esempio n. 1
0
 def find_token_expiration(digest):
     auther = TokenAuthentication()
     # XXX This is pretty wasteful since token auth can be expensive
     # but should suffice until:
     # https://github.com/James1345/django-rest-knox/issues/131
     return auther.authenticate_credentials(
         digest.encode('utf-8'))[1].expires
Esempio n. 2
0
	def has_permission(self, request, view):
		print(request.path)
		if 'Authorization' in request.headers:
			knoxAuth = TokenAuthentication()
			user, auth_token = knoxAuth.authenticate(request)
			if user:
				patient_id = request.path.split("/")[-2].split("_")[1]
				if user.user_type == 'Patient':
					if(user.id == int(patient_id)):
						return True
					else:
						return False
				else:
					doctor = Doctor.objects.get(doctor=user)
					user_patient = User.objects.get(id=int(patient_id))
					patient = Patient.objects.get(patient=user_patient)
					otpAccountSet = PhoneOTP.objects.filter(patient_id=patient, doctor_id=doctor)
					if otpAccountSet.exists():
						otpAccount = otpAccountSet.first()
						if otpAccount.has_rights():
							return True
						else:
							return False
					else:
							return False
			else:
				return False
 def _check_login_social_knox_only(self, url, data):
     resp = self.client.post(url, data)
     self.assertEqual(resp.status_code, 200)
     # check token valid
     knox_auth = KnoxTokenAuthentication()
     user, auth_data = knox_auth.authenticate_credentials(resp.data['token'].encode('utf8'))
     self.assertEqual(user.email, self.email)
Esempio n. 4
0
def serve_images(request, *, pk, path, pa="", pb=""):
    document_root = safe_join(
        f"/{settings.IMAGE_FILES_SUBDIRECTORY}", pa, pb, str(pk)
    )
    path = posixpath.normpath(path).lstrip("/")
    name = safe_join(document_root, path)

    try:
        image = Image.objects.get(pk=pk)
    except Image.DoesNotExist:
        raise Http404("Image not found.")

    try:
        user, _ = TokenAuthentication().authenticate(request)
    except (AuthenticationFailed, TypeError):
        user = request.user

    if user.has_perm("view_image", image):
        on_commit(
            lambda: create_download.apply_async(
                kwargs={"creator_id": user.pk, "image_id": image.pk}
            )
        )
        return protected_storage_redirect(name=name)

    raise PermissionDenied
Esempio n. 5
0
def get_user(access_token):
    try:
        auth = TokenAuthentication()
        token = access_token.decode().split("access_token=")[1]
        user = auth.authenticate_credentials(token.encode())
    except Exception:
        return AnonymousUser()
    else:
        return user[0]
Esempio n. 6
0
def get_user(query_params):
    close_old_connections()
    knox_auth = TokenAuthentication()
    try:
        token = query_params.get('token', (None, ))[0]
        user, auth_token = knox_auth.authenticate_credentials(
            token.encode(HTTP_HEADER_ENCODING))
        return user
    except AuthenticationFailed:
        return AnonymousUser()
Esempio n. 7
0
 def _check_login_social_knox_only(self, url, data):
     try:
         from knox.auth import TokenAuthentication
     except ImportError:
         return
     resp = self.client.post(url, data)
     self.assertEqual(resp.status_code, 200)
     # check token valid
     knox_auth = TokenAuthentication()
     user, auth_data = knox_auth.authenticate_credentials(
         resp.data['token'])
     self.assertEqual(user.email, self.email)
Esempio n. 8
0
 def __call__(self, scope):
     headers = dict(scope['headers'])
     if b'authorization' in headers:
         try:
             knoxAuth = TokenAuthentication()
             user, auth_token = knoxAuth.authenticate_credentials(
                 tokenString.encode(HTTP_HEADER_ENCODING))
             if token_name == 'Token':
                 token = Token.objects.get(key=token_key)
                 scope['user'] = user
                 close_old_connections()
         except auth_token.DoesNotExist:
             scope['user'] = AnonymousUser()
     return self.inner(scope)
Esempio n. 9
0
 def __call__(self, scope):
     cookies = dict(scope['cookies'])
     if 'token' in cookies:
         try:
             tokenString = cookies['token']
             knoxAuth = TokenAuthentication()
             user, auth_token = knoxAuth.authenticate_credentials(
                 tokenString.encode("utf-8"))
             scope['user'] = user
         except AuthenticationFailed:
             logger.error("authentication failed!")
             scope['user'] = AnonymousUser()
     else:
         scope['user'] = AnonymousUser()
     return self.inner(scope)
Esempio n. 10
0
def serve_component_interface_value(
    request, *, component_interface_value_pk, **_
):
    try:
        user, _ = TokenAuthentication().authenticate(request)
    except (AuthenticationFailed, TypeError):
        user = request.user

    try:
        # output should only be connected to a single job; throw error if not?
        civ = ComponentInterfaceValue.objects.get(
            pk=component_interface_value_pk
        )
    except (MultipleObjectsReturned, ComponentInterfaceValue.DoesNotExist):
        raise Http404("No ComponentInterfaceValue found.")

    if (
        get_objects_for_user(
            user=user, perms="algorithms.view_job", accept_global_perms=False
        )
        .filter(
            Q(outputs__pk=component_interface_value_pk)
            | Q(inputs__pk=component_interface_value_pk)
        )
        .exists()
    ):
        return protected_storage_redirect(name=civ.file.name)

    raise PermissionDenied
Esempio n. 11
0
 def get_object_token(self, token):
     cus_user = TokenAuthentication().authenticate_credentials(
         token=token.encode(encoding='UTF-8', errors='strict'))
     try:
         return TestVolunteer.objects.get(user=cus_user[0])
     except TestVolunteer.DoesNotExist:
         return Response(status=status.HTTP_404_NOT_FOUND)
Esempio n. 12
0
 def __call__(self, scope):
     headers = dict(scope['headers'])
     if b'sec-websocket-protocol' in headers:
         try:
             close_old_connections()
             token_key = headers[b'sec-websocket-protocol'].decode('utf-8')
             knoxAuth = TokenAuthentication()
             try:
                 user, auth_token = knoxAuth.authenticate_credentials(
                     token_key.encode(HTTP_HEADER_ENCODING))
             except Exception:
                 return self.inner(scope)
             scope['user'] = user
         except AuthToken.DoesNotExist:
             scope['user'] = AnonymousUser()
     return self.inner(scope)
Esempio n. 13
0
    def authenticate(self, request):
        """
        Implement authenticator interface.

        See https://www.django-rest-framework.org/api-guide/authentication/#custom-authentication
        """
        # Try to authenticate with the "real" authenticators
        user_auth = BasicAuthentication().authenticate(request)
        if not user_auth:
            user_auth = TokenAuthentication().authenticate(request)

        # Not authenticated so leave
        if not user_auth:
            return None

        # Authenticated, so look for special header...
        # This is wrapped in a try/catch because we really don't want
        # this side-effect to stop the authentication process
        try:
            user, auth = user_auth
            header = request.META.get("HTTP_OAUTH_TOKEN")
            if header:
                parts = header.split(" ")
                if len(parts) == 2:
                    provider, token = parts
                    refresh_user_access_token(user, provider, token)
        except Exception:
            logger.error("Error attempting to refresh OAuth token",
                         exc_info=True)

        return user_auth
Esempio n. 14
0
 def test_update_token_key(self):
     self.assertEqual(AuthToken.objects.count(), 0)
     token = AuthToken.objects.create(self.user)
     rf = APIRequestFactory()
     request = rf.get('/')
     request.META = {'HTTP_AUTHORIZATION': 'Token {}'.format(token)}
     (self.user, auth_token) = TokenAuthentication().authenticate(request)
     self.assertEqual(token[:CONSTANTS.TOKEN_KEY_LENGTH],
                      auth_token.token_key)
Esempio n. 15
0
    def receive_json(self, content, **kwargs):
        print('received message', content)

        message_type = content.get('type')

        if message_type is None:
            self._send_error('No Message type')
            return

        if message_type == 'authentication':
            knox_auth = TokenAuthentication()

            if not isinstance(content['token'], str):
                self._send_message('authentication',
                                   state='failure',
                                   reason='invalid token field')

            else:
                try:
                    user, auth_token = knox_auth.authenticate_credentials(
                        content['token'].encode('UTF-8'))
                except AuthenticationFailed:
                    user, auth_token = None, None
                if user is not None:
                    self._token = auth_token
                    self.scope['user'] = user
                    self._send_message('authentication', state='success')
                    self._on_user_authenticated(auth_token, user)
                else:
                    self._send_message('authentication',
                                       state='failure',
                                       reason='invalid token')
            return

        if self._token is None:
            self._send_error('not logged in')
            return

        try:
            self._receive_message(message_type, content)
        except Exception as e:
            traceback.print_exc()
            print(e)
Esempio n. 16
0
    def connect(self):
        self.room_group_name = 'lobby'
        self.knoxAuth = TokenAuthentication()

        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )

        self.accept()
Esempio n. 17
0
 async def __call__(self, receive, send):
     knoxAuth = TokenAuthentication()
     try:
         user, auth_token = await database_sync_to_async(
             knoxAuth.authenticate_credentials)(self.scope['query_string'])
         self.scope['user'] = user
     except AuthenticationFailed:
         self.scope['user'] = AnonymousUser()
     inner = self.inner(self.scope)
     inner = await inner(receive, send)
     return inner
Esempio n. 18
0
 def test_authorization_header_prefix_only(self):
     rf = APIRequestFactory()
     request = rf.get('/')
     request.META = {'HTTP_AUTHORIZATION': 'Token'}
     with self.assertRaises(AuthenticationFailed) as err:
         (self.user,
          auth_token) = TokenAuthentication().authenticate(request)
     self.assertIn(
         'Invalid token header. No credentials provided.',
         str(err.exception),
     )
Esempio n. 19
0
 def test_authorization_header_spaces_in_token_string(self):
     rf = APIRequestFactory()
     request = rf.get('/')
     request.META = {'HTTP_AUTHORIZATION': 'Token wordone wordtwo'}
     with self.assertRaises(AuthenticationFailed) as err:
         (self.user,
          auth_token) = TokenAuthentication().authenticate(request)
     self.assertIn(
         'Invalid token header. Token string should not contain spaces.',
         str(err.exception),
     )
Esempio n. 20
0
    def connect(self):

        self.token = self.scope['url_route']['kwargs']['token']
        self.issueID = self.scope['url_route']['kwargs']['issueID']
        self.room_group_name = 'issue_' + str(self.issueID)

        knoxAuth = TokenAuthentication()
        user, auth_token = knoxAuth.authenticate_credentials(
            self.token.encode(HTTP_HEADER_ENCODING))

        if user:

            try:
                self.issue = Issue.objects.get(id=self.issueID)
                self.user = user
                async_to_sync(self.channel_layer.group_add)(
                    self.room_group_name, self.channel_name)
                self.accept()

            except Issue.DoesNotExist:
                pass
Esempio n. 21
0
 def test_update_token_key(self):
     self.assertEqual(AuthToken.objects.count(), 0)
     username, password = '******', 'toor'
     user = User.objects.create_user(
         username, '*****@*****.**', password)
     token = AuthToken.objects.create(user)
     rf = APIRequestFactory()
     request = rf.get('/')
     request.META = {'HTTP_AUTHORIZATION': 'Token {}'.format(token)}
     (user, auth_token) = TokenAuthentication().authenticate(request)
     self.assertEqual(
         token[:CONSTANTS.TOKEN_KEY_LENGTH],
         auth_token.token_key)
Esempio n. 22
0
def streaming_script_execute(request):
    try:
        form_data = json.loads(request.body.decode())

        posted_token = form_data.get('token')
        script_name = form_data.get('script_name')

        if posted_token is not None:
            token_auth = TokenAuthentication()
            user, _ = token_auth.authenticate_credentials(
                posted_token.encode("utf-8"))
            if user.is_authenticated and user.is_superuser:
                post_status = status.HTTP_200_OK
                executor = ScriptExecutor(script_name)
                stream = executor.stream()
                response_data = {}
                response_data['result'] = 'success'
                response_data['message'] = 'Script update success'

                for item in stream:
                    pass
                # Check if the last item in generator is an integer
                if item > 0 or item < 0:
                    post_status = status.HTTP_500_INTERNAL_SERVER_ERROR
                    response_data['result'] = 'error'
                    response_data['message'] = 'Failed to execute the script update'
                    response_data['returncode'] = item

                return HttpResponse(json.dumps(response_data), content_type='application/json', status=post_status)
        return redirect('/login/')
    except exceptions.AuthenticationFailed:
        return redirect('/login/')
    except Exception as e:
        handle_uncaught_error(e)
        response = {'detail': f'{str(e)}'}
        return HttpResponse(json.dumps(response), content_type='application/json', status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Esempio n. 23
0
    def test_post_method_with_valid_data(self):
        self.assertEqual(AuthToken.objects.count(), 0)

        admin_client = AccountFactory(
            user=self.user,
            role=RoleFactory(priority=RolePriority.ADMIN.value)).client
        response = self.client.post(self.path, {
            'email': '*****@*****.**',
            'password': '******'
        })
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertEqual(response.data,
                         {'detail': 'Unauthorized physician access'})

        AccountFactory(user=self.user,
                       role=RoleFactory(priority=RolePriority.PHYSICIAN.value))
        for token_count in range(1, 3):
            response = self.client.post(self.path, {
                'email': '*****@*****.**',
                'password': '******'
            })
            response_data = response.data

            self.assertEqual(response.status_code, status.HTTP_200_OK)
            token = response_data.pop('token')
            self.assertDictEqual(
                response_data, {
                    'user': {
                        'email': '*****@*****.**',
                        'name': 'Dr. Admin',
                        'default_client': None,
                        'admin_client': {
                            'id': admin_client.id,
                            'name': admin_client.name,
                            'image': None
                        }
                    }
                })
            self.assertIsNotNone(token)
            self.assertEqual(AuthToken.objects.count(), token_count)

            user, auth_token = TokenAuthentication().authenticate_credentials(
                token.encode())
            self.assertEqual(user, self.user)

        self.assertEqual(AuthToken.objects.filter(user=self.user).count(), 2)
Esempio n. 24
0
    def authenticate(self, request):
        """
        Authenticate a request.

        Returns a `User` if a valid token has been supplied
        using HTTP Basic authentication.  Otherwise returns `None`.
        """
        auth = get_authorization_header(request).split()

        if not auth or auth[0].lower() != b"basic":
            return None

        if len(auth) == 1:
            raise AuthenticationFailed(
                "Invalid Basic authorization header. No credentials provided.")
        elif len(auth) > 2:
            raise AuthenticationFailed(
                "Invalid Basic authorization header. Credentials string should not contain spaces."
            )

        try:
            auth_parts = (base64.b64decode(
                auth[1]).decode(HTTP_HEADER_ENCODING).split(":"))
        except (TypeError, UnicodeDecodeError, binascii.Error):
            raise AuthenticationFailed(
                "Invalid Basic authorization header. Credentials not correctly base64 encoded."
            )

        username, password = (auth_parts if len(auth_parts) >= 2 else
                              (auth_parts[0], None))
        if password:
            if settings.API_BASIC_AUTH:
                return DRFBasicAuthentication().authenticate_credentials(
                    username, password, request)
            else:
                raise AuthenticationFailed(
                    "Basic authorization with a password is not allowed; use an API token instead."
                )
        else:
            # Treat the username as a token; pass it on to `knox.TokenAuthentication`
            token = username.encode("utf-8")
            return TokenAuthentication().authenticate_credentials(token)
Esempio n. 25
0
def current_user(request, token):
    cus_user = TokenAuthentication().authenticate_credentials(
        token=token.encode(encoding='UTF-8', errors='strict'))
    # tokens = ''
    # # print(AuthToken.objects.filter(user))
    # for token in AuthToken.objects.all():
    #     # print(type(token))
    #     RHS = str(token).split(':')[1].strip()
    #     LHS = str(token).split(':')[0].strip()
    #     print(RHS)
    #     if RHS==user:
    #         tokens=LHS
    #         break
    # print(AuthToken.objects.all())
    # x = AuthToken.objects.filter(user=user)
    # print(x)
    return Response({
        'username': cus_user.username,
        # 'token': AuthToken.objects.create(user)[0]
    })
Esempio n. 26
0
from channels.auth import AuthMiddlewareStack
from django.db import close_old_connections
from rest_framework import HTTP_HEADER_ENCODING
from django.contrib.auth.models import AnonymousUser
from knox.auth import TokenAuthentication

knoxAuth = TokenAuthentication()


class TokenAuthMiddleware:
    """
    Token authorization middleware for Django Channels 2
    from https://gist.github.com/rluts/22e05ed8f53f97bdd02eafdf38f3d60a
    """
    def __init__(self, inner):
        self.inner = inner

    def __call__(self, scope):
        headers = dict(scope['headers'])
        if b'sec-websocket-protocol' in headers:
            try:
                close_old_connections()
                token_name, token_key = headers[
                    b'sec-websocket-protocol'].decode().split(', ')
                if token_name == 'access_token':
                    user, auth_token = knoxAuth.authenticate_credentials(
                        token_key.encode(HTTP_HEADER_ENCODING))
                    scope['user'] = user
            except:
                scope['user'] = AnonymousUser()
        return self.inner(scope)
Esempio n. 27
0
 def test_authorization_header_empty(self):
     rf = APIRequestFactory()
     request = rf.get('/')
     request.META = {'HTTP_AUTHORIZATION': ''}
     self.assertEqual(TokenAuthentication().authenticate(request), None)
 def __init__(self, inner):
     # Store the ASGI application we were passed
     self.inner = inner
     self.auth = TokenAuthentication()
def authenticate_user(token_auth: TokenAuthentication, token: bytes):
    return token_auth.authenticate_credentials(token)