Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion backend/.gitignore

This file was deleted.

3 changes: 3 additions & 0 deletions backend/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# FastAPI

# Update 21/4/2566
Binary file added backend/__pycache__/eaccoms.cpython-311.pyc
Binary file not shown.
Binary file removed backend/__pycache__/hashing.cpython-311.pyc
Binary file not shown.
Binary file removed backend/__pycache__/jwttoken.cpython-311.pyc
Binary file not shown.
Binary file added backend/__pycache__/main.cpython-311.pyc
Binary file not shown.
Binary file added backend/__pycache__/projectid.cpython-311.pyc
Binary file not shown.
Binary file added backend/__pycache__/projects.cpython-311.pyc
Binary file not shown.
3 changes: 3 additions & 0 deletions backend/eaccoms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
def get_eaccoms():
eaccoms = []
return eaccoms
32,319 changes: 0 additions & 32,319 deletions backend/get-pip.py

This file was deleted.

9 changes: 0 additions & 9 deletions backend/hashing.py

This file was deleted.

27 changes: 0 additions & 27 deletions backend/jwttoken.py

This file was deleted.

40 changes: 40 additions & 0 deletions backend/login.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
from fastapi import FastAPI
from pydantic import BaseModel
import jwt
from fastapi.encoders import jsonable_encoder

app = FastAPI()

SECERT_KEY = "YOU_FAST_API_SECRET_KEY"
ALGORITHM = "HS256"
ACESS_TOKEN_EXPIRES_MINUTES = 800

test_user = {
"password": "temipassword",
"email": "temiemail@gmail.com"
}


class LoginItem(BaseModel):
username: str
password: str | None = None
email: str | None = None

@app.get("/")
def read_root():
return {"Hello": "World"}



@app.post("/login")
async def user_login(loginitem: LoginItem):

data = jsonable_encoder(loginitem)

if data['password'] == test_user['password'] and data['email'] == test_user['email']:

encoded_jwt = jwt.encode(data, SECERT_KEY, algorithm=ALGORITHM)
return {"token": encoded_jwt}

else:
return {"message": "login failed"}
152 changes: 99 additions & 53 deletions backend/main.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
from typing import Optional
from fastapi import FastAPI, HTTPException, Depends, Request,status
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from jwttoken import create_access_token
from oauth import get_current_user
from fastapi.security import OAuth2PasswordRequestForm

from fastapi import FastAPI, Response, status, HTTPException

import requests

from fastapi.middleware.cors import CORSMiddleware

from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse

import mysql.connector

from projects import get_projects, mySQL_Connection
from projectid import get_projectid

from eaccoms import get_eaccoms

app = FastAPI()
origins = [
"http://localhost:3000",
"http://localhost:8080",
]
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
Expand All @@ -20,45 +25,86 @@
allow_headers=["*"],
)

from pymongo import MongoClient
mongodb_uri = 'mongodb+srv://manjeet:test1234@cluster0.nbszr.mongodb.net/myFirstDatabase?retryWrites=true&w=majority'
port = 8000
client = MongoClient(mongodb_uri, port)
db = client["User"]


class User(BaseModel):
username: str
company: str
password: str
class Login(BaseModel):
username: str
password: str
class Token(BaseModel):
access_token: str
token_type: str
class TokenData(BaseModel):
username: Optional[str] = None

@app.get("/")
def read_root(current_user:User = Depends(get_current_user)):
return {"data":"Hello OWrld"}

@app.post('/register')
def create_user(request:User):
hashed_pass = Hash.bcrypt(request.password)
user_object = dict(request)
user_object["password"] = hashed_pass
user_id = db["users"].insert(user_object)
# print(user)
return {"res":"created"}

@app.post('/login')
def login(request:OAuth2PasswordRequestForm = Depends()):
user = db["users"].find_one({"username":request.username})
if not user:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,detail = f'No user found with this {request.username} username')
if not Hash.verify(user["password"],request.password):
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,detail = f'Wrong Username or password')
access_token = create_access_token(data={"sub": user["username"] })
return {"access_token": access_token, "token_type": "bearer"}
# การอัพเดทฐานข้อมูลเกี่ยวกับโปรเจ็ค
@app.put("/projects")
async def update_project(data: dict):
projectId = data.get("project_id")
projectName = data.get("project_name")
projectAPI = data.get("project_url")
projectKey = data.get("project_key")
projectSection = data.get("project_section")

if not all ([projectName, projectAPI, projectKey, projectSection]):
raise HTTPException(status_code=400, detail="กรุณากรอกข้อมูลให้ครบถ้วนก่อนที่จะบันทึกลงฐานข้อมูล")
try:
mySQL, myCursor = mySQL_Connection()

stringDatabase = "UPDATE `projects` SET `project_name` = %s, `project_url` = %s, `project_key` = %s, `project_section` = %s WHERE `projects`.`project_id` = %s"
variableDatabase = (projectName, projectAPI, projectKey, projectSection, projectId)
myCursor.execute(stringDatabase, variableDatabase)

mySQL.commit()
mySQL.close()
myCursor.close()
return JSONResponse(content=jsonable_encoder({"message": "คุณได้อัพเดทข้อมูลลงฐานข้อมูลเรียบร้อยแล้ว"}))
except mysql.connector.Error as err:
raise HTTPException(status_code=500, detail=str(err))

@app.delete("/projects/delete/{id}")
def delete_project(id: int, respone: Response):
mySQL, myCursor = mySQL_Connection()

