Skip to content

Commit

Permalink
google auth: get the google token
Browse files Browse the repository at this point in the history
  • Loading branch information
vokimon committed Jan 10, 2022
1 parent 73f4edf commit 629b903
Show file tree
Hide file tree
Showing 5 changed files with 99 additions and 4 deletions.
4 changes: 4 additions & 0 deletions config-example.yaml
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
baseUrl: http://example.com:4555 # CLI tools will use that base url to retrieve info from the API
appSecret: "VerySecret" # YOU SHOULD CHANGE THIS, used to sign authentification and other critical stuff
googleAuth: # Generate them from https://console.cloud.google.com/apis/credentials
GOOGLE_CLIENT_ID='alongstring.apps.googleusercontent.com'
GOOGLE_CLIENT_SECRET='anotherlongstring'
hangoutChannel: 'EwCesKUaJZ1yCpn3R4J4AaABAQ' # the channel id used to warn operators
# Drive spreadsheet with input information to compute scheduling
documentDrive: Tomatic Control # Drive document name with the input information
Expand Down
3 changes: 3 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,9 @@
'uvicorn[standard]', # server for fastapi (standard for websockets)
'aiofiles', # Static files for fastapi
'hangups',
'itsdangerous', # auth
'authlib', # auth
'httpx', # auth
#],
#tests_require=[
'nose',
Expand Down
14 changes: 12 additions & 2 deletions tomatic/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@
from fastapi.responses import (
FileResponse,
Response,
RedirectResponse,
)
from . import __version__ as version
from starlette.middleware.sessions import SessionMiddleware
import asyncio
import re
from datetime import datetime, timedelta, timezone
Expand All @@ -24,6 +25,7 @@
from yamlns import namespace as ns
from consolemsg import error, step, warn, u

from . import __version__ as version
from .callinfo import CallInfo
from .callregistry import CallRegistry
from . import schedulestorage
Expand Down Expand Up @@ -71,10 +73,13 @@ def thisweek():
return format(now().date() - timedelta(days=now().weekday()))

from .planner_api import api as Planner
from .auth import router as Auth
from fastapi.websockets import WebSocket

app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key="Hola, Supers!")
app.include_router(Planner, prefix='/api/planner')
app.include_router(Auth, prefix='/api/auth')


class ApiError(Exception): pass
Expand Down Expand Up @@ -146,7 +151,12 @@ def sender(message):

@app.get('/')
@app.get('/{file}')
def tomatic(file=None):
def tomatic(request: Request, file=None):
user = request.session.get('user')
if not user:
print("No hay usuario!", file)
return RedirectResponse(url='/api/auth/login')

return FileResponse(distpath / (file or 'index.html'))

@app.get('/api/version')
Expand Down
69 changes: 69 additions & 0 deletions tomatic/auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import json
from fastapi import APIRouter
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 starlette.config import Config
from yamlns import namespace as ns
from . import persons


config = Config('config.fastapi')
print(config.file_values)

oauth = OAuth(config)


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'
}
)

router = APIRouter()
"""
@router.get('/')
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>'
)
return HTMLResponse(html)
return HTMLResponse('<a href="/login">login</a>')
"""

@router.get('/login')
async def login(request: Request):
redirect_uri = request.url_for('auth')
print(redirect_uri)
return await oauth.google.authorize_redirect(request, redirect_uri)


@router.get('/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)

if user:
username = persons.byEmail(user['email'])
if username:
request.session['user'] = dict(user)
return RedirectResponse(url='/')


@router.get('/logout')
async def logout(request: Request):
request.session.pop('user', None)
return RedirectResponse(url='/')


13 changes: 11 additions & 2 deletions tomatic/persons.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,21 @@ def reload():

def byExtension(extension):
"""
Returns the person key having the extension
Returns the person key having the extension or the extension
"""
keytoext = dict(
(e,n) for n,e in persons().extensions.items()
)
return keytoext.get(extension,extension)
return keytoext.get(extension, extension)

def byEmail(email):
"""
Returns the person key having the email or none
"""
keytoext = dict(
(e,n) for n,e in persons().emails.items()
)
return keytoext.get(email, None)

def name(key):
"""
Expand Down

0 comments on commit 629b903

Please sign in to comment.