forked from conwetlab/wstore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
views.py
284 lines (210 loc) · 9.37 KB
/
views.py
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
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
# -*- coding: utf-8 -*-
# Copyright (c) 2013 CoNWeT Lab., Universidad Politécnica de Madrid
# This file is part of WStore.
# WStore is free software: you can redistribute it and/or modify
# it under the terms of the European Union Public Licence (EUPL)
# as published by the European Commission, either version 1.1
# of the License, or (at your option) any later version.
# WStore is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# European Union Public Licence for more details.
# You should have received a copy of the European Union Public Licence
# along with WStore.
# If not, see <https://joinup.ec.europa.eu/software/page/eupl/licence-eupl>.
import json
from django.http import HttpResponse
from wstore.admin.searchers import ResourceBrowser
from wstore.store_commons.utils.http import build_response, supported_request_mime_types, \
authentication_required
from wstore.store_commons.resource import Resource
from wstore.store_commons.utils.name import is_valid_id
from wstore.models import Context
from wstore.charging_engine.models import Unit
def is_hidden_credit_card(number, profile_card):
hidden = False
if number.startswith('xxxxxxxxxxxx'):
if number[12:] == profile_card[12:]:
hidden = True
return hidden
def is_valid_credit_card(number):
valid = True
digits = '1234567890'
if len(number) != 16:
valid = False
for d in number:
if not d in digits:
valid = False
return valid
class ResourceSearch(Resource):
@authentication_required
def read(self, request):
# Get data contained in query string
querytext = request.GET.get('q', '')
indexname = request.GET.get('namespace', '')
# if indexname is empty, builds error response
if indexname is '':
return build_response(request, 400, 'The "namespace" field is required.')
# if indexname does not exist, builds error response
if not ResourceBrowser.is_stored(indexname):
return build_response(request, 400, 'The "namespace" field does not exist.')
# Search for stored resources
response = ResourceBrowser.search(indexname, querytext)
return HttpResponse(json.dumps(response), content_type='application/json')
class UnitCollection(Resource):
@authentication_required
def read(self, request):
response = []
for unit in Unit.objects.all():
u = {
'name': unit.name,
'defined_model': unit.defined_model
}
if unit.defined_model == 'subscription':
u['renovation_period'] = unit.renovation_period
response.append(u)
return HttpResponse(json.dumps(response), status=200, mimetype='application/json;charset=UTF-8')
@authentication_required
@supported_request_mime_types(('application/json',))
def create(self, request):
# The that the user is an admin
if not request.user.is_staff:
return build_response(request, 403, 'Forbidden')
try:
unit_data = json.loads(request.raw_post_data)
except:
return build_response(request, 400, 'Invalid JSON content')
# Check the content of the request
if not 'name' in unit_data or not 'defined_model' in unit_data:
return build_response(request, 400, 'Missing required field')
# Check that the new unit does not exist
u = Unit.objects.filter(name=unit_data['name'])
if len(u) > 0:
return build_response(request, 400, 'The unit already exists')
# Check the pricing model defined
if unit_data['defined_model'].lower() != 'single payment' and \
unit_data['defined_model'].lower() != 'subscription' and \
unit_data['defined_model'].lower() != 'pay per use':
return build_response(request, 400, 'Invalid pricing model')
# Check the renovation period
if unit_data['defined_model'].lower() == 'subscription' and \
not 'renovation_period' in unit_data:
return build_response(request, 400, 'Missing renovation period')
# Create the unit
if 'renovation_period' in unit_data:
Unit.objects.create(
name=unit_data['name'],
defined_model=unit_data['defined_model'].lower(),
renovation_period=unit_data['renovation_period'])
else:
Unit.objects.create(
name=unit_data['name'],
defined_model=unit_data['defined_model'].lower())
return build_response(request, 201, 'Created')
class CurrencyCollection(Resource):
@authentication_required
def read(self, request):
# Check if the user is an admin
if not request.user.is_staff:
return build_response(request, 403, 'Forbidden')
# Get Store context
context = Context.objects.all()[0]
# Return currencies
if 'allowed' in context.allowed_currencies:
currs = [{
'currency': curr['currency'],
'default': curr['currency'].lower() == context.allowed_currencies['default'].lower()
} for curr in context.allowed_currencies['allowed']]
else:
currs = []
response = json.dumps(currs)
return HttpResponse(response, status=200, mimetype='application/json; charset=utf-8')
@authentication_required
@supported_request_mime_types(('application/json',))
def create(self, request):
# Check if the user is an admin
if not request.user.is_staff:
return build_response(request, 403, 'Forbidden')
# Get data
data = json.loads(request.raw_post_data)
if not 'currency' in data:
return build_response(request, 400, 'Invalid JSON content')
# Check currency regex
if not is_valid_id(data['currency']):
return build_response(request, 400, 'Invalid currency format')
# Get the context
context = Context.objects.all()[0]
# Check if the allowed_currencies list is empty
first = False
if not 'allowed' in context.allowed_currencies:
first = True
context.allowed_currencies['allowed'] = []
error = False
# Check that the new currency is not already included
for curr in context.allowed_currencies['allowed']:
if curr['currency'].lower() == data['currency'].lower():
error = True
break
if error:
return build_response(request, 400, 'The currency already exists')
# Check if it is the default currency
if ('default' in data and data['default']) or first:
# Note the this will override previous default currency
context.allowed_currencies['default'] = data['currency']
# Include new currency
context.allowed_currencies['allowed'].append({
'currency': data['currency'],
'in_use': False
})
context.save()
return build_response(request, 201, 'Created')
class CurrencyEntry(Resource):
@authentication_required
def update(self, request, currency):
"""
This method is used to change the default currency
"""
if not request.user.is_staff:
build_response(request, 403, 'Forbidden')
# Get the context
context = Context.objects.all()[0]
# Check that the currency exist
if not 'default' in context.allowed_currencies:
return build_response(request, 404, 'Not found')
if not currency.lower() == context.allowed_currencies['default'].lower():
for c in context.allowed_currencies['allowed']:
if c['currency'].lower() == currency.lower():
break
else:
return build_response(request, 404, 'Not found')
# Make the currency the default currency
context.allowed_currencies['default'] = currency
context.save()
# Return response
return build_response(request, 200, 'OK')
@authentication_required
def delete(self, request, currency):
# Check if the user is an admin
if not request.user.is_staff:
return build_response(request, 403, 'Forbidden')
# Get the context
context = Context.objects.all()[0]
if not 'allowed' in context.allowed_currencies:
return build_response(request, 404, 'Not found')
del_curr = None
# Search the currency
for curr in context.allowed_currencies['allowed']:
if curr['currency'].lower() == currency.lower():
del_curr = curr
break
else:
return build_response(request, 404, 'Not found')
# Check if is possible to delete the currency
if context.allowed_currencies['default'].lower() == currency.lower():
return build_response(request, 403, 'The currency cannot be deleted: It is the default currency')
if del_curr['in_use']:
return build_response(request, 403, 'The currency cannot be deleted: An offering is using it')
# Remove the currency
context.allowed_currencies['allowed'].remove(del_curr)
context.save()
return build_response(request, 204, 'No content')