summaryrefslogtreecommitdiffstats
path: root/testapi/opnfv_testapi/common/check.py
blob: 18dc67de4b4499a8ca0f5766f4df8e27aa899223 (plain)
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
##############################################################################
# Copyright (c) 2017 ZTE Corp
# feng.xiaowei@zte.com.cn
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0
##############################################################################
import functools
import re

from tornado import gen

from opnfv_testapi.common import constants
from opnfv_testapi.common import message
from opnfv_testapi.common import raises
from opnfv_testapi.common.config import CONF
from opnfv_testapi.db import api as dbapi


def is_authorized(method):
    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        resources = ['pods', 'projects', 'testcases', 'scenarios']
        if CONF.api_authenticate and self.table in resources:
            testapi_id = self.get_secure_cookie(constants.TESTAPI_ID)
            if not testapi_id:
                raises.Unauthorized(message.not_login())
            user_info = yield dbapi.db_find_one('users', {'user': testapi_id})
            if not user_info:
                raises.Unauthorized(message.not_lfid())
            if method.__name__ == "_create":
                kwargs['creator'] = testapi_id
            if self.table in ['projects']:
                query = kwargs.get('query')
                if type(query) is not dict:
                    query_data = query()
                else:
                    if self.json_args is None or 'name' not in self.json_args:
                        query_data = query
                    else:
                        query_data = self.json_args
                group = "opnfv-gerrit-" + query_data['name'] + "-submitters"
                if group not in user_info['groups']:
                    raises.Unauthorized(message.no_permission())
        ret = yield gen.coroutine(method)(self, *args, **kwargs)
        raise gen.Return(ret)
    return wrapper


def is_reource_tied(method):
    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        query_data = {}
        tied_maps = {
            'projects': ('testcases', 'project_name'),
            'pods': ('results', 'pod_name'),
            'testcases': ('results', 'case_name')
        }
        if self.table in tied_maps:
            if method.__name__ == '_update':
                if 'name' not in self.json_args:
                    ret = yield gen.coroutine(method)(self, *args, **kwargs)
                    raise gen.Return(ret)
            query_data[tied_maps[self.table][1]] = kwargs.get('query')['name']
            data = yield dbapi.db_find_one(tied_maps[self.table][0],
                                           query_data)
            if data:
                raises.Unauthorized(message.tied_with_resource())
        ret = yield gen.coroutine(method)(self, *args, **kwargs)
        raise gen.Return(ret)
    return wrapper


def valid_token(method):
    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        if self.auth and self.table == 'results':
            try:
                token = self.request.headers['X-Auth-Token']
            except KeyError:
                raises.Unauthorized(message.unauthorized())
            query = {'access_token': token}
            check = yield dbapi.db_find_one('tokens', query)
            if not check:
                raises.Forbidden(message.invalid_token())
        ret = yield gen.coroutine(method)(self, *args, **kwargs)
        raise gen.Return(ret)
    return wrapper


def not_exist(xstep):
    @functools.wraps(xstep)
    def wrap(self, *args, **kwargs):
        query = kwargs.get('query')
        data = yield dbapi.db_find_one(self.table, query)
        if not data:
            raises.NotFound(message.not_found(self.table, query))
        ret = yield gen.coroutine(xstep)(self, data, *args, **kwargs)
        raise gen.Return(ret)

    return wrap


def no_body(xstep):
    @functools.wraps(xstep)
    def wrap(self, *args, **kwargs):
        if self.json_args is None:
            raises.BadRequest(message.no_body())
        ret = yield gen.coroutine(xstep)(self, *args, **kwargs)
        raise gen.Return(ret)

    return wrap


def miss_fields(xstep):
    @functools.wraps(xstep)
    def wrap(self, *args, **kwargs):
        fields = kwargs.pop('miss_fields', [])
        if fields:
            for miss in fields:
                miss_data = self.json_args.get(miss)
                if miss_data is None or miss_data == '':
                    raises.BadRequest(message.missing(miss))
        ret = yield gen.coroutine(xstep)(self, *args, **kwargs)
        raise gen.Return(ret)
    return wrap


def carriers_exist(xstep):
    @functools.wraps(xstep)
    def wrap(self, *args, **kwargs):
        carriers = kwargs.pop('carriers', {})
        if carriers:
            for table, query in carriers:
                exist = yield dbapi.db_find_one(table, query())
                if not exist:
                    raises.Forbidden(message.not_found(table, query()))
        ret = yield gen.coroutine(xstep)(self, *args, **kwargs)
        raise gen.Return(ret)
    return wrap


def values_check(xstep):
    @functools.wraps(xstep)
    def wrap(self, *args, **kwargs):
        checks = kwargs.pop('values_check', {})
        if checks:
            for field, check, options in checks:
                if not check(field, options):
                    raises.BadRequest(message.invalid_value(field, options))
        ret = yield gen.coroutine(xstep)(self, *args, **kwargs)
        raise gen.Return(ret)
    return wrap


def new_not_exists(xstep):
    @functools.wraps(xstep)
    def wrap(self, *args, **kwargs):
        query = kwargs.get('query')
        if query:
            query_data = query()
            if self.table == 'pods':
                if query_data.get('name'):
                    query_data['name'] = re.compile(
                        '\\b{}\\b'.format(query_data.get('name')),
                        re.IGNORECASE)
            to_data = yield dbapi.db_find_one(self.table, query_data)
            if to_data:
                raises.Forbidden(message.exist(self.table, query()))
        ret = yield gen.coroutine(xstep)(self, *args, **kwargs)
        raise gen.Return(ret)
    return wrap


def updated_one_not_exist(xstep):
    @functools.wraps(xstep)
    def wrap(self, data, *args, **kwargs):
        db_keys = kwargs.pop('db_keys', [])
        query = self._update_query(db_keys, data)
        if query:
            to_data = yield dbapi.db_find_one(self.table, query)
            if to_data:
                raises.Forbidden(message.exist(self.table, query))
        ret = yield gen.coroutine(xstep)(self, data, *args, **kwargs)
        raise gen.Return(ret)
    return wrap


def query_by_name(xstep):
    @functools.wraps(xstep)
    def wrap(self, *args, **kwargs):
        if 'name' in self.request.query_arguments.keys():
            query = kwargs.get('query', {})
            query.update({
                'name': re.compile(self.get_query_argument('name'),
                                   re.IGNORECASE)})
            kwargs.update({'query': query})

        ret = yield gen.coroutine(xstep)(self, *args, **kwargs)
        raise gen.Return(ret)

    return wrap