61 lines
2.0 KiB

from flask import Blueprint, redirect, url_for, request, flash, session
from flaskapp.lib.login import check_is_logged_in
from flaskapp.lib.toornament import get_toornament
from flaskapp.config import secret
import secrets
import urllib.parse
bp = Blueprint('login', __name__)
def login():
# if the user is logged in, redirect him to the next-URL or to the index page
if request.args.get('next'):
session['next_url'] = request.args.get('next')
if check_is_logged_in():
if request.args.get('next'):
return redirect(request.args.get('next'))
return redirect(url_for('index.index'))
state = secrets.token_hex(32)
session['state'] = state
params = {
'response_type': 'code',
'client_id': secret['oauth_client_id'],
'redirect_uri': secret['oauth_redirect_uri'],
'state': state,
'scope': 'user:info participant:manage_participations'
url = urllib.parse.urlencode(params)
url = '' + url
return redirect(url)
def oauth_callback():
state = request.args.get('state')
if state != session.get('state'):
flash('Login fehlgeschlagen! - Ungültiger OAuth2 State!', 'danger')
return redirect(url_for('index.index'))
code = request.args.get('code')
if not code:
flash('Login fehlgeschlagen!')
return redirect(url_for('index.index'))
toornament = get_toornament(code)
user_data = toornament.get_user_data()
session['is_logged_in'] = True
session['username'] = user_data['name']
session['user_id'] = user_data['id']
next_url = session.get('next_url')
if next_url:
return redirect(next_url)
return redirect(url_for('index.index'))
def logout():
flash('Logout erfolgreich!', 'success')
return redirect(url_for('index.index'))