admin_auth_controller.py 2.18 KB
Newer Older
David Mendez's avatar
David Mendez committed
1
2
3
4
"""
Module that describes and handles the requests concerned with performing admin tasks
"""
from flask import request, make_response, jsonify
David Mendez's avatar
David Mendez committed
5
from flask_restx import Namespace, Resource, fields
David Mendez's avatar
David Mendez committed
6

7
from app.authorisation import token_generator
8
from app.authorisation.decorators import admin_token_required
9
10
11
from app.config import RUN_CONFIG
from app.config import verify_secret
from app.models import delayed_job_models
12

13
14
15
16
17
API = Namespace('admin', description='Request to login and get a token for the admin user')

OPERATION_RESULT = API.model('OperationResult', {
    'result': fields.String(description='The result of the admin operation.'),
})
18
19


David Mendez's avatar
David Mendez committed
20
# pylint: disable=no-self-use,broad-except
21
22
23
@API.route('/login')
class AdminLogin(Resource):
    """
24
        Resource that handles admin login requests.
25
26
27
28
29
30
31
    """
    def get(self):
        """
            If the login and password are correct, returns a token authorising the admin
            :return: a Json Web Token authorising the admin user
        """
        auth = request.authorization
32
33
34
35
36
        if auth is not None:

            if auth.username == RUN_CONFIG.get('admin_username') and verify_secret('admin_password', auth.password):
                admin_token = token_generator.generate_admin_token()
                return jsonify({'token': admin_token})
37
38

        return make_response('Could not verify username and password', 401,
39
                             {'WWW-Authenticate': 'Basic realm="Login Required'})
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63


@API.route('/delete_expired')
class DeleteExpired(Resource):
    """
       Resource that triggers the deletion of the expired jobs. Admin token is required.
    """

    @API.marshal_with(OPERATION_RESULT)
    @API.doc(security='adminKey')
    @admin_token_required
    def get(self):
        """
        Deletes the expired jobs in the system.
        :return: a summary of the result of the operation
        """

        try:

            num_deleted = delayed_job_models.delete_all_expired_jobs()
            return {
                'result': f'Successfully deleted {num_deleted} expired jobs.'
            }

David Mendez's avatar
David Mendez committed
64
        except Exception as exception:
65
66

            return {
David Mendez's avatar
David Mendez committed
67
                'result': f'There was an error: {str(exception)}'
68
            }