123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- import json
- from fastapi import FastAPI
- from starlette.config import Config
- from starlette.requests import Request
- from starlette.middleware.sessions import SessionMiddleware
- from starlette.responses import HTMLResponse, RedirectResponse
- from authlib.integrations.starlette_client import OAuth, OAuthError
- from fastapi.staticfiles import StaticFiles
- import jinja2
- import gen_designer_report
- import os
- app = FastAPI()
- app.add_middleware(SessionMiddleware, secret_key="!secret")
- config = Config('.env')
- #config.
- #config['GOOGLE_CLIENT_ID']='813384606753-40sct043k48uaveu8r2e8m7t9u885cbs.apps.googleusercontent.com'
- #config['GOOGLE_CLIENT_SECRET']='jvKKjKxCr9kUnn2e5niCQVTq'
- #Config('.env')
- oauth = OAuth(config)
- app.mount("/static", StaticFiles(directory="static"), name="static")
- CONF_URL = 'https://accounts.google.com/.well-known/openid-configuration'
- oauth.register(
- name='google',
- server_metadata_url=CONF_URL,
- client_kwargs={
- 'scope': 'openid email profile'
- }
- )
- fname=os.path.abspath(__file__)
- elmts=fname.split(os.path.sep)
- path2=os.path.sep.join(elmts[0:-1])
- keysdir=path2+os.path.sep+'static'+os.path.sep
- templateLoader = jinja2.FileSystemLoader(searchpath=keysdir)
- templateEnv = jinja2.Environment(loader=templateLoader)
- @app.route('/')
- async def homepage(request: Request):
- user = request.session.get('user')
- if user:
- data = json.dumps(user)
- html = (
- f'<pre>{data}</pre>'
- '<a href="/logout">logout</a>'
- )
- html=gen_designer_report.gen_report()
- TEMPLATE_FILE = "admin.html"
- template2 = templateEnv.get_template(TEMPLATE_FILE)
- outputText = template2.render(mycontent=html)
- return HTMLResponse(outputText)
- # return HTMLResponse(html)
- return RedirectResponse(url='/static/login.html')
- #return HTMLResponse('<a href="/login">login</a>')
- #@app.route('/adm')
- #async def adm(request: Request):
- # TEMPLATE_FILE = "admin.tmpl"
- # template = templateEnv.get_template(TEMPLATE_FILE)
- # outputText = template.render(mycontent=displaydata)
- @app.route('/login')
- async def login(request: Request):
- redirect_uri = request.url_for('auth')
- return await oauth.google.authorize_redirect(request, redirect_uri)
- @app.route('/auth')
- async def auth(request: Request):
- try:
- token = await oauth.google.authorize_access_token(request)
- except OAuthError as error:
- return HTMLResponse(f'<h1>{error.error}</h1>')
- user = await oauth.google.parse_id_token(request, token)
- request.session['user'] = dict(user)
- return RedirectResponse(url='/')
- @app.route('/logout')
- async def logout(request: Request):
- request.session.pop('user', None)
- return RedirectResponse(url='/')
- if __name__ == '__main__':
- import uvicorn
- uvicorn.run(app, host='127.0.0.1', port=8000)
|