save 15-8-2022

This commit is contained in:
2022-08-15 10:53:52 +07:00
parent d21fdea082
commit a027c72910
6 changed files with 121 additions and 22 deletions

View File

@@ -1,6 +1,6 @@
from fastapi import Depends, HTTPException, status
from jose import JWTError, jwt
from .settings import pwd_context, db, oauth2_scheme, SECRET_KEY, ALGORITHM
from .settings import *
from datetime import datetime, timedelta
from typing import Optional
@@ -22,7 +22,7 @@ async def get_user(id: str):
async def authenticate_user(token: str):
url = "https://sandboxapi.ebacsi.com.vn/auth/oauth/check_token"
url = URL_OAUTH2_GET_CHECK_TOKEN
payload = {'token': token}
headers = {
'Authorization': 'Basic RGljdGlvbmFyeU1lZGlob21lOlJ4aXR6ZnZvaWFmZmNtb2l0ZW0='
@@ -33,7 +33,7 @@ async def authenticate_user(token: str):
async def authenticate_user_oauth2(username: str, password: str):
url = "https://sandboxapi.ebacsi.com.vn/auth/oauth/token"
url = URL_OAUTH2_GET_TOKEN
payload = {'username': username,
'password': password,
@@ -70,7 +70,7 @@ async def get_current_user(token: str = Depends(oauth2_scheme)):
headers={"WWW-Authenticate": "Bearer"},
)
try:
url = "https://sandboxapi.ebacsi.com.vn/auth/oauth/check_token"
url = URL_OAUTH2_GET_CHECK_TOKEN
payload = {'token': token}

View File

@@ -58,7 +58,7 @@ class PostModel(BaseModel):
is_active: bool
created_at: Optional[datetime] = datetime.now(tz=tz)
updated_at: Optional[datetime] = None
specialist: str
specialist: str = None
summary: str = None
data: List[DataPost]
point: Point = None
@@ -125,7 +125,7 @@ class UpdatePostModel(BaseModel):
updated_at: Optional[datetime] = datetime.now(tz=tz)
specialist: str = None
summary: str = None
data: List[DataPost]
data: List[DataPost] = None
point: Point = None
class Config:
@@ -178,13 +178,13 @@ class UpdatePostModel(BaseModel):
class ShowPostModel(BaseModel):
id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")
original_post: Optional[str]
translation_post: Optional[str]
link: Optional[str]
original_post: Optional[str] = None
translation_post: Optional[str] = None
link: Optional[str] = None
is_active: Optional[str]
specialist: Optional[str] = None
summary: Optional[str] = None
data: List[DataSmallPost]
data: List[DataSmallPost] = None
point: Point = None
class Config:

View File

@@ -83,6 +83,19 @@ async def create_post(post: PostModel,
"total": 0
}
# create_history()
for dt in post["data"]:
if "ADMIN" in dt["level"]:
dt["level"].append("ORG_ADMIN")
dt["level"].remove("ADMIN")
if "PATIENT" in dt["level"]:
dt["level"].append("ORG_USER")
dt["level"].remove("PATIENT")
if "OPERATOR" in dt["level"]:
dt["level"].append("ORG_OPERATOR")
dt["level"].remove("OPERATOR")
if "RECEIPTION" in dt["level"]:
dt["level"].append("SITE_RECEIPTION")
dt["level"].remove("RECEIPTION")
new_post = await db["posts"].insert_one(post)
created_post = await db["posts"].find_one({"_id": new_post.inserted_id})
# aaa = create_history(username=data, status="tạo bài viết",
@@ -133,7 +146,7 @@ async def list_post(
if token.token != None:
posts = jsonable_encoder(posts)
for post in posts:
url = "https://sandboxapi.ebacsi.com.vn/auth/oauth/check_token"
url = URL_OAUTH2_GET_CHECK_TOKEN
payload = {'token': token.token}
@@ -410,6 +423,14 @@ async def get_post_by_name(history: HistoryFindModel):
data_token = await get_current_user(token)
data = data_token.get("user_name", None)
user_type = data_token.get("user_type", None)
if "ADMIN" == user_type:
user_type = "ORG_ADMIN"
if "PATIENT" == user_type:
user_type = "ORG_USER"
if "OPERATOR" == user_type:
user_type = "ORG_OPERATOR"
if "RECEIPTION" == user_type:
user_type = "SITE_RECEIPTION"
if data == None:
return JSONResponse(status_code=status.HTTP_401_UNAUTHORIZED, content={"message": "UNAUTHORIZED"})
else:
@@ -768,3 +789,79 @@ async def find_list_post(status: str = None, specialist: str = None, key_find: s
del history_user["authorities"]
history_new = await db["history"].insert_one(history_user)
return posts
@post.post(
"/find_post_save", response_description="search list posts"
)
async def find_list_post(token: str, page: int = 0, limit: int = 10, key_find: str = None, history: HistoryFindModel = None):
# point_data = ["point.less10",
# "point.form10to20",
# "point.form20to30",
# "point.form30to40",
# "point.form40to50",
# "point.form50to60",
# ]
age_sort = "point.total"
# history = jsonable_encoder(history)
# if history.get("age", None) != None:
# if history.get("age") > 59:
# age_sort = "point.bigger60"
# else:
# age_sort = point_data[history.get("age")//10]
# posts = await db["posts"].find("$or": [
# {"translation_post": {"$regex": key_find}},
# {"translation_post": {"$regex": key_find}},
print(key_find)
# ]).sort(age_sort, -1).to_list(100)
if key_find != None:
posts = await db["posts"].find({
"$or": [
{"translation_post": {"$regex": key_find, "$options": 'i'}},
{"data.content": {"$regex": key_find, "$options": 'i'}},
{"original_post": {"$regex": key_find, "$options": 'i'}},
{"summary": {"$regex": key_find, "$options": 'i'}},
{"tag": {"$regex": key_find, "$options": 'xi'}},
]
}).sort("point.total", -1).skip(page*limit).to_list(limit)
else:
posts = await db["posts"].find().sort("point.total", -1).skip(page*limit).to_list(limit)
count_total = 0
output = []
# history.created_at = datetime.datetime.now(tz=tz)
if token != None:
data_token = await get_current_user(token)
data = data_token.get("user_name", None)
user_type = data_token.get("user_type", None)
history = jsonable_encoder(history)
history_user = history
history_user["user_name"] = data
history_user["status"] = "Tìm kiếm bài viết đã lưu theo từ khóa"
history_user["note"] = ""
history_user["data"] = key_find
check_data = await db["history"].find({"data": key_find, "status": "Tìm kiếm bài viết đã lưu theo từ khóa"}).sort("created_at", -1).to_list(1)
if check_data != []:
history_user["count"] = int(check_data[0]["count"]) + 1
else:
history_user["count"] = 1
del history_user["_id"]
del history_user["token"]
del history_user["sick"]
del history_user["authorities"]
print(history_user)
history_new = await db["history"].insert_one(history_user)
for post in posts:
if data == None:
return JSONResponse(status_code=status.HTTP_401_UNAUTHORIZED, content={"message": "UNAUTHORIZED"})
post = jsonable_encoder(post)
count = await db["post_save"].count_documents({"post_id": post["_id"], "username": data})
if count != 0:
post["post_save"] = True
output.append(post)
count_total = count_total + 1
return {
"total": count_total,
"data": output,
}

View File

@@ -23,7 +23,7 @@ from ..dependecies import (
create_access_token,
get_password_hash
)
from ..settings import db, ACCESS_TOKEN_EXPIRE_MINUTES
from ..settings import *
import json
from typing import List
from datetime import datetime, timedelta
@@ -43,7 +43,7 @@ post_save = APIRouter()
@post_save.post("/save_post", response_description="save new post", response_model=SavePostModel)
async def create_post(post_save: SavePost):
try:
url = "https://sandboxapi.ebacsi.com.vn/auth/oauth/check_token"
url = URL_OAUTH2_GET_CHECK_TOKEN
payload = {'token': post_save.token}
headers = {
'Authorization': 'Basic RGljdGlvbmFyeU1lZGlob21lOlJ4aXR6ZnZvaWFmZmNtb2l0ZW0='
@@ -75,7 +75,7 @@ async def create_post(post_save: SavePost):
"/list_save_post_by_user", response_description="List save posts", response_model=SavePostModel
)
async def list_post(post_save: SavePost):
url = "https://sandboxapi.ebacsi.com.vn/auth/oauth/check_token"
url = URL_OAUTH2_GET_CHECK_TOKEN
payload = {'token': post_save.token}
headers = {
'Authorization': 'Basic RGljdGlvbmFyeU1lZGlob21lOlJ4aXR6ZnZvaWFmZmNtb2l0ZW0='
@@ -94,7 +94,7 @@ async def list_post(post_save: SavePost):
async def delete_save_post(post_id: str, token: str):
# delete_result = await db["post_save"].delete_one({"_id": user_id})
try:
url = "https://sandboxapi.ebacsi.com.vn/auth/oauth/check_token"
url = URL_OAUTH2_GET_CHECK_TOKEN
payload = {'token': token}
headers = {
'Authorization': 'Basic RGljdGlvbmFyeU1lZGlob21lOlJ4aXR6ZnZvaWFmZmNtb2l0ZW0='

View File

@@ -24,7 +24,7 @@ from ..dependecies import (
create_access_token,
get_password_hash
)
from ..settings import db, ACCESS_TOKEN_EXPIRE_MINUTES
from ..settings import *
import json
from typing import List
from datetime import datetime, timedelta
@@ -72,7 +72,7 @@ router = APIRouter()
@router.post("/login")
async def login_for_access_token(body: LoginRequest):
url = "https://sandboxapi.ebacsi.com.vn/auth/oauth/token"
url = URL_OAUTH2_GET_TOKEN
payload = {'username': body.username,
'password': body.password,
@@ -90,7 +90,7 @@ async def login_for_access_token(body: LoginRequest):
access_token = json.loads(response.text)
url = "https://sandboxapi.ebacsi.com.vn/auth/oauth/check_token"
url = URL_OAUTH2_GET_CHECK_TOKEN
payload = {'token': access_token["access_token"]}
headers = {
'Authorization': 'Basic RGljdGlvbmFyeU1lZGlob21lOlJ4aXR6ZnZvaWFmZmNtb2l0ZW0='
@@ -107,7 +107,7 @@ async def login_for_access_token(body: LoginRequest):
# @router.post("/token")
# async def login_for_access_token(body: OAuth2PasswordRequestForm = Depends()):
# url = "https://sandboxapi.ebacsi.com.vn/auth/oauth/token"
# url = URL_OAUTH2_GET_TOKEN
# payload = {'username': body.username,
# 'password': body.password,
@@ -164,7 +164,7 @@ async def login_for_access_token_2(body: OAuth2PasswordRequestForm = Depends()):
@router.post("/current", response_description="Current User")
async def current_user(token: TokenModel):
try:
url = "https://sandboxapi.ebacsi.com.vn/auth/oauth/check_token"
url = URL_OAUTH2_GET_CHECK_TOKEN
payload = {'token': token.token}
headers = {
'Authorization': 'Basic RGljdGlvbmFyeU1lZGlob21lOlJ4aXR6ZnZvaWFmZmNtb2l0ZW0='
@@ -188,7 +188,7 @@ async def current_user(token: TokenModel):
@router.post("/refresh_token", response_description="refresh token")
async def refresh_token(refresh_token: TokenModel):
url = "https://sandboxapi.ebacsi.com.vn/auth/oauth/token"
url = URL_OAUTH2_GET_TOKEN
payload = {'refresh_token': refresh_token.refresh_token,
'grant_type': refresh_token.grant_type}

View File

@@ -19,6 +19,8 @@ ACCESS_TOKEN_EXPIRE_MINUTES = 30
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
URL_SERVER = os.getenv('URL_SERVER')
URL_OAUTH2_GET_CHECK_TOKEN = os.getenv("URL_OAUTH2_GET_CHECK_TOKEN")
URL_OAUTH2_GET_TOKEN = os.getenv("URL_OAUTH2_GET_TOKEN")
class DateTimeEncoder(JSONEncoder):
@@ -29,7 +31,7 @@ class DateTimeEncoder(JSONEncoder):
oauth2_scheme = OAuth2PasswordBearer(
tokenUrl="https://sandboxapi.ebacsi.com.vn/auth/oauth/token")
tokenUrl=URL_OAUTH2_GET_CHECK_TOKEN)
ROLE_PUBLIC = "PUBLIC"
ROLE_ORG = [
{