auth.py 6.44 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
66
67
68
69
70
71
@auth.verify_password
def verify_password(username_or_token, password):
    # first try to authenticate by token
    g.user = User.verify_auth_token(username_or_token)
    if not g.user:
        # try to authenticate with username/password
        try:
            g.user = User.verify_user_password(username_or_token, password)
72
73
        except Exception as e:
            utils.get_logger(__name__).error('could not verify password', exc_info=e)
74
75
76
77
78
79
80
81
82
83
84
85
86
            return False

    if not g.user:
        return True  # anonymous access

    return True


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

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


124
ns = api.namespace(
125
126
    'auth',
    description='Authentication related endpoints.')
127
128


129
130
131
132
133
134
135
136
137
138
139
140
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')
141
class TokenResource(Resource):
142
143
    @api.doc('get_user')
    @api.marshal_with(user_model, skip_none=True, code=200, description='User data send')
144
145
146
147
148
149
150
151
152
153
    @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:
154
            return g.user
155
156
157
        except LoginException:
            abort(
                401,
158
                message='User not logged in, provide credentials via Basic HTTP authentication.')
159
160


161
def create_authorization_predicate(upload_id, calc_id=None):
162
163
164
165
166
167
168
169
170
171
    """
    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
172
        upload = coe_repo.Upload.from_upload_id(upload_id)
173
174
175
176
        if upload is not None:
            return upload.user_id == g.user.user_id

        # look in staging
177
        staging_upload = processing.Upload.get(upload_id)
178
179
180
181
        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
182
        if files.UploadFiles.get(upload_id) is not None:
183
            logger = utils.get_logger(__name__, upload_id=upload_id, calc_id=calc_id)
184
185
186
187
            logger.error('Upload files without respective db entry')

        raise KeyError
    return func