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)
示例#2
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
示例#3
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]
示例#4
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()
示例#5
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)
示例#6
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)
示例#7
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)
示例#8
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)
示例#9
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)
示例#10
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
示例#11
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)
def authenticate_user(token_auth: TokenAuthentication, token: bytes):
    return token_auth.authenticate_credentials(token)