testoauth.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import json
  2. from fastapi import FastAPI
  3. from starlette.config import Config
  4. from starlette.requests import Request
  5. from starlette.middleware.sessions import SessionMiddleware
  6. from starlette.responses import HTMLResponse, RedirectResponse
  7. from authlib.integrations.starlette_client import OAuth, OAuthError
  8. from fastapi.staticfiles import StaticFiles
  9. import jinja2
  10. import gen_designer_report
  11. import os
  12. app = FastAPI()
  13. app.add_middleware(SessionMiddleware, secret_key="!secret")
  14. config = Config('.env')
  15. #config.
  16. #config['GOOGLE_CLIENT_ID']='813384606753-40sct043k48uaveu8r2e8m7t9u885cbs.apps.googleusercontent.com'
  17. #config['GOOGLE_CLIENT_SECRET']='jvKKjKxCr9kUnn2e5niCQVTq'
  18. #Config('.env')
  19. oauth = OAuth(config)
  20. app.mount("/static", StaticFiles(directory="static"), name="static")
  21. CONF_URL = 'https://accounts.google.com/.well-known/openid-configuration'
  22. oauth.register(
  23. name='google',
  24. server_metadata_url=CONF_URL,
  25. client_kwargs={
  26. 'scope': 'openid email profile'
  27. }
  28. )
  29. fname=os.path.abspath(__file__)
  30. elmts=fname.split(os.path.sep)
  31. path2=os.path.sep.join(elmts[0:-1])
  32. keysdir=path2+os.path.sep+'static'+os.path.sep
  33. templateLoader = jinja2.FileSystemLoader(searchpath=keysdir)
  34. templateEnv = jinja2.Environment(loader=templateLoader)
  35. @app.route('/')
  36. async def homepage(request: Request):
  37. user = request.session.get('user')
  38. if user:
  39. data = json.dumps(user)
  40. html = (
  41. f'<pre>{data}</pre>'
  42. '<a href="/logout">logout</a>'
  43. )
  44. html=gen_designer_report.gen_report()
  45. TEMPLATE_FILE = "admin.html"
  46. template2 = templateEnv.get_template(TEMPLATE_FILE)
  47. outputText = template2.render(mycontent=html)
  48. return HTMLResponse(outputText)
  49. # return HTMLResponse(html)
  50. return RedirectResponse(url='/static/login.html')
  51. #return HTMLResponse('<a href="/login">login</a>')
  52. #@app.route('/adm')
  53. #async def adm(request: Request):
  54. # TEMPLATE_FILE = "admin.tmpl"
  55. # template = templateEnv.get_template(TEMPLATE_FILE)
  56. # outputText = template.render(mycontent=displaydata)
  57. @app.route('/login')
  58. async def login(request: Request):
  59. redirect_uri = request.url_for('auth')
  60. return await oauth.google.authorize_redirect(request, redirect_uri)
  61. @app.route('/auth')
  62. async def auth(request: Request):
  63. try:
  64. token = await oauth.google.authorize_access_token(request)
  65. except OAuthError as error:
  66. return HTMLResponse(f'<h1>{error.error}</h1>')
  67. user = await oauth.google.parse_id_token(request, token)
  68. request.session['user'] = dict(user)
  69. return RedirectResponse(url='/')
  70. @app.route('/logout')
  71. async def logout(request: Request):
  72. request.session.pop('user', None)
  73. return RedirectResponse(url='/')
  74. if __name__ == '__main__':
  75. import uvicorn
  76. uvicorn.run(app, host='127.0.0.1', port=8000)