-
Notifications
You must be signed in to change notification settings - Fork 32
/
services.py
284 lines (229 loc) · 8.44 KB
/
services.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
import base64
import json
import boto3
import redis
import requests
from botocore.client import Config
from botocore.exceptions import NoCredentialsError, ClientError
from django.conf import settings
from django.core.files.base import ContentFile
from django.db import connection
from pydash import get
from core.settings import REDIS_HOST, REDIS_PORT, REDIS_DB
class S3:
"""
Configured from settings.EXPORT_SERVICE
"""
GET = 'get_object'
PUT = 'put_object'
@classmethod
def upload_file(
cls, key, file_path=None, headers=None, binary=False, metadata=None
): # pylint: disable=too-many-arguments
"""Uploads file object"""
read_directive = 'rb' if binary else 'r'
file_path = file_path if file_path else key
return cls._upload(key, open(file_path, read_directive).read(), headers, metadata)
@classmethod
def upload_base64( # pylint: disable=too-many-arguments,inconsistent-return-statements
cls, doc_base64, file_name, append_extension=True, public_read=False, headers=None
):
"""Uploads via base64 content with file name"""
_format = None
_doc_string = None
try:
_format, _doc_string = doc_base64.split(';base64,')
except: # pylint: disable=bare-except # pragma: no cover
pass
if not _format or not _doc_string: # pragma: no cover
return
if append_extension:
file_name_with_ext = file_name + "." + _format.split('/')[-1]
else:
if file_name and file_name.split('.')[-1].lower() not in [
'pdf', 'jpg', 'jpeg', 'bmp', 'gif', 'png'
]:
file_name += '.jpg'
file_name_with_ext = file_name
doc_data = ContentFile(base64.b64decode(_doc_string))
if public_read:
cls._upload_public(file_name_with_ext, doc_data)
else:
cls._upload(file_name_with_ext, doc_data, headers)
return file_name_with_ext
@classmethod
def url_for(cls, file_path):
return cls._generate_signed_url(cls.GET, file_path) if file_path else None
@classmethod
def public_url_for(cls, file_path):
url = f"http://{settings.AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com/{file_path}"
if settings.ENV != 'development':
url = url.replace('http://', 'https://')
return url
@classmethod
def exists(cls, key):
try:
cls.__resource().meta.client.head_object(Key=key, Bucket=settings.AWS_STORAGE_BUCKET_NAME)
except (ClientError, NoCredentialsError):
return False
return True
@classmethod
def delete_objects(cls, path): # pragma: no cover
try:
s3_resource = cls.__resource()
keys = cls.__fetch_keys(prefix=path)
if keys:
s3_resource.meta.client.delete_objects(
Bucket=settings.AWS_STORAGE_BUCKET_NAME, Delete=dict(Objects=keys)
)
except: # pylint: disable=bare-except
pass
@classmethod
def remove(cls, key):
try:
_conn = cls._conn()
return _conn.delete_object(
Bucket=settings.AWS_STORAGE_BUCKET_NAME,
Key=key
)
except NoCredentialsError: # pragma: no cover
pass
return None
@staticmethod
def _conn():
session = S3._session()
return session.client(
's3',
config=Config(region_name=settings.AWS_REGION_NAME, signature_version='s3v4')
)
@staticmethod
def _session():
return boto3.Session(
aws_access_key_id=settings.AWS_ACCESS_KEY_ID,
aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,
)
@classmethod
def _generate_signed_url(cls, accessor, key, metadata=None):
params = {
'Bucket': settings.AWS_STORAGE_BUCKET_NAME,
'Key': key,
**(metadata or {})
}
try:
_conn = cls._conn()
return _conn.generate_presigned_url(
accessor,
Params=params,
ExpiresIn=60*60*24*7, # a week
)
except NoCredentialsError: # pragma: no cover
pass
return None
@classmethod
def _upload(cls, file_path, file_content, headers=None, metadata=None):
"""Uploads via file content with file_path as path + name"""
url = cls._generate_signed_url(cls.PUT, file_path, metadata)
result = None
if url:
res = requests.put(
url, data=file_content, headers=headers
) if headers else requests.put(url, data=file_content)
result = res.status_code
return result
@classmethod
def _upload_public(cls, file_path, file_content):
try:
client = cls._conn()
return client.upload_fileobj(
file_content,
settings.AWS_STORAGE_BUCKET_NAME,
file_path,
ExtraArgs={'ACL': 'public-read'},
)
except NoCredentialsError: # pragma: no cover
pass
return None
@classmethod
def __fetch_keys(cls, prefix='/', delimiter='/'): # pragma: no cover
prefix = prefix[1:] if prefix.startswith(delimiter) else prefix
s3_resource = cls.__resource()
objects = s3_resource.meta.client.list_objects(Bucket=settings.AWS_STORAGE_BUCKET_NAME, Prefix=prefix)
return [{'Key': k} for k in [obj['Key'] for obj in objects.get('Contents', [])]]
@classmethod
def __resource(cls):
return cls._session().resource('s3')
class RedisService: # pragma: no cover
def __init__(self):
self.conn = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB)
def set(self, key, val):
return self.conn.set(key, val)
def set_json(self, key, val):
return self.conn.set(key, json.dumps(val))
def get_formatted(self, key):
val = self.get(key)
if isinstance(val, bytes):
val = val.decode()
try:
val = json.loads(val)
except: # pylint: disable=bare-except
pass
return val
def exists(self, key):
return self.conn.exists(key)
def get(self, key):
return self.conn.get(key)
def keys(self, pattern):
return self.conn.keys(pattern)
def get_int(self, key):
return int(self.conn.get(key).decode('utf-8'))
class PostgresQL:
@staticmethod
def create_seq(seq_name, owned_by, min_value=0, start=1):
with connection.cursor() as cursor:
cursor.execute(
f"CREATE SEQUENCE IF NOT EXISTS {seq_name} MINVALUE {min_value} START {start} OWNED BY {owned_by};")
@staticmethod
def update_seq(seq_name, start):
with connection.cursor() as cursor:
cursor.execute(f"SELECT setval('{seq_name}', {start}, true);")
@staticmethod
def drop_seq(seq_name):
with connection.cursor() as cursor:
cursor.execute(f"DROP SEQUENCE IF EXISTS {seq_name};")
@staticmethod
def next_value(seq_name):
with connection.cursor() as cursor:
cursor.execute(f"SELECT nextval('{seq_name}');")
return cursor.fetchone()[0]
@staticmethod
def last_value(seq_name):
with connection.cursor() as cursor:
cursor.execute(f"SELECT last_value from {seq_name};")
return cursor.fetchone()[0]
class AbstractAuthService:
def __init__(self, username, password=None, user=None):
self.username = username
self.password = password
self.user = user
if self.username and not self.user:
self.set_user()
def set_user(self):
from core.users.models import UserProfile
self.user = UserProfile.objects.filter(username=self.username).first()
def get_token(self):
pass
class DjangoAuthService(AbstractAuthService):
def get_token(self, check_password=True):
if check_password:
if not self.user.check_password(self.password):
return False
return self.user.get_token()
class OIDCAuthService(AbstractAuthService):
def get_token(self):
return self.user.get_oidc_token(self.password)
class AuthService:
@staticmethod
def get(**kwargs):
if get(settings, 'OIDC_SERVER_URL'):
return OIDCAuthService(**kwargs)
return DjangoAuthService(**kwargs)