auth.py 6.59 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# Copyright 2018 Markus Scheidgen
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an"AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Endpoints can use *flask_httpauth* based authentication either with basic HTTP
authentication or access tokens. Currently the authentication is validated against
users and sessions in the NOMAD-coe repository postgres db.

.. autodata:: base_path

There are two authentication "schemes" to authenticate users. First we use
HTTP Basic Authentication (username, password), which also works with username=token,
password=''. Second, there is a curstom HTTP header 'X-Token' that can be used to
give a token. The first precedes the second. The used tokens are given and stored
by the NOMAD-coe repository GUI.

Authenticated user information is available via FLASK's build in flask.g.user object.
It is set to None, if no user information is available.

There are two decorators for FLASK API endpoints that can be used if endpoints require
authenticated user information for authorization or otherwise.

.. autofunction:: login_if_available
.. autofunction:: login_really_required
"""

38
39
from flask import g, request
from flask_restplus import abort, Resource, fields
40
41
from flask_httpauth import HTTPBasicAuth

42
from nomad import config, processing, files, utils, coe_repo
43
from nomad.coe_repo import User, LoginException
44

45
from .app import app, api
46
47
48
49
50

app.config['SECRET_KEY'] = config.services.api_secret
auth = HTTPBasicAuth()


51
52
53
54
55
56
57
58
59
60
61
62
63
# Authentication scheme definitions, for swagger only.
api.authorizations = {
    'HTTP Basic': {
        'type': 'basic'
    },
    'X-Token': {
        'type': 'apiKey',
        'in': 'header',
        'name': 'X-Token'
    }
}


64
65
@auth.verify_password
def verify_password(username_or_token, password):
66
67
68
69
70
71
72
73
    if username_or_token is None or username_or_token == '':
        g.user = None
        return True

    if password is None or password == '':
        g.user = User.verify_auth_token(username_or_token)
        return g.user is not None
    else:
74
75
        try:
            g.user = User.verify_user_password(username_or_token, password)
76
77
        except Exception as e:
            utils.get_logger(__name__).error('could not verify password', exc_info=e)
78
79
            return False

80
        return g.user is not None
81

82
83
84
85

@auth.error_handler
def auth_error_handler():
    abort(401, 'Could not authenticate user, bad credentials')
86
87
88
89
90
91
92


def login_if_available(func):
    """
    A decorator for API endpoint implementations that might authenticate users, but
    provide limited functionality even without users.
    """
93
94
    @api.response(401, 'Not authorized, some data require authentication and authorization')
    @api.doc(security=list(api.authorizations.keys()))
95
96
97
98
99
100
101
102
    @auth.login_required
    def wrapper(*args, **kwargs):
        # TODO the cutom X-Token based authentication should be replaced by a real
        # Authentication header based token authentication
        if not g.user and 'X-Token' in request.headers:
            token = request.headers['X-Token']
            g.user = User.verify_auth_token(token)
            if not g.user:
103
                abort(401, message='Not authorized, some data require authentication and authorization')
104
105
106
107
108
109
110
111
112
113
114
115
116

        return func(*args, **kwargs)

    wrapper.__name__ = func.__name__
    wrapper.__doc__ = func.__doc__
    return wrapper


def login_really_required(func):
    """
    A decorator for API endpoint implementations that forces user authentication on
    endpoints.
    """
117
118
    @api.response(401, 'Authentication required or not authorized to access requested data')
    @api.doc(security=list(api.authorizations.keys()))
119
120
121
    @login_if_available
    def wrapper(*args, **kwargs):
        if g.user is None:
122
            abort(401, message='Authentication required or not authorized to access requested data')
123
124
125
126
127
128
129
        else:
            return func(*args, **kwargs)
    wrapper.__name__ = func.__name__
    wrapper.__doc__ = func.__doc__
    return wrapper


130
ns = api.namespace(
131
132
    'auth',
    description='Authentication related endpoints.')
133
134


135
136
137
138
139
140
141
142
143
144
145
146
user_model = api.model('User', {
    'first_name': fields.String(description='The user\'s first name'),
    'last_name': fields.String(description='The user\'s last name'),
    'email': fields.String(description='Guess what, the user\'s email'),
    'affiliation': fields.String(description='The user\'s affiliation'),
    'token': fields.String(
        description='The access token that authenticates the user with the API. '
        'User the HTTP header "X-Token" to provide it in API requests.')
})


@ns.route('/user')
147
class TokenResource(Resource):
148
149
    @api.doc('get_user')
    @api.marshal_with(user_model, skip_none=True, code=200, description='User data send')
150
151
152
153
154
155
156
157
158
159
    @login_really_required
    def get(self):
        """
        Get the access token for the authenticated user.

        You can use basic authentication to access this endpoint and receive a
        token for further api access. This token will expire at some point and presents
        a more secure method of authentication.
        """
        try:
160
            return g.user
161
162
163
        except LoginException:
            abort(
                401,
164
                message='User not logged in, provide credentials via Basic HTTP authentication.')
165
166


167
def create_authorization_predicate(upload_id, calc_id=None):
168
169
170
171
172
173
174
175
176
177
    """
    Returns a predicate that determines if the logged in user has the authorization
    to access the given upload and calculation.
    """
    def func():
        if g.user is None:
            # guest users don't have authorized access to anything
            return False

        # look in repository
178
        upload = coe_repo.Upload.from_upload_id(upload_id)
179
180
181
182
        if upload is not None:
            return upload.user_id == g.user.user_id

        # look in staging
183
        staging_upload = processing.Upload.get(upload_id)
184
185
186
187
        if staging_upload is not None:
            return str(g.user.user_id) == str(staging_upload.user_id)

        # There are no db entries for the given resource
188
        if files.UploadFiles.get(upload_id) is not None:
189
            logger = utils.get_logger(__name__, upload_id=upload_id, calc_id=calc_id)
190
191
192
193
            logger.error('Upload files without respective db entry')

        raise KeyError
    return func