stringDatabase = "DELETE FROM `projects` WHERE `projects`.`project_id` = %s"
val = (id, )
myCursor.execute(stringDatabase, val)

mySQL.commit()
mySQL.close()
myCursor.close()
return JSONResponse(content=jsonable_encoder({"message": "คุณได้ลบข้อมูลออกจากฐานข้อมูลเรียบร้อยแล้ว"}))

# การเพิ่มฐานข้อมูลเกี่ยวกับโปรเจ็ค
@app.post("/projects/post")
async def insert_user(data: dict):
Project_description = data.get("project_name")
Project_api = data.get("project_url")
Project_key = data.get("project_key")
Project_section = data.get("project_section")

if not all([Project_description, Project_api, Project_key, Project_section]):
raise HTTPException(
status_code=400, detail="กรุณากรอกข้อมูลให้ครบถ้วนก่อนที่จะบันทึกลงฐานข้อมูล")
try:
mySQL, myCursor = mySQL_Connection()

Database = "INSERT INTO `projects` (`project_name`, `project_url`, `project_key`, `project_section`) VALUES (%s, %s, %s, %s)"
Variable = (Project_description, Project_api, Project_key, Project_section)
myCursor.execute(Database, Variable)

mySQL.commit()
mySQL.close()
myCursor.close()
return JSONResponse(content=jsonable_encoder({"message": "คุณได้บันทึกลงฐานข้อมูลเรียบร้อยแล้ว"}))
except mysql.connector.Error as err:
raise HTTPException(status_code=500, detail=str(err))

# ดึงไอดีข้อมูลแก้ไขเกี่ยวกับโปรเจค
@app.get("/EditForms/{id}")
def read_project(id: int, response: Response):
return get_projectid(id, response)

@app.get("/project/{id}")
def read_project(id: int, response: Response):
return get_projectid(id, response)

@app.get("/api/accoms/rooms")
async def get_rooms():
url = "https://demo.eaccom.net/api/v1/room/"
response = requests.get(url)
data = response.json()
return data

@app.get("/api/projects")
def read_products():
products = get_projects()
return JSONResponse(content=jsonable_encoder(products))
12 changes: 0 additions & 12 deletions backend/oauth.py

This file was deleted.

50 changes: 50 additions & 0 deletions backend/projectid.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
from fastapi import status, Response
import mysql.connector


def mySQL_Connection():
mySQL = mysql.connector.connect(
host="localhost", user="root", password="", database="manageapi")
myCursor = mySQL.cursor(dictionary=True)
return mySQL, myCursor


def get_projectid(id: int, response: Response):
mySQL, myCursor = mySQL_Connection()

myproducts = 'SELECT * FROM `projects` WHERE `project_id` = %s'
val = (id, )
myCursor.execute(myproducts, val)
mystringprojects = myCursor.fetchone()

if mystringprojects is None:
response.status_code = status.HTTP_404_NOT_FOUND
return {"message": "ไม่มีสินค้าชิ้นนี้ในฐานข้อมูล"}
else:
result = {}
result['project_id'] = mystringprojects['project_id']
result['project_name'] = mystringprojects['project_name']
result['project_url'] = mystringprojects['project_url']
result['project_key'] = mystringprojects['project_key']
result['project_section'] = mystringprojects['project_section']

mySQL.close()
myCursor.close()
response.status_code = status.HTTP_200_OK
return result

# if mystringcomponents:
# component = []
# for data in mystringcomponents:
# components = {}
# components['name'] = data['component_name']
# components['value'] = data['component_type']
# component.append(components)
# result['product_component'] = component
# else:
# result['product_component'] = None

# mySQL.close()
# myCursor.close()
# response.status_code = status.HTTP_200_OK
# return result
60 changes: 60 additions & 0 deletions backend/projects.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import mysql.connector


def mySQL_Connection():
mySQL = mysql.connector.connect(
host="localhost", user="root", password="", database="manageapi")
myCursor = mySQL.cursor(dictionary=True)
return mySQL, myCursor


def get_projects():
mySQL, myCursor = mySQL_Connection()

myCursor.execute('SELECT * FROM `projects`')
stringprojects = myCursor.fetchall()

projects = []
for project in stringprojects:
project_dict = {}
project_dict['project_id'] = project['project_id']
project_dict['project_name'] = project['project_name']
project_dict['project_url'] = project['project_url']
project_dict['project_key'] = project['project_key']
project_dict['project_section'] = project['project_section']
projects.append(project_dict)
mySQL.close()
myCursor.close()
return projects

# def get_products():
# mySQL, myCursor = mySQL_Connection()

# myCursor.execute('SELECT * FROM `products`')
# mystringproducts = myCursor.fetchall()

# myCursor.execute('SELECT * FROM `products_component`')
# mystringcomponents = myCursor.fetchall()

# products = []
# for product in mystringproducts:
# product_dict = {}
# product_dict['product_id'] = product['product_id']
# product_dict['product_name'] = product['product_name']
# product_dict['product_price'] = product['product_price']
# product_dict['product_cost'] = product['product_cost']
# product_dict['product_total'] = product['product_total']
# product_dict['product_detail'] = []

# for component in mystringcomponents:
# if component['component_id'] == product['product_id']:
# component_dict = {}
# component_dict['component_name'] = component['component_name']
# component_dict['component_type'] = component['component_type']
# product_dict['product_detail'].append(component_dict)
# products.append(product_dict)

# mySQL.close()
# myCursor.close()

# return products
7 changes: 0 additions & 7 deletions backend/requirement.txt

This file was deleted.

Loading