main.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  1. # fastapi
  2. from fastapi import FastAPI, Request, Response, HTTPException, status, Depends , Form
  3. from fastapi import templating
  4. from fastapi.templating import Jinja2Templates
  5. from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
  6. from fastapi.middleware.cors import CORSMiddleware
  7. from fastapi.staticfiles import StaticFiles
  8. # fastapi view function parameters
  9. from typing import List, Optional
  10. import json
  11. # path
  12. import sys
  13. from sqlalchemy.sql.elements import False_
  14. # time
  15. # import datetime
  16. from datetime import timedelta, datetime
  17. # db
  18. import dataset
  19. from passlib import context
  20. import models
  21. from random import randint
  22. # authorize
  23. from passlib.context import CryptContext
  24. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  25. import jwt
  26. from fastapi_jwt_auth import AuthJWT
  27. from fastapi_jwt_auth.exceptions import AuthJWTException
  28. from fastapi.security import OAuth2AuthorizationCodeBearer, OAuth2PasswordRequestForm
  29. import numpy as np
  30. import pymysql
  31. pymysql.install_as_MySQLdb()
  32. db_settings = {
  33. "host": "db.ptt.cx",
  34. "port": 3306,
  35. "user": "choozmo",
  36. "password": "pAssw0rd",
  37. "db": "Water_tower",
  38. "charset": "utf8mb4"
  39. }
  40. # app
  41. app = FastAPI()
  42. app.add_middleware(
  43. CORSMiddleware,
  44. allow_origins=["*"],
  45. allow_credentials=True,
  46. allow_methods=["*"],
  47. allow_headers=["*"],
  48. )
  49. SECRET_KEY = "df2f77bd544240801a048bd4293afd8eeb7fff3cb7050e42c791db4b83ebadcd"
  50. ALGORITHM = "HS256"
  51. ACCESS_TOKEN_EXPIRE_MINUTES = 3000
  52. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  53. #
  54. app.mount(path='/templates', app=StaticFiles(directory='templates'), name='templates')
  55. app.mount(path='/static', app=StaticFiles(directory='static'), name='static ')
  56. #
  57. templates = Jinja2Templates(directory='templates')
  58. @AuthJWT.load_config
  59. def get_config():
  60. return models.Settings()
  61. # view
  62. @app.get('/', response_class=HTMLResponse)
  63. async def index(request: Request):
  64. print(request)
  65. return templates.TemplateResponse(name='index.html', context={'request': request})
  66. @app.get('/login', response_class=HTMLResponse)
  67. async def login(request: Request):
  68. return templates.TemplateResponse(name='login.html', context={'request': request})
  69. @app.post("/login")
  70. async def login_for_access_token(request: Request, form_data: OAuth2PasswordRequestForm = Depends(), Authorize: AuthJWT = Depends()):
  71. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  72. user = authenticate_user(form_data.username, form_data.password)
  73. if not user:
  74. raise HTTPException(
  75. status_code=status.HTTP_401_UNAUTHORIZED,
  76. detail="Incorrect username or password",
  77. headers={"WWW-Authenticate": "Bearer"},
  78. )
  79. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  80. access_token = create_access_token(
  81. data={"sub": user.username}, expires_delta=access_token_expires
  82. )
  83. table = db['users']
  84. user.token = access_token
  85. print(user)
  86. table.update(dict(user), ['username'],['password'])
  87. access_token = Authorize.create_access_token(subject=user.username)
  88. refresh_token = Authorize.create_refresh_token(subject=user.username)
  89. Authorize.set_access_cookies(access_token)
  90. Authorize.set_refresh_cookies(refresh_token)
  91. #return templates.TemplateResponse("home.html", {"request": request, "msg": 'Login'})
  92. return {"access_token": access_token, "token_type": "bearer"} # 回傳token給前端
  93. @app.get('/register', response_class=HTMLResponse)
  94. async def login(request: Request):
  95. return templates.TemplateResponse(name='rigister_test.html', context={'request': request})
  96. @app.post('/register')
  97. async def register(request: Request, form_data: OAuth2PasswordRequestForm = Depends()):
  98. user = models.User(**await request.form())
  99. print(form_data.username, form_data.password, user)
  100. user.id = randint(1000, 9999)
  101. user.isAdmin = 0 #預設為非管理者
  102. user.roleType = 0 #預設為employee
  103. # 密碼加密
  104. #user.password = get_password_hash(user.password)
  105. # 存入DB
  106. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  107. user_table = db['users']
  108. user_table.insert(dict(user))
  109. # 跳轉頁面至登入
  110. return templates.TemplateResponse(name='login.html', context={'request': request})
  111. @app.get('/home', response_class=HTMLResponse)
  112. async def home(request: Request):
  113. return templates.TemplateResponse(name='home.html', context={'request': request})
  114. @app.get('/tower', response_class=HTMLResponse)
  115. async def tower(request: Request, Authorize: AuthJWT = Depends()):
  116. try:
  117. Authorize.jwt_required()
  118. except Exception as e:
  119. print(e)
  120. return RedirectResponse('/login')
  121. current_user = Authorize.get_jwt_subject()
  122. result = get_user_under_organization(current_user)
  123. result.append({'Data' : get_tower_info('dev001')})
  124. return templates.TemplateResponse(name='tower.html', context={"request":request})
  125. @app.get('/tower/org', response_class=HTMLResponse)
  126. async def tower(request: Request, Authorize: AuthJWT = Depends()):
  127. try:
  128. Authorize.jwt_required()
  129. except Exception as e:
  130. print(e)
  131. return RedirectResponse('/login')
  132. current_user = Authorize.get_jwt_subject()
  133. result = get_user_under_organization(current_user)
  134. return json.dumps(result,ensure_ascii=False)
  135. @app.get('/tower/', response_class=HTMLResponse)
  136. async def tower(request: Request,company:str,factory:str,department:str,towerGroup:str, Authorize: AuthJWT = Depends()):
  137. try:
  138. Authorize.jwt_required()
  139. except Exception as e:
  140. print(e)
  141. return RedirectResponse('/login')
  142. #current_user = Authorize.get_jwt_subject()
  143. tower_arr = get_tower(company,factory,department,towerGroup)
  144. result = []
  145. for tower in tower_arr:
  146. result.append({'tower_name': tower,'tower_data': get_tower_info(tower)})
  147. print(result)
  148. return json.dumps(result,ensure_ascii=False)
  149. @app.get('/optim', response_class=HTMLResponse)
  150. async def optim(request: Request, Authorize: AuthJWT = Depends()):
  151. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  152. table=db['record_tower']
  153. temp = table.find_one(key = 'hotTemp')
  154. statement2 = 'SELECT value FROM record_tower WHERE record_tower.key = "coldTempData2"'
  155. for temp2 in db.query(statement2):
  156. print(temp2['value'])
  157. statement3 = 'SELECT value FROM record_tower WHERE record_tower.key = "wetTemp"'
  158. for temp3 in db.query(statement3):
  159. print(temp3['value'])
  160. try:
  161. Authorize.jwt_required()
  162. except Exception as e:
  163. print(e)
  164. return RedirectResponse('/login')
  165. return templates.TemplateResponse(name='optim.html',context={'request': request,"temp":temp,"temp2":temp2,"temp3":temp3})
  166. @app.get('/vibration', response_class=HTMLResponse)
  167. async def vibration(request: Request, Authorize: AuthJWT = Depends()):
  168. try:
  169. Authorize.jwt_required()
  170. except Exception as e:
  171. print(e)
  172. return RedirectResponse('/login')
  173. # current_user = Authorize.get_jwt_subject()
  174. return templates.TemplateResponse(name='vibration.html', context={'request': request})
  175. @app.get('/history', response_class=HTMLResponse)
  176. async def history(request: Request, Authorize: AuthJWT = Depends()):
  177. try:
  178. Authorize.jwt_required()
  179. except Exception as e:
  180. print(e)
  181. return RedirectResponse('/login')
  182. # current_user = Authorize.get_jwt_subject()
  183. return templates.TemplateResponse(name='history.html', context={'request': request})
  184. @app.get('/device', response_class=HTMLResponse)
  185. async def device(request: Request, Authorize: AuthJWT = Depends()):
  186. try:
  187. Authorize.jwt_required()
  188. except Exception as e:
  189. print(e)
  190. return RedirectResponse('/login')
  191. # current_user = Authorize.get_jwt_subject()
  192. return templates.TemplateResponse(name='device.html', context={'request': request})
  193. @app.get('/system', response_class=HTMLResponse)
  194. async def system(request: Request, Authorize: AuthJWT = Depends()):
  195. try:
  196. Authorize.jwt_required()
  197. except Exception as e:
  198. print(e)
  199. return RedirectResponse('/login')
  200. # current_user = Authorize.get_jwt_subject()
  201. return templates.TemplateResponse(name='system.html', context={'request': request})
  202. @app.get('/member', response_class=HTMLResponse)
  203. async def get_member(request: Request, Authorize: AuthJWT = Depends()):
  204. """獲取所有帳號資訊"""
  205. try:
  206. Authorize.jwt_required()
  207. except Exception as e:
  208. print(e)
  209. return RedirectResponse('/login')
  210. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  211. statement = 'SELECT id,username,isAdmin FROM users'
  212. json_dic = []
  213. for row in db.query(statement):
  214. #print(row['id'],row['username'])
  215. json_dic.append({'username':row['username'],'isAdmin':row['isAdmin'],'roleType':check_role_type(row['username']),'role_name' :get_role_name(check_role_type(row['username']))})
  216. result = json.dumps(json_dic,ensure_ascii=False)
  217. return result
  218. @app.get('/member/edit/', response_class=HTMLResponse)
  219. async def login(request: Request, name:str,isAdmin:int,isEnable:int ,Authorize: AuthJWT = Depends()):
  220. try:
  221. Authorize.jwt_required()
  222. except Exception as e:
  223. print(e)
  224. return RedirectResponse('/login')
  225. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  226. current_user = Authorize.get_jwt_subject()
  227. current_user_roleType = check_role_type(current_user)
  228. del_user_roleType = check_role_type(name)
  229. statement = 'SELECT isAdmin FROM users WHERE userName = "'+current_user+'"'
  230. for row in db.query(statement):
  231. if row['isAdmin']!=1:
  232. return json.dumps([{'msg':'你沒有權限'}],ensure_ascii=False)
  233. if del_user_roleType == None:
  234. return json.dumps([{'msg':'不存在使用者'}],ensure_ascii=False)
  235. elif current_user_roleType>del_user_roleType or current_user_roleType==del_user_roleType:
  236. return json.dumps([{'msg':'你沒有權限'}],ensure_ascii=False)
  237. user_dic = get_user(name)
  238. print(user_dic)
  239. user_dic.isAdmin = isAdmin
  240. user_dic.isEnable = isEnable
  241. table = db['users']
  242. table.update(dict(user_dic), ['username'])
  243. return json.dumps([{'msg':"成功更改"}],ensure_ascii=False)
  244. @app.get('/member_delete', response_class=HTMLResponse)
  245. async def login(request: Request, Authorize: AuthJWT = Depends()):
  246. try:
  247. Authorize.jwt_required()
  248. except Exception as e:
  249. print(e)
  250. return RedirectResponse('/login')
  251. return templates.TemplateResponse(name='delete_member_test2.html', context={'request': request})
  252. @app.post('/member_delete')
  253. async def delete_member(request: Request):
  254. """刪除成員"""
  255. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  256. del_user = models.del_user(**await request.form())
  257. delete_name = del_user.del_name
  258. statement = 'SELECT * FROM users'
  259. current_user = ''
  260. for row in db.query(statement):
  261. if row['token'] != None :
  262. if compare_jwt_token(row['token'],del_user.access_token):
  263. current_user = row['username']
  264. if current_user == '':
  265. return {'msg':'尚未登入'}
  266. statement = 'SELECT isAdmin FROM users WHERE userName = "'+current_user+'"'
  267. for row in db.query(statement):
  268. if row['isAdmin']!=1:
  269. return {'msg': ' 你沒有權限'}
  270. current_user_roleType = check_role_type(current_user)
  271. del_user_roleType = check_role_type(delete_name)
  272. if del_user_roleType == None:
  273. return {'msg':'不存在使用者'}
  274. elif current_user_roleType>del_user_roleType or current_user_roleType==del_user_roleType:
  275. return {'msg': ' 你沒有權限'}
  276. else :
  277. table = db['users']
  278. table.delete(username=delete_name)
  279. return {'msg': ' 成功刪除'}
  280. @app.get('/member_authority/{edit_one}', response_class=HTMLResponse)
  281. async def member_authority(request:Request,edit_one: int,Authorize: AuthJWT = Depends()):
  282. """設定成員權限"""
  283. try:
  284. Authorize.jwt_required()
  285. except Exception as e:
  286. print(e)
  287. return RedirectResponse('/login')
  288. context = {'request': request}
  289. current_user = Authorize.get_jwt_subject()
  290. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  291. statement = check_isAdmin(current_user)
  292. if statement == "no user":
  293. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':'no user' })
  294. elif statement == 0:
  295. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':"沒有權限" })
  296. current_user_roleType = check_role_type(current_user)
  297. if edit_one == None:
  298. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':'no role' })
  299. elif int(current_user_roleType)>int(edit_one) or int(current_user_roleType)==int(edit_one):
  300. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':"沒有權限" })
  301. result = check_role_acl(edit_one)
  302. if result == []:
  303. cmd = 'SELECT id FROM module'
  304. for row in db.query(cmd):
  305. dic_tmp = {'id':0,'isView':0,'isAdd':0 ,'isEdit':0,'isDel':0,'role_id' : edit_one}
  306. context[get_modul_name(row['id']) ] = dic_tmp
  307. else:
  308. for dic in result:
  309. modul_name = get_modul_name(dic['module_id'])
  310. del dic['module_id']
  311. context[modul_name ] = dic
  312. return templates.TemplateResponse(name='member_authority_test.html', context=context)
  313. @app.post('/member_authority')
  314. async def member_authority(request: Request):
  315. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  316. edit_one = models.user_authority(**await request.form())
  317. statement = 'SELECT * FROM users'
  318. current_user = ''
  319. for row in db.query(statement):
  320. if row['token'] != None :
  321. if compare_jwt_token(row['token'],edit_one.access_token):
  322. current_user = row['username']
  323. if current_user == '':
  324. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':'尚未登入'})
  325. statement = check_isAdmin(current_user)
  326. if statement == "no user":
  327. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':statement })
  328. elif statement == 0:
  329. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':'你沒有權限' })
  330. current_user_roleType = check_role_type(current_user)
  331. edit_one_roleType = edit_one.role_id
  332. if current_user_roleType>edit_one_roleType or current_user_roleType==edit_one_roleType:
  333. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg': ' 你沒有權限'})
  334. else :
  335. row = ['ai_prediction' ,'channel' ,'device', 'event', 'index' ,'performance', 'record', 'setting_device' ,'setting_system','tower']
  336. if check_role_acl(edit_one.role_id) == []:
  337. for module in row :
  338. new_dict = edit_one.get_acl_from_module_name(module)
  339. new_dict["id"]= None
  340. table = db['role_acl']
  341. table.insert(new_dict)
  342. else:
  343. for module in row :
  344. new_dict = edit_one.get_acl_from_module_name(module)
  345. table = db['role_acl']
  346. table.update(new_dict, ['id'])
  347. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg': '成功更改權限'})
  348. # 溫度API
  349. @app.get('/temperature')
  350. async def get_temperatures():
  351. """ 撈DB溫度 """
  352. return {'hot_water': 30.48, 'cold_water': 28.10, 'wet_ball': 25.14}
  353. @app.post("/example")
  354. async def example(request: Request,Authorize: AuthJWT = Depends()):
  355. try:
  356. Authorize.jwt_required()
  357. except Exception as e:
  358. print(e)
  359. current_user = Authorize.get_jwt_subject()
  360. #form_data = await request.form()
  361. print( current_user)
  362. return current_user
  363. @app.post('/user')
  364. def user(Authorize: AuthJWT = Depends()):
  365. Authorize.jwt_required()
  366. current_user = Authorize.get_jwt_subject()
  367. return {"user": current_user}
  368. @app.get("/example", response_class=HTMLResponse)
  369. async def example(request: Request,Authorize: AuthJWT = Depends()):
  370. try:
  371. Authorize.jwt_required()
  372. except Exception as e:
  373. print(e)
  374. return RedirectResponse('/login')
  375. current_user = Authorize.get_jwt_subject()
  376. print( current_user)
  377. return current_user
  378. @app.get('/health')
  379. async def get_health(date: str):
  380. """ 撈健康指標、預設健康指標 """
  381. date = str(datetime.strptime(date, "%Y-%m-%d"))[:10]
  382. print(date)
  383. print(str(datetime.today()))
  384. print(str(datetime.today()-timedelta(days=1)))
  385. fake_data = {
  386. str(datetime.today())[:10]: {'curr_health': 0.7, 'pred_health': 0.8},
  387. str(datetime.today()-timedelta(days=1))[:10]: {'curr_health': 0.6, 'pred_health': 0.7},
  388. }
  389. return fake_data[date]
  390. @app.get('/history_data')
  391. async def get_history(time_end: str):
  392. """ 透過終點時間,抓取歷史資料。 """
  393. date = str(datetime.strptime(time_end, "%Y-%m-%d"))[:10]
  394. print(date)
  395. print(str(datetime.today()))
  396. print(str(datetime.today()-timedelta(days=1)))
  397. fake_data = {
  398. str(datetime.today())[:10]: {
  399. 'curr_history': {
  400. 'RPM_1X': list(np.random.rand(13)),
  401. 'RPM_2X': list(np.random.rand(13)),
  402. 'RPM_3X': list(np.random.rand(13)),
  403. 'RPM_4X': list(np.random.rand(13)),
  404. 'RPM_5X': list(np.random.rand(13)),
  405. 'RPM_6X': list(np.random.rand(13)),
  406. 'RPM_7X': list(np.random.rand(13)),
  407. 'RPM_8X': list(np.random.rand(13)),
  408. 'Gear_1X': list(np.random.rand(13)),
  409. 'Gear_2X': list(np.random.rand(13)),
  410. 'Gear_3X': list(np.random.rand(13)),
  411. 'Gear_4X': list(np.random.rand(13)),
  412. },
  413. 'past_history': {
  414. 'RPM_1X': list(np.random.rand(13)),
  415. 'RPM_2X': list(np.random.rand(13)),
  416. 'RPM_3X': list(np.random.rand(13)),
  417. 'RPM_4X': list(np.random.rand(13)),
  418. 'RPM_5X': list(np.random.rand(13)),
  419. 'RPM_6X': list(np.random.rand(13)),
  420. 'RPM_7X': list(np.random.rand(13)),
  421. 'RPM_8X': list(np.random.rand(13)),
  422. 'Gear_1X': list(np.random.rand(13)),
  423. 'Gear_2X': list(np.random.rand(13)),
  424. 'Gear_3X': list(np.random.rand(13)),
  425. 'Gear_4X': list(np.random.rand(13)),
  426. }
  427. },
  428. str(datetime.today()-timedelta(days=1))[:10]: {
  429. 'curr_history': {
  430. 'RPM_1X': list(np.random.rand(13)),
  431. 'RPM_2X': list(np.random.rand(13)),
  432. 'RPM_3X': list(np.random.rand(13)),
  433. 'RPM_4X': list(np.random.rand(13)),
  434. 'RPM_5X': list(np.random.rand(13)),
  435. 'RPM_6X': list(np.random.rand(13)),
  436. 'RPM_7X': list(np.random.rand(13)),
  437. 'RPM_8X': list(np.random.rand(13)),
  438. 'Gear_1X': list(np.random.rand(13)),
  439. 'Gear_2X': list(np.random.rand(13)),
  440. 'Gear_3X': list(np.random.rand(13)),
  441. 'Gear_4X': list(np.random.rand(13)),
  442. },
  443. 'past_history': {
  444. 'RPM_1X': list(np.random.rand(13)),
  445. 'RPM_2X': list(np.random.rand(13)),
  446. 'RPM_3X': list(np.random.rand(13)),
  447. 'RPM_4X': list(np.random.rand(13)),
  448. 'RPM_5X': list(np.random.rand(13)),
  449. 'RPM_6X': list(np.random.rand(13)),
  450. 'RPM_7X': list(np.random.rand(13)),
  451. 'RPM_8X': list(np.random.rand(13)),
  452. 'Gear_1X': list(np.random.rand(13)),
  453. 'Gear_2X': list(np.random.rand(13)),
  454. 'Gear_3X': list(np.random.rand(13)),
  455. 'Gear_4X': list(np.random.rand(13)),
  456. }
  457. },
  458. }
  459. return fake_data[date]
  460. # Login funtion part
  461. def check_user_exists(username):
  462. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  463. if int(next(iter(db.query('SELECT COUNT(*) FROM Water_tower.users WHERE userName = "'+username+'"')))['COUNT(*)']) > 0:
  464. return True
  465. else:
  466. return False
  467. def get_user(username: str):
  468. """ 取得使用者資訊(Model) """
  469. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  470. if not check_user_exists(username): # if user don't exist
  471. return False
  472. user_dict = next(
  473. iter(db.query('SELECT * FROM Water_tower.users where userName ="'+username+'"')))
  474. user = models.User(**user_dict)
  475. return user
  476. def user_register(user):
  477. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  478. table = db['users']
  479. #user.password = get_password_hash(user.password)
  480. table.insert(dict(user))
  481. def get_password_hash(password):
  482. """ 加密密碼 """
  483. return pwd_context.hash(password)
  484. def verify_password(plain_password, hashed_password):
  485. """ 驗證密碼(hashed) """
  486. return pwd_context.verify(plain_password, hashed_password)
  487. def authenticate_user(username: str, password: str):
  488. """ 連線DB,讀取使用者是否存在。 """
  489. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  490. if not check_user_exists(username): # if user don't exist
  491. return False
  492. user_dict = next(iter(db.query('SELECT * FROM Water_tower.users where userName ="'+username+'"')))
  493. user = models.User(**user_dict)
  494. #if not verify_password(password, user.password):
  495. #return False
  496. return user
  497. def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
  498. """ 創建token,並設定過期時間。 """
  499. to_encode = data.copy()
  500. if expires_delta:
  501. expire = datetime.utcnow() + expires_delta
  502. else:
  503. expire = datetime.utcnow() + timedelta(minutes=15)
  504. to_encode.update({"exp": expire})
  505. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  506. return encoded_jwt
  507. def compare_jwt_token(access_token: str, token: str):
  508. """比對jwt token"""
  509. if len(access_token) < len(token):
  510. if access_token in token:
  511. return True
  512. else :
  513. return False
  514. elif len(access_token) > len(token):
  515. if token in access_token:
  516. return True
  517. else :
  518. return False
  519. else :
  520. if token == access_token:
  521. return True
  522. else :
  523. return False
  524. def check_isAdmin(user_name:str):
  525. """查看是否為管理員"""
  526. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  527. isAdmin = None
  528. cmd = 'SELECT isAdmin FROM users WHERE userName = "'+user_name+'"'
  529. for row in db.query(cmd) :
  530. isAdmin = row['isAdmin']
  531. if isAdmin== None:
  532. return "no user"
  533. return isAdmin
  534. def check_role_type(user_name:str)->int:
  535. """查看使用者權限"""
  536. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  537. cmd = 'SELECT user_role.role_id FROM `users` JOIN `user_role` ON `users`.id = `user_role`.user_id where `users`.username = "'+user_name+'"'
  538. role_type = None
  539. for row in db.query(cmd) :
  540. role_type = row['role_id']
  541. return role_type
  542. def check_role_acl(role:int):
  543. """查看權限"""
  544. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  545. cmd = 'SELECT * FROM role_acl where role_id = '+str(role)
  546. result = []
  547. for row in db.query(cmd) :
  548. dic ={}
  549. for col_name in db['role_acl'].columns:
  550. dic[col_name] = row[col_name]
  551. if dic != {}:
  552. result.append(dic)
  553. return result
  554. def get_role_name(role_id:int):
  555. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  556. cmd = 'SELECT * FROM role where id = '+str(role_id)
  557. role:str
  558. for row in db.query(cmd) :
  559. role = row['name']
  560. return role
  561. def get_user_under_organization(user_name:str):
  562. """查看所屬公司"""
  563. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  564. user_role = check_role_type(user_name)
  565. #print(user_name,user_role)
  566. cmd = 'SELECT * FROM organization'
  567. result = []
  568. if int(user_role) == 1 :
  569. num=0
  570. for row in db.query(cmd) :
  571. company = row['Company']
  572. factory = row['Factory']
  573. department = row['Department']
  574. result.append({})
  575. cmd2 = 'SELECT TowerGroupCode FROM device WHERE CompanyCode = "' + company + '" AND FactoryCode = "' + factory + '" AND DepartmentCode = "' + department + '"'
  576. group = []
  577. for row2 in db.query(cmd2):
  578. if row2['TowerGroupCode'] not in group :
  579. group.append(row2['TowerGroupCode'])
  580. result[num] = {'company':company,'factory':factory,'department':department,'group':group,'able':1}
  581. num = num +1
  582. elif int(user_role) == 2:
  583. cmd2 = 'SELECT company FROM user WHERE user.username = '+user_name
  584. company_able:str
  585. num = 0
  586. for row in db.query(cmd2) :
  587. company_able = row['company']
  588. for row in db.query(cmd) :
  589. company = row['Company']
  590. factory = row['Factory']
  591. department = row['Department']
  592. cmd3 = 'SELECT TowerGroupCode FROM device WHERE CompanyCode = "' + company + '" AND FactoryCode = "' + factory + '" AND DepartmentCode = "' + department + '"'
  593. group = []
  594. for row2 in db.query(cmd3):
  595. group.append(row2['TowerGroupCode'])
  596. if company == company_able:
  597. result[num] = {'company':company,'factory':factory,'department':department,'group':group,'able':1}
  598. else:
  599. result[num] = {'company':company,'factory':factory,'department':department,'group':group,'able':0}
  600. num = num +1
  601. elif int(user_role) == 3:
  602. cmd2 = 'SELECT company,factory FROM users WHERE users.username = '+user_name
  603. company_able:str
  604. factory_able:str
  605. num = 0
  606. for row in db.query(cmd2) :
  607. company = row['company']
  608. factory = row['factory']
  609. for row in db.query(cmd) :
  610. company = row['Company']
  611. factory = row['Factory']
  612. department = row['Department']
  613. cmd3 = 'SELECT TowerGroupCode FROM device WHERE CompanyCode = "' + company + '" AND FactoryCode = "' + factory + '" AND DepartmentCode = "' + department + '"'
  614. group = []
  615. for row2 in db.query(cmd3):
  616. group.append(row2['TowerGroupCode'])
  617. if company == company_able and factory==factory_able:
  618. result[num] = {'company':company,'factory':factory,'department':department,'group':group,'able':1}
  619. else:
  620. result[num] = {'company':company,'factory':factory,'department':department,'group':group,'able':0}
  621. num=num+1
  622. elif int(user_role) == 4:
  623. cmd2 = 'SELECT company,factory,department FROM users WHERE username = '+user_name
  624. company_able:str
  625. factory_able:str
  626. department_able:str
  627. num = 0
  628. for row in db.query(cmd2) :
  629. company_able = row['company']
  630. factory_able = row['factory']
  631. department_able = row['Department']
  632. for row in db.query(cmd) :
  633. company = row['Company']
  634. factory = row['Factory']
  635. department = row['Department']
  636. cmd3 = 'SELECT TowerGroupCode FROM device WHERE CompanyCode = "' + company + '" AND FactoryCode = "' + factory + '" AND DepartmentCode = "' + department + '"'
  637. group = []
  638. for row2 in db.query(cmd3):
  639. group.append(row2['TowerGroupCode'])
  640. if company == company_able and factory==factory_able and department==department_able:
  641. result[num] = {'company':company,'factory':factory,'department':department,'group':group,'able':1}
  642. else:
  643. result[num] = {'company':company,'factory':factory,'department':department,'group':group,'able':1}
  644. num = num +1
  645. else :
  646. result =[ {'msg':"error"}]
  647. return result
  648. def get_user_id(user_name:str):
  649. """獲取user id"""
  650. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  651. cmd = 'SELECT id FROM `users` where username = "'+user_name+'"'
  652. id = None
  653. for row in db.query(cmd) :
  654. id = row['id']
  655. return id
  656. def get_user_name(user_id:int):
  657. """獲取user name"""
  658. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  659. cmd = 'SELECT username FROM `users` where id = "'+user_id+'"'
  660. id = None
  661. for row in db.query(cmd) :
  662. id = row['username']
  663. return id
  664. def get_modul_name(modul_id:str):
  665. """獲取modul名稱"""
  666. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  667. cmd = 'SELECT moduleName FROM `module` where id = "'+modul_id+'"'
  668. modul_name = None
  669. for row in db.query(cmd) :
  670. modul_name = row['moduleName']
  671. return modul_name
  672. def get_tower_info(tower_id:str):
  673. """獲取水塔資料"""
  674. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  675. cmd = 'SELECT * FROM `record_dcs` where device_id = "'+tower_id+'"'
  676. result ={'DCS':{},'Fan':{},'Moter':{}}
  677. for row in db.query(cmd) :
  678. result['DCS'][row['key']]=row['value']
  679. cmd = 'SELECT * FROM `record_tower` where device_id = "'+tower_id+'"'
  680. for row in db.query(cmd) :
  681. result['Fan'][row['key']]=row['value']
  682. result['Moter'] = []
  683. cmd = 'SELECT * FROM `vibration` where device_id = "'+tower_id+'"'
  684. for row in db.query(cmd) :
  685. result['Moter'].append({'channel_name':row['channelName'],'Vrms':row['DataValue'],'CV' :row['CVIndex'],'threshold':row['threshold']})
  686. return result
  687. def get_tower(company:str,factory:str,department:str,towerGroup:str):
  688. towergroup_arr =[]
  689. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  690. cmd = 'SELECT id FROM `device` where CompanyCode = "'+company+'" AND FactoryCode = "' +factory+'" AND DepartmentCode = "'+department+'" AND TowerGroupCode = "' + towerGroup + '"'
  691. for row in db.query(cmd) :
  692. towergroup_arr.append(row['id'])
  693. return towergroup_arr