-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
348 lines (275 loc) · 10.8 KB
/
main.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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
from fastapi import FastAPI, Request, status, HTTPException, Depends
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from tortoise import BaseDBAsyncClient
from tortoise.signals import post_save
from tortoise.contrib.fastapi import register_tortoise
from authentication import *
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from fastapi import File, UploadFile
from fastapi.staticfiles import StaticFiles
from PIL import Image
from models import *
from typing import List, Optional, Type
from emails import send_register_email
import secrets
import uvicorn
app = FastAPI()
oauth2_schema = OAuth2PasswordBearer(tokenUrl='token')
templtes = Jinja2Templates(directory='templates')
app.mount('/static', StaticFiles(directory='static'), name='static')
@app.post('/token')
async def generate_token(request_form: OAuth2PasswordRequestForm = Depends()):
token = await token_generator(request_form.username, request_form.password)
return {'access_token':token, 'token_type':'bearer'}
async def get_current_user(token: str = Depends(oauth2_schema)):
try :
payload = jwt.decode(token, config_credential['SECRET'], algorithms='HS256')
user = await User.get(id = payload.get('id'))
print(user, type(user), user.__dict__)
except :
raise HTTPException(
status_code= status.HTTP_401_UNAUTHORIZED,
detail = 'Invalid username or password',
headers = {'WWW-Authenticate':'Bearer'}
)
return await user
@app.post('/user/me')
async def user_login(user: user_pydanticIn = Depends(get_current_user)):
business = await Business.get(owner = user)
logo = business.logo
print(logo, type(logo))
logo_path = 'localhost:8000/static/images/'+logo
return {
'status': 'ok',
'data': {
'username': user.username,
'email': user.email,
'verified': user.is_verified,
'joined_date': user.join_date.strftime('%b %d %Y'),
'logo': logo_path
}
}
@post_save(User)
async def create_business(
sender: 'Type[User]',
instance: User,
created: bool,
using_db: 'Optional[BaseDBAsyncClient]',
update_fileds: List[str]
) -> None :
if created:
business_obj = await Business.create(
business_name = instance.username, owner = instance
)
await business_pydantic.from_tortoise_orm(business_obj)
# print(instance, type(isinstance), instance.__dict__)
await send_register_email([instance.email], instance)
@app.get('/verification', response_class=HTMLResponse)
async def email_verification(request: Request, token: str):
user = await verify_token(token)
if user and not user.is_verified :
user.is_verified = True
await user.save()
return templtes.TemplateResponse('verification.html',
{"request": request,
"username": user.username})
raise HTTPException(
status_code = status.HTTP_404_NOT_FOUND,
detail='Invalid token or expired token',
headers={'WWW-Authenticate': 'Bearer'}
)
@app.post('/registration')
async def user_registrations(user: user_pydanticIn):
user_info = user.dict(exclude_unset=True)
user_info['password'] = get_hashed_password(user_info['password'])
user_obj = await User.create(**user_info)
new_user = await user_pydantic.from_tortoise_orm(user_obj)
return {
'status': 'ok',
'data': f'Hello {new_user.username}, thanks for choosing our services Please check your email inbox and click on the link to confirm your eamil'
}
@app.get('/')
def index():
return {'Message': "Hello world"}
@app.post('/uploadfile/profile', tags=['Upload File'])
async def create_upload_file(file: UploadFile = File(...),
user: user_pydantic = Depends(get_current_user)):
FILEPATH = './static/images/'
filename = file.filename
extension = filename.split('.')[1]
if extension not in ['png', 'jpg'] :
return {
'status': 'error',
'detail': 'File extenstion not allowed',
}
token_name = secrets.token_hex(10)+ '.' + extension
generate_name = FILEPATH + token_name
file_content = await file.read()
with open(generate_name, 'wb') as file :
file.write(file_content)
img = Image.open(generate_name)
img = img.resize(size = (200, 200))
img.save(generate_name)
file.close()
business = await Business.get(owner = user)
owner = await business.owner
if owner == user:
business.logo = token_name
await business.save()
raise HTTPException(
status_code = status.HTTP_401_UNAUTHORIZED,
detail='Not authenticated to perform this action',
headers={'WWW-Authenticate': 'Bearer'}
)
@app.post('/uploadfile/product/{id}', tags=['Upload File'])
async def create_upload_file(id: int, file: UploadFile = File(...),
user : user_pydantic = Depends(get_current_user)):
FILEPATH = './static/images'
filename = file.filename
extension = filename.split('.')[1]
if extension not in ['png', 'jpg'] :
return {
'status': 'error',
'detail': 'File extenstion not allowed',
}
token_name = secrets.token_hex(10)+ '.' + extension
generate_name = FILEPATH + token_name
file_content = await file.read()
with open(generate_name, 'wb') as file :
file.write(file_content)
img = Image.open(generate_name)
img = img.resize(size = (200, 200))
img.save(generate_name)
file.close()
product = await Product.get(id = id)
business = await product.business
owner = await business.owner
if owner == user :
product.product_image = token_name
await product.save()
# return await product_pydantic.from_tortoise_orm(product)
else:
raise HTTPException(
status_code = status.HTTP_401_UNAUTHORIZED,
detail='Not authenticated to perform this action',
headers={'WWW-Authenticate': 'Bearer'}
)
file_url = 'localhost:8000' + generate_name[1:]
return {
'status': 'ok',
'filename': file_url
}
@app.post('/products')
async def add_new_product(product: product_pydanticIn,
user : user_pydantic = Depends(get_current_user)):
print('-----------------')
product = product.dict(exclude_unset = True)
if product['original_price'] > 0:
product['percentage_discount'] = ((product['original_price'] - product['new_price']) / product['original_price']) * 100
product_obj = await Product.create(**product, business = user)
product_obj = await product_pydantic.from_tortoise_orm(product_obj)
print(product_obj, type(product_obj), product_obj.__dict__)
print('--------')
return {
'status': 'ok',
'data': product_obj
}
else :
return {
'status': 'error',
}
@app.get('/product')
async def get_product():
response = await product_pydantic.from_queryset(Product.all())
return {
'status': 'ok',
'data': response
}
@app.get('/product/{id}')
async def get_product(id: int):
product = await Product.get(id = id)
business = await product.business
owner = await business.owner
response = await product_pydantic.from_queryset_single(Product.get(id = id))
return {
'status': 'ok',
'data': {
'product_detail': response,
'business_detail': {
'name': business.business_name,
'city': business.city,
'region': business.region,
'logo': business.logo,
'description': business.business_description,
'owner_id': owner.id,
'email': owner.email,
'join_date': owner.join_date.strftime('%b %d %Y')
}
}
}
@app.delete('/product/{id}')
async def delete_product(id: int, user: user_pydantic = Depends(get_current_user)):
product = await Product.get(id = id)
business = await product.business
owner = await business.owner
if user == owner :
product.delete()
else :
raise HTTPException(
status_code = status.HTTP_401_UNAUTHORIZED,
detail='Not authenticated to perform this action',
headers={'WWW-Authenticate': 'Bearer'}
)
@app.put('/product/{id}')
async def update_product(id: int,
update_info: product_pydanticIn,
user: user_pydantic = Depends(get_current_user)):
product = await Product.get(id = id)
business = await product.business
owner = await business.owner
update_info = update_info.dict(exclude_unset = True)
update_info['date_published'] = datetime.utcnow()
if user == owner and update_info['original_price'] != 0 :
update_info['percentage_discount'] = ((update_info['original_price'] - update_info['new_price'])/ update_info['original_price']) * 100
product = await product.update_from_dict(update_info)
await product.save()
response = await product_pydantic.from_tortoise_orm(product)
return {
'status': 'ok',
'data': response
}
else :
raise HTTPException(
status_code = status.HTTP_401_UNAUTHORIZED,
detail='Not authenticated to perform this action',
headers={'WWW-Authenticate': 'Bearer'}
)
@app.put('/business/{id}')
async def update_business(id: int,
update_business : business_pydanticIn,
user: user_pydantic = Depends(get_current_user)):
update_business = update_business.dict()
business = await Business.get(id = id)
business_owner = await business.owner
if user == business_owner :
await business.update_from_dict(update_business)
business.save()
response = await business_pydantic.from_tortoise_orm(business)
return {
'status': 'ok',
'data': response
}
else :
raise HTTPException(
status_code = status.HTTP_401_UNAUTHORIZED,
detail='Not authenticated to perform this action',
headers={'WWW-Authenticate': 'Bearer'}
)
register_tortoise(
app,
db_url="postgres://admin:1234@localhost:5431/postgres",
modules={'models': ['models']},
generate_schemas=True,
add_exception_handlers=True
)