Skip to content

Commit

Permalink
FIEF http only harmonize with Traefik https only
Browse files Browse the repository at this point in the history
  • Loading branch information
Claudio Rossner committed Mar 20, 2024
1 parent dbc1d5f commit eeb05cd
Show file tree
Hide file tree
Showing 15 changed files with 504 additions and 70 deletions.
2 changes: 1 addition & 1 deletion fiefdemo/fiefwebapp/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Use official
FROM python:3.11.2
FROM python:3.12

# Set working dir within the container
WORKDIR /code
Expand Down
37 changes: 34 additions & 3 deletions fiefdemo/fiefwebapp/app/feng.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
####################################

# Taken from: https://nicegui.io
# Parts taken from:
# https://nicegui.io
# https://nicegui.io/documentation/section_configuration_deployment
# https://github.com/zauberzeug/nicegui/tree/main/examples/fastapi/
# https://github.com/markbaumgarten/nicegui-letsencrypt/blob/main
Expand All @@ -10,15 +11,23 @@
# Imports

import os
import requests

from nicegui import app, ui
from pathlib import Path
from fastapi import FastAPI, Request
from fastapi.responses import RedirectResponse
from fastapi.staticfiles import StaticFiles

from config.settings import settings

# Init

fief_base_url=settings.fief_server_url
api_url=f'{fief_base_url}:8000'
my_redirect_uri = '{fief_base_url}8000/public'


