auth.py 11.7 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
# 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.

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
"""

36
37
from flask import g, request
from flask_restplus import abort, Resource, fields
38
from flask_httpauth import HTTPBasicAuth
39
from datetime import datetime
40

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

44
from .app import app, api, RFC3339DateTime
45
46
47
48
49

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


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


63
64
@auth.verify_password
def verify_password(username_or_token, password):
65
66
67
68
69
70
71
72
    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:
73
74
        try:
            g.user = User.verify_user_password(username_or_token, password)
75
76
        except LoginException:
            return False
77
78
        except Exception as e:
            utils.get_logger(__name__).error('could not verify password', exc_info=e)
79
80
            return False

81
        return g.user is not None
82

83
84
85
86

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


def login_if_available(func):
    """
    A decorator for API endpoint implementations that might authenticate users, but
    provide limited functionality even without users.
    """
94
95
    @api.response(401, 'Not authorized, some data require authentication and authorization')
    @api.doc(security=list(api.authorizations.keys()))
96
97
98
99
100
101
102
103
    @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:
104
                abort(401, message='Not authorized, some data require authentication and authorization')
105
106
107
108
109
110
111
112
113
114
115
116
117

        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.
    """
118
119
    @api.response(401, 'Authentication required or not authorized to access requested data')
    @api.doc(security=list(api.authorizations.keys()))
120
121
122
    @login_if_available
    def wrapper(*args, **kwargs):
        if g.user is None:
123
            abort(401, message='Authentication required or not authorized to access requested data')
124
125
126
127
128
129
130
        else:
            return func(*args, **kwargs)
    wrapper.__name__ = func.__name__
    wrapper.__doc__ = func.__doc__
    return wrapper


131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
def admin_login_required(func):
    """
    A decorator for API endpoint implementations that should only work for the admin user.
    """
    @api.response(401, 'Authentication required or not authorized as admin user. Only admin can access this endpoint.')
    @api.doc(security=list(api.authorizations.keys()))
    @login_really_required
    def wrapper(*args, **kwargs):
        if not g.user.is_admin:
            abort(401, message='Only the admin user can perform reset.')
        else:
            return func(*args, **kwargs)

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


149
ns = api.namespace(
150
151
    'auth',
    description='Authentication related endpoints.')
152
153


154
user_model = api.model('User', {
155
    'user_id': fields.Integer(description='The id to use in the repo db, make sure it does not already exist.'),
156
157
158
    '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'),
159
160
161
    'affiliation': fields.Nested(model=api.model('Affiliation', {
        'name': fields.String(description='The name of the affiliation', default='not given'),
        'address': fields.String(description='The address of the affiliation', default='not given')})),
162
    'password': fields.String(description='The bcrypt 2y-indented password for initial and changed password'),
163
164
    'token': fields.String(
        description='The access token that authenticates the user with the API. '
165
        'User the HTTP header "X-Token" to provide it in API requests.'),
166
    'created': RFC3339DateTime(description='The create date for the user.')
167
168
169
170
})


@ns.route('/user')
171
class UserResource(Resource):
172
173
    @api.doc('get_user')
    @api.marshal_with(user_model, skip_none=True, code=200, description='User data send')
174
175
176
    @login_really_required
    def get(self):
        """
177
        Get user information including a long term access token for the authenticated user.
178
179
180
181
182
183

        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:
184
            return g.user
185
186
187
        except LoginException:
            abort(
                401,
188
                message='User not logged in, provide credentials via Basic HTTP authentication.')
189

190
191
    @api.doc('create_user')
    @api.expect(user_model)
192
    @api.response(400, 'Invalid user data')
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
    @api.marshal_with(user_model, skip_none=True, code=200, description='User created')
    @login_really_required
    def put(self):
        """
        Creates a new user account. Currently only the admin user is allows. The
        NOMAD-CoE repository GUI should be used to create user accounts for now.
        Passwords have to be encrypted by the client with bcrypt and 2y indent.
        """
        if not g.user.is_admin:
            abort(401, message='Only the admin user can perform create user.')

        data = request.get_json()
        if data is None:
            data = {}

        for required_key in ['last_name', 'first_name', 'password', 'email']:
            if required_key not in data:
                abort(400, message='The %s is missing' % required_key)

212
213
214
215
        if 'user_id' in data:
            if coe_repo.User.from_user_id(data['user_id']) is not None:
                abort(400, 'User with given user_id %d already exists.' % data['user_id'])

216
217
218
        user = coe_repo.User.create_user(
            email=data['email'], password=data.get('password', None), crypted=True,
            first_name=data['first_name'], last_name=data['last_name'],
219
            created=data.get('created', datetime.now()),
220
221
            affiliation=data.get('affiliation', None), token=data.get('token', None),
            user_id=data.get('user_id', None))
222
223
224
225
226

        return user, 200

    @api.doc('update_user')
    @api.expect(user_model)
227
    @api.response(400, 'Invalid user data')
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
    @api.marshal_with(user_model, skip_none=True, code=200, description='User updated')
    @login_really_required
    def post(self):
        """
        Allows to edit the authenticated user and change his password. Password
        have to be encrypted by the client with bcrypt and 2y indent.
        """
        data = request.get_json()
        if data is None:
            data = {}

        if 'email' in data:
            abort(400, message='Cannot change the users email.')

        g.user.update(crypted=True, **data)

        return g.user, 200

246

247
248
249
token_model = api.model('Token', {
    'user': fields.Nested(user_model),
    'token': fields.String(description='The short term token to sign URLs'),
250
    'expiries_at': RFC3339DateTime(desription='The time when the token expires')
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
})


signature_token_argument = dict(
    name='token', type=str, help='Token that signs the URL and authenticates the user',
    location='args')


@ns.route('/token')
class TokenResource(Resource):
    @api.doc('get_token')
    @api.marshal_with(token_model, skip_none=True, code=200, description='Token send')
    @login_really_required
    def get(self):
        """
        Generates a short (10s) term JWT token that can be used to authenticate the user in
        URLs towards most API get request, e.g. for file downloads on the
        raw or archive api endpoints. Use the token query parameter to sign URLs.
        """
        token, expires_at = g.user.get_signature_token()
        return {
            'user': g.user,
            'token': token,
            'expires_at': expires_at.isoformat()
        }


def with_signature_token(func):
    """
    A decorator for API endpoint implementations that validates signed URLs.
    """
    @api.response(401, 'Invalid or expired signature token')
    def wrapper(*args, **kwargs):
        token = request.args.get('token', None)
        if token is not None:
            try:
                g.user = coe_repo.User.verify_signature_token(token)
            except LoginException:
                abort(401, 'Invalid or expired signature token')

        return func(*args, **kwargs)
    wrapper.__name__ = func.__name__
    wrapper.__doc__ = func.__doc__
    return wrapper


297
def create_authorization_predicate(upload_id, calc_id=None):
298
299
300
301
302
303
304
305
    """
    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
306
307
308
        elif g.user.user_id == 0:
            # the admin user does have authorization to access everything
            return True
309
310

        # look in repository
311
        upload = coe_repo.Upload.from_upload_id(upload_id)
312
313
314
315
        if upload is not None:
            return upload.user_id == g.user.user_id

        # look in staging
316
        staging_upload = processing.Upload.get(upload_id)
317
318
319
320
        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
321
        if files.UploadFiles.get(upload_id) is not None:
322
            logger = utils.get_logger(__name__, upload_id=upload_id, calc_id=calc_id)
323
324
325
326
            logger.error('Upload files without respective db entry')

        raise KeyError
    return func