main.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  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[row['username']] = {'isAdmin':row['isAdmin'],'roleType':check_role_acl(row['username'])}
  216. result = json.dumps(json_dic,ensure_ascii=False)
  217. current_user = Authorize.get_jwt_subject()
  218. return result
  219. @app.get('/member/edit', response_class=HTMLResponse)
  220. async def login(request: Request, Authorize: AuthJWT = Depends()):
  221. try:
  222. Authorize.jwt_required()
  223. except Exception as e:
  224. print(e)
  225. return RedirectResponse('/login')
  226. return templates.TemplateResponse(name='member_edit_test.html', context={'request': request})
  227. @app.get('/member_delete', response_class=HTMLResponse)
  228. async def login(request: Request, Authorize: AuthJWT = Depends()):
  229. try:
  230. Authorize.jwt_required()
  231. except Exception as e:
  232. print(e)
  233. return RedirectResponse('/login')
  234. return templates.TemplateResponse(name='delete_member_test2.html', context={'request': request})
  235. @app.post('/member_delete')
  236. async def delete_member(request: Request):
  237. """刪除成員"""
  238. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  239. del_user = models.del_user(**await request.form())
  240. delete_name = del_user.del_name
  241. statement = 'SELECT * FROM users'
  242. current_user = ''
  243. for row in db.query(statement):
  244. if row['token'] != None :
  245. if compare_jwt_token(row['token'],del_user.access_token):
  246. current_user = row['username']
  247. if current_user == '':
  248. return {'msg':'尚未登入'}
  249. statement = 'SELECT isAdmin FROM users WHERE userName = "'+current_user+'"'
  250. for row in db.query(statement):
  251. if row['isAdmin']!=1:
  252. return {'msg': ' 你沒有權限'}
  253. current_user_roleType = check_role_type(current_user)
  254. del_user_roleType = check_role_type(delete_name)
  255. if del_user_roleType == None:
  256. return {'msg':'不存在使用者'}
  257. elif current_user_roleType>del_user_roleType or current_user_roleType==del_user_roleType:
  258. return {'msg': ' 你沒有權限'}
  259. else :
  260. table = db['users']
  261. table.delete(username=delete_name)
  262. return {'msg': ' 成功刪除'}
  263. @app.get('/member_authority/{edit_one}', response_class=HTMLResponse)
  264. async def member_authority(request:Request,edit_one: int,Authorize: AuthJWT = Depends()):
  265. """設定成員權限"""
  266. try:
  267. Authorize.jwt_required()
  268. except Exception as e:
  269. print(e)
  270. return RedirectResponse('/login')
  271. context = {'request': request}
  272. current_user = Authorize.get_jwt_subject()
  273. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  274. statement = check_isAdmin(current_user)
  275. if statement == "no user":
  276. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':'no user' })
  277. elif statement == 0:
  278. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':"沒有權限" })
  279. current_user_roleType = check_role_type(current_user)
  280. if edit_one == None:
  281. return templates.TemplateResponse(name='notice.html', context={'"request":request,msg':'no role' })
  282. elif int(current_user_roleType)>int(edit_one) or int(current_user_roleType)==int(edit_one):
  283. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':"沒有權限" })
  284. result = check_role_acl(edit_one)
  285. if result == []:
  286. cmd = 'SELECT id FROM module'
  287. for row in db.query(cmd):
  288. dic_tmp = {'id':0,'isView':0,'isAdd':0 ,'isEdit':0,'isDel':0,'role_id' : edit_one}
  289. context[get_modul_name(row['id']) ] = dic_tmp
  290. else:
  291. for dic in result:
  292. modul_name = get_modul_name(dic['module_id'])
  293. del dic['module_id']
  294. context[modul_name ] = dic
  295. return templates.TemplateResponse(name='member_authority_test.html', context=context)
  296. @app.post('/member_authority')
  297. async def member_authority(request: Request):
  298. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  299. edit_one = models.user_authority(**await request.form())
  300. statement = 'SELECT * FROM users'
  301. current_user = ''
  302. for row in db.query(statement):
  303. if row['token'] != None :
  304. if compare_jwt_token(row['token'],edit_one.access_token):
  305. current_user = row['username']
  306. if current_user == '':
  307. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':'尚未登入'})
  308. statement = check_isAdmin(current_user)
  309. if statement == "no user":
  310. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':statement })
  311. elif statement == 0:
  312. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':'你沒有權限' })
  313. current_user_roleType = check_role_type(current_user)
  314. edit_one_roleType = edit_one.role_id
  315. if current_user_roleType>edit_one_roleType or current_user_roleType==edit_one_roleType:
  316. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg': ' 你沒有權限'})
  317. else :
  318. row = ['ai_prediction' ,'channel' ,'device', 'event', 'index' ,'performance', 'record', 'setting_device' ,'setting_system','tower']
  319. if check_role_acl(edit_one.role_id) == []:
  320. for module in row :
  321. new_dict = edit_one.get_acl_from_module_name(module)
  322. new_dict["id"]= pymysql.NULL
  323. table = db['role_acl']
  324. table.insert(new_dict)
  325. else:
  326. for module in row :
  327. new_dict = edit_one.get_acl_from_module_name(module)
  328. table = db['role_acl']
  329. table.update(new_dict, ['id'])
  330. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg': '成功更改權限'})
  331. # 溫度API
  332. @app.get('/temperature')
  333. async def get_temperatures():
  334. """ 撈DB溫度 """
  335. return {'hot_water': 30.48, 'cold_water': 28.10, 'wet_ball': 25.14}
  336. @app.post("/example")
  337. async def example(request: Request,Authorize: AuthJWT = Depends()):
  338. try:
  339. Authorize.jwt_required()
  340. except Exception as e:
  341. print(e)
  342. current_user = Authorize.get_jwt_subject()
  343. #form_data = await request.form()
  344. print( current_user)
  345. return current_user
  346. @app.post('/user')
  347. def user(Authorize: AuthJWT = Depends()):
  348. Authorize.jwt_required()
  349. current_user = Authorize.get_jwt_subject()
  350. return {"user": current_user}
  351. @app.get("/example", response_class=HTMLResponse)
  352. async def example(request: Request,Authorize: AuthJWT = Depends()):
  353. try:
  354. Authorize.jwt_required()
  355. except Exception as e:
  356. print(e)
  357. return RedirectResponse('/login')
  358. current_user = Authorize.get_jwt_subject()
  359. print( current_user)
  360. return current_user
  361. @app.get('/health')
  362. async def get_health(date: str):
  363. """ 撈健康指標、預設健康指標 """
  364. date = str(datetime.strptime(date, "%Y-%m-%d"))[:10]
  365. print(date)
  366. print(str(datetime.today()))
  367. print(str(datetime.today()-timedelta(days=1)))
  368. fake_data = {
  369. str(datetime.today())[:10]: {'curr_health': 0.7, 'pred_health': 0.8},
  370. str(datetime.today()-timedelta(days=1))[:10]: {'curr_health': 0.6, 'pred_health': 0.7},
  371. }
  372. return fake_data[date]
  373. @app.get('/history_data')
  374. async def get_history(time_end: str):
  375. """ 透過終點時間,抓取歷史資料。 """
  376. date = str(datetime.strptime(time_end, "%Y-%m-%d"))[:10]
  377. print(date)
  378. print(str(datetime.today()))
  379. print(str(datetime.today()-timedelta(days=1)))
  380. fake_data = {
  381. str(datetime.today())[:10]: {
  382. 'curr_history': {
  383. 'RPM_1X': list(np.random.rand(13)),
  384. 'RPM_2X': list(np.random.rand(13)),
  385. 'RPM_3X': list(np.random.rand(13)),
  386. 'RPM_4X': list(np.random.rand(13)),
  387. 'RPM_5X': list(np.random.rand(13)),
  388. 'RPM_6X': list(np.random.rand(13)),
  389. 'RPM_7X': list(np.random.rand(13)),
  390. 'RPM_8X': list(np.random.rand(13)),
  391. 'Gear_1X': list(np.random.rand(13)),
  392. 'Gear_2X': list(np.random.rand(13)),
  393. 'Gear_3X': list(np.random.rand(13)),
  394. 'Gear_4X': list(np.random.rand(13)),
  395. },
  396. 'past_history': {
  397. 'RPM_1X': list(np.random.rand(13)),
  398. 'RPM_2X': list(np.random.rand(13)),
  399. 'RPM_3X': list(np.random.rand(13)),
  400. 'RPM_4X': list(np.random.rand(13)),
  401. 'RPM_5X': list(np.random.rand(13)),
  402. 'RPM_6X': list(np.random.rand(13)),
  403. 'RPM_7X': list(np.random.rand(13)),
  404. 'RPM_8X': list(np.random.rand(13)),
  405. 'Gear_1X': list(np.random.rand(13)),
  406. 'Gear_2X': list(np.random.rand(13)),
  407. 'Gear_3X': list(np.random.rand(13)),
  408. 'Gear_4X': list(np.random.rand(13)),
  409. }
  410. },
  411. str(datetime.today()-timedelta(days=1))[:10]: {
  412. 'curr_history': {
  413. 'RPM_1X': list(np.random.rand(13)),
  414. 'RPM_2X': list(np.random.rand(13)),
  415. 'RPM_3X': list(np.random.rand(13)),
  416. 'RPM_4X': list(np.random.rand(13)),
  417. 'RPM_5X': list(np.random.rand(13)),
  418. 'RPM_6X': list(np.random.rand(13)),
  419. 'RPM_7X': list(np.random.rand(13)),
  420. 'RPM_8X': list(np.random.rand(13)),
  421. 'Gear_1X': list(np.random.rand(13)),
  422. 'Gear_2X': list(np.random.rand(13)),
  423. 'Gear_3X': list(np.random.rand(13)),
  424. 'Gear_4X': list(np.random.rand(13)),
  425. },
  426. 'past_history': {
  427. 'RPM_1X': list(np.random.rand(13)),
  428. 'RPM_2X': list(np.random.rand(13)),
  429. 'RPM_3X': list(np.random.rand(13)),
  430. 'RPM_4X': list(np.random.rand(13)),
  431. 'RPM_5X': list(np.random.rand(13)),
  432. 'RPM_6X': list(np.random.rand(13)),
  433. 'RPM_7X': list(np.random.rand(13)),
  434. 'RPM_8X': list(np.random.rand(13)),
  435. 'Gear_1X': list(np.random.rand(13)),
  436. 'Gear_2X': list(np.random.rand(13)),
  437. 'Gear_3X': list(np.random.rand(13)),
  438. 'Gear_4X': list(np.random.rand(13)),
  439. }
  440. },
  441. }
  442. return fake_data[date]
  443. # Login funtion part
  444. def check_user_exists(username):
  445. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  446. if int(next(iter(db.query('SELECT COUNT(*) FROM Water_tower.users WHERE userName = "'+username+'"')))['COUNT(*)']) > 0:
  447. return True
  448. else:
  449. return False
  450. def get_user(username: str):
  451. """ 取得使用者資訊(Model) """
  452. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  453. if not check_user_exists(username): # if user don't exist
  454. return False
  455. user_dict = next(
  456. iter(db.query('SELECT * FROM Water_tower.users where userName ="'+username+'"')))
  457. user = models.User(**user_dict)
  458. return user
  459. def user_register(user):
  460. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  461. table = db['users']
  462. #user.password = get_password_hash(user.password)
  463. table.insert(dict(user))
  464. def get_password_hash(password):
  465. """ 加密密碼 """
  466. return pwd_context.hash(password)
  467. def verify_password(plain_password, hashed_password):
  468. """ 驗證密碼(hashed) """
  469. return pwd_context.verify(plain_password, hashed_password)
  470. def authenticate_user(username: str, password: str):
  471. """ 連線DB,讀取使用者是否存在。 """
  472. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  473. if not check_user_exists(username): # if user don't exist
  474. return False
  475. user_dict = next(iter(db.query('SELECT * FROM Water_tower.users where userName ="'+username+'"')))
  476. user = models.User(**user_dict)
  477. #if not verify_password(password, user.password):
  478. #return False
  479. return user
  480. def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
  481. """ 創建token,並設定過期時間。 """
  482. to_encode = data.copy()
  483. if expires_delta:
  484. expire = datetime.utcnow() + expires_delta
  485. else:
  486. expire = datetime.utcnow() + timedelta(minutes=15)
  487. to_encode.update({"exp": expire})
  488. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  489. return encoded_jwt
  490. def compare_jwt_token(access_token: str, token: str):
  491. """比對jwt token"""
  492. if len(access_token) < len(token):
  493. if access_token in token:
  494. return True
  495. else :
  496. return False
  497. elif len(access_token) > len(token):
  498. if token in access_token:
  499. return True
  500. else :
  501. return False
  502. else :
  503. if token == access_token:
  504. return True
  505. else :
  506. return False
  507. def check_isAdmin(user_name:str):
  508. """查看是否為管理員"""
  509. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  510. isAdmin = None
  511. cmd = 'SELECT isAdmin FROM users WHERE userName = "'+user_name+'"'
  512. for row in db.query(cmd) :
  513. isAdmin = row['isAdmin']
  514. if isAdmin== None:
  515. return "no user"
  516. return isAdmin
  517. def check_role_type(user_name:str)->int:
  518. """查看使用者權限"""
  519. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  520. cmd = 'SELECT user_role.role_id FROM `users` JOIN `user_role` ON `users`.id = `user_role`.user_id where `users`.username = "'+user_name+'"'
  521. role_type = None
  522. for row in db.query(cmd) :
  523. role_type = row['role_id']
  524. return role_type
  525. def check_role_acl(role:int):
  526. """查看權限"""
  527. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  528. cmd = 'SELECT * FROM role_acl where role_id = '+str(role)
  529. result = []
  530. for row in db.query(cmd) :
  531. dic ={}
  532. for col_name in db['role_acl'].columns:
  533. dic[col_name] = row[col_name]
  534. if dic != {}:
  535. result.append(dic)
  536. return result
  537. def get_user_under_organization(user_name:str):
  538. """查看所屬公司"""
  539. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  540. user_role = check_role_type(user_name)
  541. #print(user_name,user_role)
  542. cmd = 'SELECT * FROM organization'
  543. result = []
  544. if int(user_role) == 1 :
  545. num=0
  546. for row in db.query(cmd) :
  547. company = row['Company']
  548. factory = row['Factory']
  549. department = row['Department']
  550. result.append({})
  551. cmd2 = 'SELECT TowerGroupCode FROM device WHERE CompanyCode = "' + company + '" AND FactoryCode = "' + factory + '" AND DepartmentCode = "' + department + '"'
  552. group = []
  553. for row2 in db.query(cmd2):
  554. if row2['TowerGroupCode'] not in group :
  555. group.append(row2['TowerGroupCode'])
  556. result[num] = {'company':company,'factory':factory,'department':department,'group':group,'able':1}
  557. num = num +1
  558. elif int(user_role) == 2:
  559. cmd2 = 'SELECT company FROM user WHERE user.username = '+user_name
  560. company_able:str
  561. num = 0
  562. for row in db.query(cmd2) :
  563. company_able = row['company']
  564. for row in db.query(cmd) :
  565. company = row['Company']
  566. factory = row['Factory']
  567. department = row['Department']
  568. cmd3 = 'SELECT TowerGroupCode FROM device WHERE CompanyCode = "' + company + '" AND FactoryCode = "' + factory + '" AND DepartmentCode = "' + department + '"'
  569. group = []
  570. for row2 in db.query(cmd3):
  571. group.append(row2['TowerGroupCode'])
  572. if company == company_able:
  573. result[num] = {'company':company,'factory':factory,'department':department,'group':group,'able':1}
  574. else:
  575. result[num] = {'company':company,'factory':factory,'department':department,'group':group,'able':0}
  576. num = num +1
  577. elif int(user_role) == 3:
  578. cmd2 = 'SELECT company,factory FROM users WHERE users.username = '+user_name
  579. company_able:str
  580. factory_able:str
  581. num = 0
  582. for row in db.query(cmd2) :
  583. company = row['company']
  584. factory = row['factory']
  585. for row in db.query(cmd) :
  586. company = row['Company']
  587. factory = row['Factory']
  588. department = row['Department']
  589. cmd3 = 'SELECT TowerGroupCode FROM device WHERE CompanyCode = "' + company + '" AND FactoryCode = "' + factory + '" AND DepartmentCode = "' + department + '"'
  590. group = []
  591. for row2 in db.query(cmd3):
  592. group.append(row2['TowerGroupCode'])
  593. if company == company_able and factory==factory_able:
  594. result[num] = {'company':company,'factory':factory,'department':department,'group':group,'able':1}
  595. else:
  596. result[num] = {'company':company,'factory':factory,'department':department,'group':group,'able':0}
  597. num=num+1
  598. elif int(user_role) == 4:
  599. cmd2 = 'SELECT company,factory,department FROM users WHERE username = '+user_name
  600. company_able:str
  601. factory_able:str
  602. department_able:str
  603. num = 0
  604. for row in db.query(cmd2) :
  605. company_able = row['company']
  606. factory_able = row['factory']
  607. department_able = row['Department']
  608. for row in db.query(cmd) :
  609. company = row['Company']
  610. factory = row['Factory']
  611. department = row['Department']
  612. cmd3 = 'SELECT TowerGroupCode FROM device WHERE CompanyCode = "' + company + '" AND FactoryCode = "' + factory + '" AND DepartmentCode = "' + department + '"'
  613. group = []
  614. for row2 in db.query(cmd3):
  615. group.append(row2['TowerGroupCode'])
  616. if company == company_able and factory==factory_able and department==department_able:
  617. result[num] = {'company':company,'factory':factory,'department':department,'group':group,'able':1}
  618. else:
  619. result[num] = {'company':company,'factory':factory,'department':department,'group':group,'able':1}
  620. num = num +1
  621. else :
  622. result =[ {'msg':"error"}]
  623. return result
  624. def get_user_id(user_name:str):
  625. """獲取user id"""
  626. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  627. cmd = 'SELECT id FROM `users` where username = "'+user_name+'"'
  628. id = None
  629. for row in db.query(cmd) :
  630. id = row['id']
  631. return id
  632. def get_user_name(user_id:int):
  633. """獲取user name"""
  634. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  635. cmd = 'SELECT username FROM `users` where id = "'+user_id+'"'
  636. id = None
  637. for row in db.query(cmd) :
  638. id = row['username']
  639. return id
  640. def get_modul_name(modul_id:str):
  641. """獲取modul名稱"""
  642. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  643. cmd = 'SELECT moduleName FROM `module` where id = "'+modul_id+'"'
  644. modul_name = None
  645. for row in db.query(cmd) :
  646. modul_name = row['moduleName']
  647. return modul_name
  648. def get_tower_info(tower_id:str):
  649. """獲取水塔資料"""
  650. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  651. cmd = 'SELECT * FROM `record_dcs` where device_id = "'+tower_id+'"'
  652. result ={'DCS':{},'Fan':{},'Moter':{}}
  653. for row in db.query(cmd) :
  654. result['DCS'][row['key']]=row['value']
  655. cmd = 'SELECT * FROM `record_tower` where device_id = "'+tower_id+'"'
  656. for row in db.query(cmd) :
  657. result['Fan'][row['key']]=row['value']
  658. cmd = 'SELECT * FROM `vibration` where device_id = "'+tower_id+'"'
  659. for row in db.query(cmd) :
  660. result['Moter'][row['channelName']]={'Vrms':row['DataValue'],'CV' :row['CVIndex']}
  661. return result
  662. def get_tower(company:str,factory:str,department:str,towerGroup:str):
  663. towergroup_arr =[]
  664. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  665. cmd = 'SELECT id FROM `device` where CompanyCode = "'+company+'" AND FactoryCode = "' +factory+'" AND DepartmentCode = "'+department+'" AND TowerGroupCode = "' + towerGroup + '"'
  666. for row in db.query(cmd) :
  667. towergroup_arr.append(row['id'])
  668. return towergroup_arr