main.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  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 pymysql
  19. from pymysql import cursors
  20. import dataset
  21. from passlib import context
  22. import models
  23. from random import randint
  24. # authorize
  25. from passlib.context import CryptContext
  26. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  27. import jwt
  28. from fastapi_jwt_auth import AuthJWT
  29. from fastapi_jwt_auth.exceptions import AuthJWTException
  30. from fastapi.security import OAuth2AuthorizationCodeBearer, OAuth2PasswordRequestForm
  31. import numpy as np
  32. import mysql.connector
  33. pymysql.install_as_MySQLdb()
  34. db_settings = {
  35. "host": "db.ptt.cx",
  36. "port": 3306,
  37. "user": "choozmo",
  38. "password": "pAssw0rd",
  39. "db": "Water_tower",
  40. "charset": "utf8mb4"
  41. }
  42. # app
  43. app = FastAPI()
  44. app.add_middleware(
  45. CORSMiddleware,
  46. allow_origins=["*"],
  47. allow_credentials=True,
  48. allow_methods=["*"],
  49. allow_headers=["*"],
  50. )
  51. SECRET_KEY = "df2f77bd544240801a048bd4293afd8eeb7fff3cb7050e42c791db4b83ebadcd"
  52. ALGORITHM = "HS256"
  53. ACCESS_TOKEN_EXPIRE_MINUTES = 3000
  54. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  55. #
  56. app.mount(path='/templates', app=StaticFiles(directory='templates'), name='templates')
  57. app.mount(path='/static', app=StaticFiles(directory='static'), name='static ')
  58. #
  59. templates = Jinja2Templates(directory='templates')
  60. @AuthJWT.load_config
  61. def get_config():
  62. return models.Settings()
  63. # view
  64. @app.get('/', response_class=HTMLResponse)
  65. async def index(request: Request):
  66. print(request)
  67. return templates.TemplateResponse(name='index.html', context={'request': request})
  68. @app.get('/login', response_class=HTMLResponse)
  69. async def login(request: Request):
  70. return templates.TemplateResponse(name='login_test.html', context={'request': request})
  71. @app.post("/login")
  72. async def login_for_access_token(request: Request, form_data: OAuth2PasswordRequestForm = Depends(), Authorize: AuthJWT = Depends()):
  73. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  74. user = authenticate_user(form_data.username, form_data.password)
  75. if not user:
  76. raise HTTPException(
  77. status_code=status.HTTP_401_UNAUTHORIZED,
  78. detail="Incorrect username or password",
  79. headers={"WWW-Authenticate": "Bearer"},
  80. )
  81. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  82. access_token = create_access_token(
  83. data={"sub": user.username}, expires_delta=access_token_expires
  84. )
  85. table = db['users']
  86. user.token = access_token
  87. print(user)
  88. table.update(dict(user), ['username'],['password'])
  89. access_token = Authorize.create_access_token(subject=user.username)
  90. refresh_token = Authorize.create_refresh_token(subject=user.username)
  91. Authorize.set_access_cookies(access_token)
  92. Authorize.set_refresh_cookies(refresh_token)
  93. #return templates.TemplateResponse("home.html", {"request": request, "msg": 'Login'})
  94. return {"access_token": access_token, "token_type": "bearer"} # 回傳token給前端
  95. @app.get('/register', response_class=HTMLResponse)
  96. async def login(request: Request):
  97. return templates.TemplateResponse(name='rigister_test.html', context={'request': request})
  98. @app.post('/register')
  99. async def register(request: Request, form_data: OAuth2PasswordRequestForm = Depends()):
  100. user = models.User(**await request.form())
  101. print(form_data.username, form_data.password, user)
  102. user.id = randint(1000, 9999)
  103. user.isAdmin = 0 #預設為非管理者
  104. user.roleType = 0 #預設為employee
  105. # 密碼加密
  106. #user.password = get_password_hash(user.password)
  107. # 存入DB
  108. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  109. user_table = db['users']
  110. user_table.insert(dict(user))
  111. # 跳轉頁面至登入
  112. return templates.TemplateResponse(name='login.html', context={'request': request})
  113. @app.get('/home', response_class=HTMLResponse)
  114. async def home(request: Request):
  115. return templates.TemplateResponse(name='home.html', context={'request': request})
  116. @app.get('/tower', response_class=HTMLResponse)
  117. async def tower(request: Request, Authorize: AuthJWT = Depends()):
  118. try:
  119. Authorize.jwt_required()
  120. except Exception as e:
  121. print(e)
  122. return RedirectResponse('/login')
  123. # current_user = Authorize.get_jwt_subject()
  124. return templates.TemplateResponse(name='tower.html', context={'request': request})
  125. @app.get('/optim', response_class=HTMLResponse)
  126. async def optim(request: Request, Authorize: AuthJWT = Depends()):
  127. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  128. table=db['record_tower']
  129. temp = table.find_one(key = 'hotTemp')
  130. try:
  131. Authorize.jwt_required()
  132. except Exception as e:
  133. print(e)
  134. return RedirectResponse('/login')
  135. # current_user = Authorize.get_jwt_subject()
  136. return templates.TemplateResponse(name='optim.html',context={'request': request,"temp":temp})
  137. @app.get('/vibration', response_class=HTMLResponse)
  138. async def vibration(request: Request, Authorize: AuthJWT = Depends()):
  139. try:
  140. Authorize.jwt_required()
  141. except Exception as e:
  142. print(e)
  143. return RedirectResponse('/login')
  144. # current_user = Authorize.get_jwt_subject()
  145. return templates.TemplateResponse(name='vibration.html', context={'request': request})
  146. @app.get('/history', response_class=HTMLResponse)
  147. async def history(request: Request, Authorize: AuthJWT = Depends()):
  148. try:
  149. Authorize.jwt_required()
  150. except Exception as e:
  151. print(e)
  152. return RedirectResponse('/login')
  153. # current_user = Authorize.get_jwt_subject()
  154. return templates.TemplateResponse(name='history.html', context={'request': request})
  155. @app.get('/device', response_class=HTMLResponse)
  156. async def device(request: Request, Authorize: AuthJWT = Depends()):
  157. try:
  158. Authorize.jwt_required()
  159. except Exception as e:
  160. print(e)
  161. return RedirectResponse('/login')
  162. # current_user = Authorize.get_jwt_subject()
  163. return templates.TemplateResponse(name='device.html', context={'request': request})
  164. @app.get('/system', response_class=HTMLResponse)
  165. async def system(request: Request, Authorize: AuthJWT = Depends()):
  166. try:
  167. Authorize.jwt_required()
  168. except Exception as e:
  169. print(e)
  170. return RedirectResponse('/login')
  171. # current_user = Authorize.get_jwt_subject()
  172. return templates.TemplateResponse(name='system.html', context={'request': request})
  173. @app.get('/member', response_class=HTMLResponse)
  174. async def get_member(request: Request, Authorize: AuthJWT = Depends()):
  175. """獲取所有帳號資訊"""
  176. try:
  177. Authorize.jwt_required()
  178. except Exception as e:
  179. print(e)
  180. return RedirectResponse('/login')
  181. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  182. statement = 'SELECT id,username,isAdmin,roleType FROM users'
  183. json_dic = {}
  184. for row in db.query(statement):
  185. #print(row['id'],row['username'])
  186. json_dic[row['username']] = {'isAdmin':row['isAdmin'],'roleType':row['roleType']}
  187. result = json.dumps(json_dic,ensure_ascii=False)
  188. current_user = Authorize.get_jwt_subject()
  189. print(current_user)
  190. return result
  191. @app.get('/member/edit', response_class=HTMLResponse)
  192. async def login(request: Request, Authorize: AuthJWT = Depends()):
  193. try:
  194. Authorize.jwt_required()
  195. except Exception as e:
  196. print(e)
  197. return RedirectResponse('/login')
  198. return templates.TemplateResponse(name='member_edit_test.html', context={'request': request})
  199. @app.get('/member_delete', response_class=HTMLResponse)
  200. async def login(request: Request, Authorize: AuthJWT = Depends()):
  201. try:
  202. Authorize.jwt_required()
  203. except Exception as e:
  204. print(e)
  205. return RedirectResponse('/login')
  206. return templates.TemplateResponse(name='delete_member_test2.html', context={'request': request})
  207. @app.post('/member_delete')
  208. async def delete_member(request: Request):
  209. """刪除成員"""
  210. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  211. del_user = models.del_user(**await request.form())
  212. delete_name = del_user.del_name
  213. statement = 'SELECT * FROM users'
  214. current_user = ''
  215. for row in db.query(statement):
  216. if row['token'] != None :
  217. if compare_jwt_token(row['token'],del_user.access_token):
  218. current_user = row['username']
  219. if current_user == '':
  220. return {'msg':'尚未登入'}
  221. statement = 'SELECT isAdmin FROM users WHERE userName = "'+current_user+'"'
  222. for row in db.query(statement):
  223. if row['isAdmin']!=1:
  224. return {'msg': ' 你沒有權限'}
  225. current_user_roleType = check_role_type(current_user)
  226. del_user_roleType = check_role_type(delete_name)
  227. if del_user_roleType == None:
  228. return {'msg':'不存在使用者'}
  229. elif current_user_roleType>del_user_roleType or current_user_roleType==del_user_roleType:
  230. return {'msg': ' 你沒有權限'}
  231. else :
  232. table = db['users']
  233. table.delete(username=delete_name)
  234. return {'msg': ' 成功刪除'}
  235. @app.get('/member_authority/{edit_one}', response_class=HTMLResponse)
  236. async def member_authority(request:Request,edit_one: str,Authorize: AuthJWT = Depends()):
  237. """設定成員權限"""
  238. try:
  239. Authorize.jwt_required()
  240. except Exception as e:
  241. print(e)
  242. return RedirectResponse('/login')
  243. context = {'request': request}
  244. current_user = Authorize.get_jwt_subject()
  245. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  246. statement = check_isAdmin(current_user)
  247. if statement == "no user":
  248. return {'msg':statement }
  249. elif statement == 0:
  250. return {'msg':'你沒有權限' }
  251. current_user_roleType = check_role_type(current_user)
  252. edit_one_roleType = check_role_type(edit_one)
  253. if edit_one_roleType == None:
  254. return {'msg':'不存在使用者'}
  255. elif current_user_roleType>edit_one_roleType or current_user_roleType==edit_one_roleType:
  256. return {'msg': ' 你沒有權限'}
  257. result = check_role_acl(edit_one)
  258. if result == []:
  259. cmd = 'SELECT id FROM module'
  260. for row in db.query(cmd):
  261. dic_tmp = {'id':get_user_id(edit_one),'isView':0,'isAdd':0 ,'isEdit':0,'isDel':0,'role_id' : check_role_type(edit_one)}
  262. context[get_modul_name(row['id']) ] = dic_tmp
  263. else:
  264. for dic in result:
  265. modul_name = get_modul_name(dic['module_id'])
  266. del dic['module_id']
  267. context[modul_name ] = dic
  268. print(context)
  269. return templates.TemplateResponse(name='member_authority_test.html', context=context)
  270. @app.post('/member_authority')
  271. async def member_authority(request: Request):
  272. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  273. edit_one = models.user_authority(**await request.form())
  274. statement = 'SELECT * FROM users'
  275. current_user = ''
  276. for row in db.query(statement):
  277. if row['token'] != None :
  278. if compare_jwt_token(row['token'],edit_one.access_token):
  279. current_user = row['username']
  280. if current_user == '':
  281. return {'msg':'尚未登入'}
  282. statement = check_isAdmin(current_user)
  283. if statement == "no user":
  284. return {'msg':statement }
  285. elif statement == 0:
  286. return {'msg':'你沒有權限' }
  287. current_user_roleType = check_role_type(current_user)
  288. edit_one_roleType = edit_one.role_id
  289. if edit_one.id == None:
  290. return {'msg':'不存在使用者'}
  291. elif current_user_roleType>edit_one_roleType or current_user_roleType==edit_one_roleType:
  292. return {'msg': ' 你沒有權限'}
  293. else :
  294. row = ['ai_prediction' ,'channel' ,'device', 'event', 'index' ,'performance', 'record', 'setting_device' ,'setting_system','tower']
  295. if check_role_acl(get_user_name(edit_one.id)) == []:
  296. for module in row :
  297. new_dict = edit_one.get_acl_from_module_name(module)
  298. table = db['role_acl']
  299. table.insert(new_dict)
  300. else:
  301. for module in row :
  302. new_dict = edit_one.get_acl_from_module_name(module)
  303. table = db['role_acl']
  304. table.update(new_dict, ['id'],['module_id'])
  305. return {'msg': ' 成功更改'}
  306. # 溫度API
  307. @app.get('/temperature')
  308. async def get_temperatures():
  309. """ 撈DB溫度 """
  310. return {'hot_water': 30.48, 'cold_water': 28.10, 'wet_ball': 25.14}
  311. @app.post("/example")
  312. async def example(request: Request,Authorize: AuthJWT = Depends()):
  313. try:
  314. Authorize.jwt_required()
  315. except Exception as e:
  316. print(e)
  317. current_user = Authorize.get_jwt_subject()
  318. #form_data = await request.form()
  319. print( current_user)
  320. return current_user
  321. @app.post('/user')
  322. def user(Authorize: AuthJWT = Depends()):
  323. Authorize.jwt_required()
  324. current_user = Authorize.get_jwt_subject()
  325. return {"user": current_user}
  326. @app.get("/example", response_class=HTMLResponse)
  327. async def example(request: Request,Authorize: AuthJWT = Depends()):
  328. try:
  329. Authorize.jwt_required()
  330. except Exception as e:
  331. print(e)
  332. return RedirectResponse('/login')
  333. current_user = Authorize.get_jwt_subject()
  334. print( current_user)
  335. return current_user
  336. @app.get('/health')
  337. async def get_health(date: str):
  338. """ 撈健康指標、預設健康指標 """
  339. date = str(datetime.strptime(date, "%Y-%m-%d"))[:10]
  340. print(date)
  341. print(str(datetime.today()))
  342. print(str(datetime.today()-timedelta(days=1)))
  343. fake_data = {
  344. str(datetime.today())[:10]: {'curr_health': 0.7, 'pred_health': 0.8},
  345. str(datetime.today()-timedelta(days=1))[:10]: {'curr_health': 0.6, 'pred_health': 0.7},
  346. }
  347. return fake_data[date]
  348. @app.get('/history_data')
  349. async def get_history(time_end: str):
  350. """ 透過終點時間,抓取歷史資料。 """
  351. date = str(datetime.strptime(time_end, "%Y-%m-%d"))[:10]
  352. print(date)
  353. print(str(datetime.today()))
  354. print(str(datetime.today()-timedelta(days=1)))
  355. fake_data = {
  356. str(datetime.today())[:10]: {
  357. 'curr_history': {
  358. 'RPM_1X': list(np.random.rand(13)),
  359. 'RPM_2X': list(np.random.rand(13)),
  360. 'RPM_3X': list(np.random.rand(13)),
  361. 'RPM_4X': list(np.random.rand(13)),
  362. 'RPM_5X': list(np.random.rand(13)),
  363. 'RPM_6X': list(np.random.rand(13)),
  364. 'RPM_7X': list(np.random.rand(13)),
  365. 'RPM_8X': list(np.random.rand(13)),
  366. 'Gear_1X': list(np.random.rand(13)),
  367. 'Gear_2X': list(np.random.rand(13)),
  368. 'Gear_3X': list(np.random.rand(13)),
  369. 'Gear_4X': list(np.random.rand(13)),
  370. },
  371. 'past_history': {
  372. 'RPM_1X': list(np.random.rand(13)),
  373. 'RPM_2X': list(np.random.rand(13)),
  374. 'RPM_3X': list(np.random.rand(13)),
  375. 'RPM_4X': list(np.random.rand(13)),
  376. 'RPM_5X': list(np.random.rand(13)),
  377. 'RPM_6X': list(np.random.rand(13)),
  378. 'RPM_7X': list(np.random.rand(13)),
  379. 'RPM_8X': list(np.random.rand(13)),
  380. 'Gear_1X': list(np.random.rand(13)),
  381. 'Gear_2X': list(np.random.rand(13)),
  382. 'Gear_3X': list(np.random.rand(13)),
  383. 'Gear_4X': list(np.random.rand(13)),
  384. }
  385. },
  386. str(datetime.today()-timedelta(days=1))[:10]: {
  387. 'curr_history': {
  388. 'RPM_1X': list(np.random.rand(13)),
  389. 'RPM_2X': list(np.random.rand(13)),
  390. 'RPM_3X': list(np.random.rand(13)),
  391. 'RPM_4X': list(np.random.rand(13)),
  392. 'RPM_5X': list(np.random.rand(13)),
  393. 'RPM_6X': list(np.random.rand(13)),
  394. 'RPM_7X': list(np.random.rand(13)),
  395. 'RPM_8X': list(np.random.rand(13)),
  396. 'Gear_1X': list(np.random.rand(13)),
  397. 'Gear_2X': list(np.random.rand(13)),
  398. 'Gear_3X': list(np.random.rand(13)),
  399. 'Gear_4X': list(np.random.rand(13)),
  400. },
  401. 'past_history': {
  402. 'RPM_1X': list(np.random.rand(13)),
  403. 'RPM_2X': list(np.random.rand(13)),
  404. 'RPM_3X': list(np.random.rand(13)),
  405. 'RPM_4X': list(np.random.rand(13)),
  406. 'RPM_5X': list(np.random.rand(13)),
  407. 'RPM_6X': list(np.random.rand(13)),
  408. 'RPM_7X': list(np.random.rand(13)),
  409. 'RPM_8X': list(np.random.rand(13)),
  410. 'Gear_1X': list(np.random.rand(13)),
  411. 'Gear_2X': list(np.random.rand(13)),
  412. 'Gear_3X': list(np.random.rand(13)),
  413. 'Gear_4X': list(np.random.rand(13)),
  414. }
  415. },
  416. }
  417. return fake_data[date]
  418. # Login funtion part
  419. def check_user_exists(username):
  420. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  421. if int(next(iter(db.query('SELECT COUNT(*) FROM Water_tower.users WHERE userName = "'+username+'"')))['COUNT(*)']) > 0:
  422. return True
  423. else:
  424. return False
  425. def get_user(username: str):
  426. """ 取得使用者資訊(Model) """
  427. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  428. if not check_user_exists(username): # if user don't exist
  429. return False
  430. user_dict = next(
  431. iter(db.query('SELECT * FROM Water_tower.users where userName ="'+username+'"')))
  432. user = models.User(**user_dict)
  433. return user
  434. def user_register(user):
  435. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  436. table = db['users']
  437. #user.password = get_password_hash(user.password)
  438. table.insert(dict(user))
  439. def get_password_hash(password):
  440. """ 加密密碼 """
  441. return pwd_context.hash(password)
  442. def verify_password(plain_password, hashed_password):
  443. """ 驗證密碼(hashed) """
  444. return pwd_context.verify(plain_password, hashed_password)
  445. def authenticate_user(username: str, password: str):
  446. """ 連線DB,讀取使用者是否存在。 """
  447. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  448. if not check_user_exists(username): # if user don't exist
  449. return False
  450. user_dict = next(iter(db.query('SELECT * FROM Water_tower.users where userName ="'+username+'"')))
  451. user = models.User(**user_dict)
  452. #if not verify_password(password, user.password):
  453. #return False
  454. return user
  455. def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
  456. """ 創建token,並設定過期時間。 """
  457. to_encode = data.copy()
  458. if expires_delta:
  459. expire = datetime.utcnow() + expires_delta
  460. else:
  461. expire = datetime.utcnow() + timedelta(minutes=15)
  462. to_encode.update({"exp": expire})
  463. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  464. return encoded_jwt
  465. def compare_jwt_token(access_token: str, token: str):
  466. """比對jwt token"""
  467. if len(access_token) < len(token):
  468. if access_token in token:
  469. return True
  470. else :
  471. return False
  472. elif len(access_token) > len(token):
  473. if token in access_token:
  474. return True
  475. else :
  476. return False
  477. else :
  478. if token == access_token:
  479. return True
  480. else :
  481. return False
  482. def check_isAdmin(user_name:str):
  483. """查看是否為管理員"""
  484. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  485. isAdmin = None
  486. cmd = 'SELECT isAdmin FROM users WHERE userName = "'+user_name+'"'
  487. for row in db.query(cmd) :
  488. isAdmin = row['isAdmin']
  489. if isAdmin== None:
  490. return "no user"
  491. return isAdmin
  492. def check_role_type(user_name:str):
  493. """查看使用者權限"""
  494. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  495. cmd = 'SELECT role.id FROM `users` JOIN `role` ON `users`.roleType = `role`.name where `users`.username = "'+user_name+'"'
  496. role_type = None
  497. for row in db.query(cmd) :
  498. role_type = row['id']
  499. return role_type
  500. def check_role_acl(user_name:str):
  501. """查看權限"""
  502. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  503. cmd = 'SELECT role_acl.* FROM `users` JOIN `role_acl` ON `users`.id = `role_acl`.user_id where `users`.username = "'+user_name+'"'
  504. result = []
  505. for row in db.query(cmd) :
  506. dic ={}
  507. for col_name in db['role_acl'].columns:
  508. dic[col_name] = row[col_name]
  509. if dic != {}:
  510. result.append(dic)
  511. return result
  512. def get_user_id(user_name:str):
  513. """獲取user id"""
  514. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  515. cmd = 'SELECT id FROM `users` where username = "'+user_name+'"'
  516. id = None
  517. for row in db.query(cmd) :
  518. id = row['id']
  519. return id
  520. def get_user_name(user_id:int):
  521. """獲取user id"""
  522. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  523. cmd = 'SELECT username FROM `users` where id = "'+user_id+'"'
  524. id = None
  525. for row in db.query(cmd) :
  526. id = row['username']
  527. return id
  528. def get_modul_name(modul_id:str):
  529. """獲取modul名稱"""
  530. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  531. cmd = 'SELECT moduleName FROM `module` where id = "'+modul_id+'"'
  532. modul_name = None
  533. for row in db.query(cmd) :
  534. modul_name = row['moduleName']
  535. return modul_name