Skip to content

Commit

Permalink
app: factor auth checks into decorator
Browse files Browse the repository at this point in the history
  • Loading branch information
redshiftzero committed Feb 6, 2020
1 parent 7bbb265 commit 341f6ec
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 22 deletions.
51 changes: 29 additions & 22 deletions securedrop_client/logic.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"""
import arrow
from datetime import datetime
import functools
import inspect
import logging
import os
Expand Down Expand Up @@ -47,6 +48,18 @@
logger = logging.getLogger(__name__)


def login_required(f):
@functools.wraps(f)
def decorated_function(self, *args, **kwargs):
if not self.api:
self.on_action_requiring_login()
return
else:
return f(self, *args, **kwargs)

return decorated_function


class APICallRunner(QObject):
"""
Used to call the SecureDrop API in a non-blocking manner.
Expand Down Expand Up @@ -405,23 +418,23 @@ def authenticated(self):
"""
return bool(self.api and self.api.token is not None)

@login_required
def sync_api(self):
"""
Grab data from the remote SecureDrop API in a non-blocking manner.
"""
logger.debug("In sync_api on thread {}".format(self.thread().currentThreadId()))
if self.authenticated():
self.sync_events.emit('syncing')
logger.debug("You are authenticated, going to make your call")
self.sync_events.emit('syncing')
logger.debug("You are authenticated, going to make your call")

job = MetadataSyncJob(self.data_dir, self.gpg)
job.success_signal.connect(self.on_sync_success, type=Qt.QueuedConnection)
job.failure_signal.connect(self.on_sync_failure, type=Qt.QueuedConnection)
job = MetadataSyncJob(self.data_dir, self.gpg)
job.success_signal.connect(self.on_sync_success, type=Qt.QueuedConnection)
job.failure_signal.connect(self.on_sync_failure, type=Qt.QueuedConnection)

self.api_job_queue.enqueue(job)
self.api_job_queue.enqueue(job)

logger.debug("In sync_api, after call to submit job to queue, on "
"thread {}".format(self.thread().currentThreadId()))
logger.debug("In sync_api, after call to submit job to queue, on "
"thread {}".format(self.thread().currentThreadId()))

def last_sync(self):
"""
Expand Down Expand Up @@ -497,15 +510,12 @@ def on_update_star_failure(self, result: UpdateStarJobException) -> None:
error = _('Failed to update star.')
self.gui.update_error_status(error)

@login_required
def update_star(self, source_db_object, callback):
"""
Star or unstar. The callback here is the API sync as we first make sure
that we apply the change to the server, and then update locally.
"""
if not self.api: # Then we should tell the user they need to login.
self.on_action_requiring_login()
return

job = UpdateStarJob(source_db_object.uuid, source_db_object.is_starred)
job.success_signal.connect(self.on_update_star_success, type=Qt.QueuedConnection)
job.success_signal.connect(callback, type=Qt.QueuedConnection)
Expand Down Expand Up @@ -542,6 +552,7 @@ def set_status(self, message, duration=5000):
"""
self.gui.update_activity_status(message, duration)

@login_required
def _submit_download_job(self,
object_type: Union[Type[db.Reply], Type[db.Message], Type[db.File]],
uuid: str) -> None:
Expand Down Expand Up @@ -695,6 +706,7 @@ def print_file(self, file_uuid: str) -> None:

self.export.begin_print.emit([file_location])

@login_required
def on_submission_download(
self,
submission_type: Union[Type[db.File], Type[db.Message]],
Expand All @@ -703,11 +715,8 @@ def on_submission_download(
"""
Download the file associated with the Submission (which may be a File or Message).
"""
if self.api:
self._submit_download_job(submission_type, submission_uuid)
self.set_status(_('Downloading file'))
else:
self.on_action_requiring_login()
self._submit_download_job(submission_type, submission_uuid)
self.set_status(_('Downloading file'))

def on_file_download_success(self, uuid: Any) -> None:
"""
Expand Down Expand Up @@ -747,6 +756,7 @@ def on_delete_source_failure(self, result: Exception) -> None:
error = _('Failed to delete source at server')
self.gui.update_error_status(error)

@login_required
def delete_source(self, source: db.Source):
"""
Performs a delete operation on source record.
Expand All @@ -756,16 +766,13 @@ def delete_source(self, source: db.Source):
synchronize the server records with the local state. If not,
the failure handler will display an error.
"""
if not self.api: # Then we should tell the user they need to login.
self.on_action_requiring_login()
return

job = DeleteSourceJob(source.uuid)
job.success_signal.connect(self.on_delete_source_success, type=Qt.QueuedConnection)
job.failure_signal.connect(self.on_delete_source_failure, type=Qt.QueuedConnection)

self.api_job_queue.enqueue(job)

@login_required
def send_reply(self, source_uuid: str, reply_uuid: str, message: str) -> None:
"""
Send a reply to a source.
Expand Down
5 changes: 5 additions & 0 deletions tests/test_logic.py
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,7 @@ def test_Controller_sync_api(homedir, config, mocker, session_maker):
co = Controller('http://localhost', mock_gui, session_maker, homedir)

co.authenticated = mocker.MagicMock(return_value=True)
co.api = 'this has a value'
co.api_job_queue = mocker.MagicMock()
co.api_job_queue.enqueue = mocker.MagicMock()

Expand Down Expand Up @@ -787,6 +788,7 @@ def test_Controller_on_file_download_Submission_no_auth(homedir, config, session
"""If the controller is not authenticated, do not enqueue a download job"""
mock_gui = mocker.MagicMock()
co = Controller('http://localhost', mock_gui, session_maker, homedir)
co.on_action_requiring_login = mocker.MagicMock()
co.api = None

mock_success_signal = mocker.MagicMock()
Expand All @@ -809,6 +811,7 @@ def test_Controller_on_file_download_Submission_no_auth(homedir, config, session
assert not mock_queue.enqueue.called
assert not mock_success_signal.connect.called
assert not mock_failure_signal.connect.called
assert co.on_action_requiring_login.called


def test_Controller_on_file_downloaded_success(homedir, config, mocker, session_maker):
Expand Down Expand Up @@ -1030,6 +1033,7 @@ def test_Controller_download_new_replies_with_new_reply(mocker, session, session
user-facing status message when a new reply is found.
"""
co = Controller('http://localhost', mocker.MagicMock(), session_maker, homedir)
co.api = 'Api token has a value'
reply = factory.Reply(source=factory.Source())
mocker.patch('securedrop_client.storage.find_new_replies', return_value=[reply])
success_signal = mocker.MagicMock()
Expand Down Expand Up @@ -1132,6 +1136,7 @@ def test_Controller_download_new_messages_with_new_message(mocker, session, sess
usre-facing status message when a new message is found.
"""
co = Controller('http://localhost', mocker.MagicMock(), session_maker, homedir)
co.api = 'Api token has a value'
message = factory.Message(source=factory.Source())
mocker.patch('securedrop_client.storage.find_new_messages', return_value=[message])
success_signal = mocker.MagicMock()
Expand Down

0 comments on commit 341f6ec

Please sign in to comment.