-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
360 lines (298 loc) · 12 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
349
350
351
352
353
354
355
356
357
358
359
360
from fastapi import FastAPI, Request, HTTPException, status, Depends
from starlette.requests import Request
from starlette.responses import HTMLResponse
from tortoise.contrib.fastapi import register_tortoise
from tortoise import models
from models import *
from authentication import *
from emails import *
# auth
from authentication import *
from fastapi.security import (OAuth2PasswordBearer, OAuth2PasswordRequestForm)
# signals
from tortoise.signals import post_save
from typing import List, Optional, Type
from tortoise import BaseDBAsyncClient
# response classes
from fastapi.responses import HTMLResponse
# templates
from fastapi.templating import Jinja2Templates
# upload images
from fastapi import File, UploadFile
import secrets
from fastapi.staticfiles import StaticFiles
from PIL import Image
# CORS headers
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
# CORS url
origins = [
'http://localhost:3000'
]
# adding middleware
app.add_middleware(CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=['*'],
allow_headers=['*']
)
oauth2_scheme = OAuth2PasswordBearer(tokenUrl='token')
# config for static files
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_scheme)):
"""проверяем текущего пользователя"""
try:
payload = jwt.decode(token, config_credential["SECRET"], algorithms=['HS256'])
user = await User.get(id=payload.get("id"))
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)):
"""login пользователя"""
business = await Business.get(owner=user)
logo = business.logo
logo_path = "localhost:8000/static/images"+logo
return {
"status": "ok",
"data":
{
"username": user.username,
"email": user.email,
"verified": user.is_verified,
"joined_data": user.join_data.strtime("%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_fields: List[str]) -> None:
"""создаём функцию для отправки сингалов для создания бизнес аккаунта при создании пользователя"""
if created:
business_obj = await Business.create(
business_name=instance.username, owner=instance
)
await business_pydantic.from_tortoise_orm(business_obj)
await send_email([instance.email], instance)
@app.post("/registration")
async def user_registration(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}, we are glad to see you here. Check your email inbox to the link to confirm"
f" your registration"
}
# template for email verification
templates = Jinja2Templates(directory="templates")
@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 templates.TemplateResponse("verification.html", {"request": request, "username": user.username})
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or expired token",
headers={"WWW-Authenticate": "Bearer"}
)
@app.get("/")
def index():
return {"Message": "hello world"}
@app.post("/uplloadfile/profile")
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 extension not allowed"}
token_name = secrets.token_hex(10)+"." + extension
generated_name = FILEPATH + token_name
file_content = await file.read()
with open(generated_name, "wb") as file:
file.write(file_content)
img = Image.open(generated_name)
img = img.resize(size=(150, 150))
img.save(generated_name)
file.close()
business = await Business.get(owner=user)
owner = await business.owner
if owner == user:
business.logo = token_name
await business.save()
else:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated to do this",
headers={"WWW-Authenticate": "Bearer"}
)
file_url = "localhost:8000" + generated_name[1:]
return {"status": "ok", "filename": file_url}
@app.post("/uploadfile/product/{id}")
async def create_upload_productfile(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 extension not allowed"}
token_name = secrets.token_hex(10) + "." + extension
generated_name = FILEPATH + token_name
file_content = await file.read()
with open(generated_name, "wb") as file:
file.write(file_content)
img = Image.open(generated_name)
img = img.resize(size=(150, 150))
img.save(generated_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()
else:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated to do this",
headers={"WWW-Authenticate": "Bearer"}
)
file_url = "localhost:8000" + generated_name[1:]
return {"status": "ok", "filename": file_url}
# CRUD
@app.post("/product")
async def add_new_product(product: product_pydanticIn,
user: user_pydantic = Depends(get_current_user)):
"""добавление продукта"""
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)
return {"status": "ok", "data": product_obj}
else:
return {"status": "error"}
@app.get("/products")
async def get_products():
"""получение данных прдуктов"""
response = await product_pydantic.from_queryset(Product.all())
return {"status": "ok", "data": response}
@app.get("/product/{id}")
async def get_single_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_details": response,
"business_details": {
"name": business.business_name,
"city": business.city,
"region": business.region,
"description": business.business_description,
"logo": business.logo,
"owner_id": owner.id,
"business_id": business.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:
await product.delete()
else:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated to do this",
headers={"WWW-Authenticate": "Bearer"}
)
return {"status": "ok"}
@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 do this",
headers={"WWW-Authenticate": "Bearer"}
)
@app.put("update_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)
await 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 do this",
headers={"WWW-Authenticate": "Bearer"}
)
@app.delete("delete_business/{id}")
async def delete_business(id: int, user: user_pydantic = Depends(get_current_user)):
"""удаление бизнесса"""
business = await Business.get(id=id)
business_owner = await business.owner
if user == business_owner:
await business.delete()
else:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated to do this",
headers={"WWW-Authenticate": "Bearer"}
)
return {"status": "ok"}
register_tortoise(
app,
db_url="sqlite://database.sqlite3",
modules={"models": ["models"]},
generate_schemas=True,
add_exception_handlers=True
)