static_files = StaticFiles(
directory=(Path(__file__).parent / 'static').resolve(),
follow_symlink=True,
Expand All @@ -28,21 +37,43 @@
def init(fastapi_app: FastAPI) -> None:
@ui.page('/')
async def main_page(request: Request) -> None:
return RedirectResponse('/info')
return RedirectResponse('/public')

ui.run_with(
fastapi_app,
)

def check_authentication():
response = requests.get(f'{api_url}/private', cookies=ui.request.cookies)
if response.status_code == 200:
return response.json()
else:
return None

####################################

# Page(s)

@ui.page('/info')
def on_private_page():
user = check_authentication()
ui.clear()
with ui.page('/private'):
if user:
ui.label(f'Private Page - Welcome: {user["email"]}')
ui.button('Back to public page', on_click=lambda: ui.goto('/'))
else:
ui.notify('Access denied. Please login.', level='error')
ui.goto('/')

@ui.page('/public')
async def info(request: Request) -> None:
with ui.header().classes('bg-transparent'), ui.column().classes('w-full max-w-3xl mx-auto my-3'):
ui.image('/static/logo.png').classes('max-w-[20%]')
with ui.column().classes('w-full max-w-2xl mx-auto items-stretch'):
ui.label("""Hello NiceGUI World""")
ui.label('Publice Page')
ui.button('Call private endpoint (needs authentification)', on_click=on_private_page)
ui.button('Login', on_click=lambda: ui.redirect(f'{fief_base_url}/auth/login?redirect_uri={my_redirect_uri}'))
ui.button('Register', on_click=lambda: ui.redirect(f'{fief_base_url}/auth/register?redirect_uri={my_redirect_uri}'))

####################################
46 changes: 28 additions & 18 deletions fiefdemo/fiefwebapp/app/main.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
####################################

# Taken from the official FIEF documenation: https://docs.fief.dev/integrate/python/fastapi/

# Imports

from typing import Annotated
from typing import Optional

from fastapi import FastAPI, Depends, HTTPException, status
from fastapi import FastAPI, Depends, HTTPException, status, Request
from fastapi.responses import HTMLResponse
from fastapi.security import OAuth2AuthorizationCodeBearer
from fastapi.responses import RedirectResponse
from fief_client import FiefAccessTokenInfo, FiefAsync
from fief_client import Fief, FiefAccessTokenInfo, FiefAsync
from fief_client.integrations.fastapi import FiefAuth

from config.settings import settings
Expand All @@ -21,23 +19,24 @@

# App

FIEF_SERVER_URL=settings.fief_server_url,
FIEF_CLIENT_ID=settings.fief_client_id,
FIEF_CLIENT_SECRET=settings.fief_client_secret,

fief = FiefAsync(
settings.fief_server_url,
settings.fief_client_id,
settings.fief_client_secret,
FIEF_SERVER_URL,
FIEF_CLIENT_ID,
FIEF_CLIENT_SECRET,
# host="localhost:8000",
)

oauth2 = OAuth2AuthorizationCodeBearer(
f"{settings.fief_server_url}/authorize",
f"{settings.fief_server_url}/api/token",
f"{FIEF_SERVER_URL}/authorize",
f"{FIEF_SERVER_URL}/api/token",
scopes={"openid": "openid", "offline_access": "offline_access"},
auto_error=False,
)

auth = FiefAuth(fief, oauth2)

AuthenticatedUser = Annotated[FiefAccessTokenInfo, Depends(auth.authenticated())]
# AuthenticatedUser = Annotated[FiefAccessTokenInfo, Depends(auth.authenticated())]

app = FastAPI()

Expand All @@ -47,10 +46,21 @@

@app.get("/user")
async def get_user(
access_token_info: FiefAccessTokenInfo = Depends(auth.authenticated()),
user: FiefAccessTokenInfo = Depends(auth.authenticated()),
):
print(f"TokenInfo: {access_token_info}")
return access_token_info
print(f"TokenInfo: {user}")
return user

# Public endpoint - does not need any authentification
@app.get("/public")
def read_public_data():
return {"message": "This is a public page."}

# Private secured endpoint - needs authentification
@app.get("/private")
async def read_private_data(user: FiefAccessTokenInfo = Depends(auth.authenticated())):

return {"message": f"Secret (private) page - you are authenticated as: {user.email}"}

####################################

Expand Down
44 changes: 35 additions & 9 deletions fiefdemo/fiefwebapp/config/.env.template.j2
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,30 @@ SECRET=XXX
FIEF_CLIENT_ID=XXX
FIEF_CLIENT_SECRET=XXX
ENCRYPTION_KEY=XXX
PORT=8000
{% if fiefdemo_use_ip_port == true %}
PORT=8000
ROOT_DOMAIN={{ fiefdemo_ip }}:8000
{% else %}
ROOT_DOMAIN=localhost
PORT=80
ROOT_DOMAIN={{ fiefdemo_domain }}
{% endif %}
{% if fiefdemo_use_ip_port == true %}
FIEF_DOMAIN={{ fiefdemo_ip }}:8000
{% else %}
FIEF_DOMAIN=fiefdemo.localhost
FIEF_DOMAIN=fiefdemo.{{ fiefdemo_domain }}
{% endif %}
FIEF_MAIN_USER_EMAIL=admin@localhost.me
FIEF_MAIN_USER_PASSWORD=fiefwebapp
{% if fiefdemo_use_ip_port == true %}
FIEF_SERVER_URL=http://{{ fiefdemo_ip }}:8000
{% else %}
FIEF_SERVER_URL=http://fiefdemo.localhost
{% if fiefdemo_domain == 'localhost' %}
FIEF_SERVER_URL=http://fiefdemo.{{ fiefdemo_domain }}
{% else %}
# If Port = 80 use http instead https
FIEF_SERVER_URL=http://fiefdemo.{{ fiefdemo_domain }}
#FIEF_SERVER_URL=https://fiefdemo.{{ fiefdemo_domain }}
{% endif %}
{% endif %}

# Read more: https://docs.fief.dev/self-hosting/deployment/setup-database/
Expand All @@ -36,28 +43,47 @@ DATABASE_NAME=fief
REDIS_URL=redis://redis:6379

# Extras
{% if fiefdemo_use_ip_port == true %}
{% if fiefdemo_use_ip_port == true or fief_http_only == true %}
#DATABASE_URL="postgresql://${DATABASE_USERNAME}:${DATABASE_PASSWORD}@{{ fiefdemo_ip }}:5432/fief"
{% else %}
#DATABASE_URL="postgresql://${DATABASE_USERNAME}:${DATABASE_PASSWORD}@localhost:5432/fief"
{% endif %}
CSRF_COOKIE_SECURE=False
SESSION_DATA_COOKIE_SECURE=False
USER_LOCALE_COOKIE_SECURE=False
LOGIN_SESSION_COOKIE_SECURE=False
SESSION_COOKIE_SECURE=False
LOGIN_HINT_COOKIE_SECURE=False
REGISTRATION_SESSION_COOKIE_SECURE=False
{% else %}
#DATABASE_URL="postgresql://${DATABASE_USERNAME}:${DATABASE_PASSWORD}@{{ fiefdemo_domain }}:5432/fief"
CSRF_COOKIE_SECURE=True
SESSION_DATA_COOKIE_SECURE=True
USER_LOCALE_COOKIE_SECURE=True
LOGIN_SESSION_COOKIE_SECURE=True
SESSION_COOKIE_SECURE=True
LOGIN_HINT_COOKIE_SECURE=True
REGISTRATION_SESSION_COOKIE_SECURE=True
{% endif %}
FORWARD_ALLOWED_IPS=*

# Do we have to use this too?
FIEF_API_KEY="ABCD"
FIEF_MAIN_ADMIN_API_KEY="ABCD"
{% if fiefdemo_use_ip_port == true or fief_http_only == true %}
FIEF_ADMIN_SESSION_COOKIE_SECURE=False
{% else %}
FIEF_ADMIN_SESSION_COOKIE_SECURE=True
{% endif %}
# Optional if DB-Connection is doing trouble
#DATABASE_SSL_MODE=disable
DATABASE_SSL_MODE=disable
TELEMETRY_ENABLED=false

# CLIENT_REDIRECT_URI_SSL_REQUIRED=False
UVICORN_SSL_KEYFILE=/etc/ssl/private/server.key
UVICORN_SSL_CERTFILE=/etc/ssl/certs/server.crt

# Spezielles
CLIENT_REDIRECT_URI_SSL_REQUIRED=False
CSRF_CHECK_ENABLED=False

# NiceGUI needs
UID=1000
GID=1000
6 changes: 6 additions & 0 deletions fiefdemo/fiefwebapp/config/jinja_vars.yml.template
Original file line number Diff line number Diff line change
@@ -1,2 +1,8 @@
fiefdemo_use_ip_port: false
fiefdemo_ip: 192.168.2.33
fiefdemo_domain: localhost
tls_email: "admin@localhost.me"
tls_key: "xxx"
tls_dns_token: "xxx"
use_dozzle: true
fief_http_only: true
2 changes: 2 additions & 0 deletions fiefdemo/fiefwebapp/data/.gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
/fief/*
!/fief/db
!/fief/db/.gitkeep
/letsencrypt/*
!/letsencrypt/acme.json.template
Empty file.
Loading

0 comments on commit eeb05cd

Please sign in to comment.