2020-05-09 18:00:07 +00:00
|
|
|
|
2022-02-19 22:16:13 +00:00
|
|
|
from authlib.integrations.base_client.errors import MissingTokenError, InvalidTokenError
|
2022-04-08 19:28:22 +00:00
|
|
|
from base64 import b64encode, b64decode
|
2023-12-25 16:28:09 +00:00
|
|
|
from flask import Blueprint, redirect, request
|
2020-05-27 15:56:10 +00:00
|
|
|
from flask import current_app
|
2023-12-25 16:28:09 +00:00
|
|
|
from flask import jsonify, session
|
2022-02-19 22:16:13 +00:00
|
|
|
from flask import render_template, url_for
|
2023-12-25 16:28:09 +00:00
|
|
|
from flask_login import logout_user, current_user
|
2022-04-08 19:28:22 +00:00
|
|
|
from http import HTTPStatus
|
2020-05-09 18:00:07 +00:00
|
|
|
from werkzeug.utils import redirect
|
|
|
|
import logging
|
|
|
|
from datetime import timedelta
|
2022-02-19 22:16:13 +00:00
|
|
|
from flask.typing import ResponseReturnValue
|
2023-03-17 07:52:33 +00:00
|
|
|
from ory_hydra_client.api.o_auth_2 import list_o_auth_2_consent_sessions, revoke_o_auth_2_consent_sessions
|
2022-02-19 22:16:13 +00:00
|
|
|
from ory_hydra_client.models import GenericError
|
2023-12-25 16:28:09 +00:00
|
|
|
from urllib.parse import urlparse
|
|
|
|
from typing import Optional, Any
|
|
|
|
import jwt
|
|
|
|
from datetime import datetime, timedelta
|
2023-12-25 17:55:20 +00:00
|
|
|
import webauthn
|
|
|
|
from webauthn.helpers.structs import (
|
|
|
|
AuthenticatorSelectionCriteria,
|
|
|
|
PublicKeyCredentialDescriptor,
|
|
|
|
ResidentKeyRequirement,
|
|
|
|
UserVerificationRequirement,
|
|
|
|
)
|
2020-05-09 18:00:07 +00:00
|
|
|
|
2023-12-25 18:44:38 +00:00
|
|
|
from ..model import db, User, AppToken, PasskeyCredential
|
|
|
|
from ..form.frontend import ClientCertForm, PasswordChangeForm, \
|
|
|
|
AppTokenForm, AppTokenDeleteForm, PasskeyRegisterForm
|
2022-04-08 19:28:22 +00:00
|
|
|
from ..form.base import ButtonForm
|
2022-06-18 17:35:05 +00:00
|
|
|
from ..auth_providers import PasswordAuthProvider
|
2022-02-19 22:16:13 +00:00
|
|
|
from .oauth2 import redirect_login, oauth2
|
|
|
|
from ..hydra import hydra_service
|
2022-06-17 11:38:49 +00:00
|
|
|
from ..pki import pki
|
|
|
|
from ..lenticular_services import lenticular_services
|
2020-05-09 18:00:07 +00:00
|
|
|
|
|
|
|
frontend_views = Blueprint('frontend', __name__, url_prefix='')
|
2020-05-27 15:56:10 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2023-10-09 19:58:44 +00:00
|
|
|
def get_current_user() -> User:
|
|
|
|
user_any: Any = current_user
|
|
|
|
user: User = user_any
|
|
|
|
return user
|
|
|
|
|
2020-05-27 15:56:10 +00:00
|
|
|
|
2022-02-19 22:16:13 +00:00
|
|
|
def before_request() -> Optional[ResponseReturnValue]:
|
2020-05-27 15:56:10 +00:00
|
|
|
try:
|
2022-02-19 22:16:13 +00:00
|
|
|
resp = oauth2.custom.get('/userinfo')
|
2023-10-09 19:58:44 +00:00
|
|
|
if not get_current_user().is_authenticated or resp.status_code != 200:
|
2020-06-21 09:52:37 +00:00
|
|
|
logger.info('user not logged in redirect')
|
2020-06-02 17:09:32 +00:00
|
|
|
return redirect_login()
|
2022-02-19 22:16:13 +00:00
|
|
|
except MissingTokenError:
|
2022-06-17 11:38:49 +00:00
|
|
|
logger.info('MissingTokenError redirect user to login')
|
2022-02-19 22:16:13 +00:00
|
|
|
return redirect_login()
|
|
|
|
except InvalidTokenError:
|
2022-06-17 11:38:49 +00:00
|
|
|
logger.info('InvalidTokenError redirect user to login')
|
2020-06-02 17:09:32 +00:00
|
|
|
return redirect_login()
|
2020-05-27 15:56:10 +00:00
|
|
|
|
2022-02-19 22:16:13 +00:00
|
|
|
return None
|
2020-05-27 15:56:10 +00:00
|
|
|
|
2020-05-09 18:00:07 +00:00
|
|
|
|
2022-02-19 22:16:13 +00:00
|
|
|
frontend_views.before_request(before_request)
|
2020-05-21 11:20:27 +00:00
|
|
|
|
2020-06-02 17:09:32 +00:00
|
|
|
|
|
|
|
@frontend_views.route('/logout')
|
2022-02-19 22:16:13 +00:00
|
|
|
def logout() -> ResponseReturnValue:
|
2020-06-02 17:09:32 +00:00
|
|
|
logout_user()
|
|
|
|
return redirect(
|
|
|
|
f'{current_app.config["HYDRA_PUBLIC_URL"]}/oauth2/sessions/logout')
|
2020-05-21 11:20:27 +00:00
|
|
|
|
|
|
|
|
2020-05-09 18:00:07 +00:00
|
|
|
@frontend_views.route('/', methods=['GET'])
|
2022-02-19 22:16:13 +00:00
|
|
|
def index() -> ResponseReturnValue:
|
2020-06-02 17:09:32 +00:00
|
|
|
if 'next_url' in session:
|
|
|
|
next_url = session['next_url']
|
|
|
|
del session['next_url']
|
|
|
|
return redirect(next_url)
|
2023-12-25 23:24:28 +00:00
|
|
|
return render_template(
|
|
|
|
'frontend/index.html.j2',
|
|
|
|
lenticular_services=lenticular_services,
|
|
|
|
)
|
2020-05-09 18:00:07 +00:00
|
|
|
|
|
|
|
|
|
|
|
@frontend_views.route('/client_cert')
|
2022-02-19 22:16:13 +00:00
|
|
|
def client_cert() -> ResponseReturnValue:
|
2020-05-09 18:00:07 +00:00
|
|
|
client_certs = {}
|
2022-06-17 11:38:49 +00:00
|
|
|
for service in lenticular_services.values():
|
2020-05-27 15:56:10 +00:00
|
|
|
client_certs[str(service.name)] = \
|
2023-10-09 19:58:44 +00:00
|
|
|
pki.get_client_certs(get_current_user(), service)
|
2020-05-09 18:00:07 +00:00
|
|
|
|
2020-05-27 15:56:10 +00:00
|
|
|
return render_template(
|
|
|
|
'frontend/client_cert.html.j2',
|
2022-06-17 11:38:49 +00:00
|
|
|
services=lenticular_services,
|
2020-05-27 15:56:10 +00:00
|
|
|
client_certs=client_certs)
|
2020-05-09 18:00:07 +00:00
|
|
|
|
|
|
|
|
2020-05-25 18:23:27 +00:00
|
|
|
@frontend_views.route('/client_cert/<service_name>/<serial_number>')
|
2022-02-19 22:16:13 +00:00
|
|
|
def get_client_cert(service_name, serial_number) -> ResponseReturnValue:
|
2022-06-17 11:38:49 +00:00
|
|
|
service = lenticular_services[service_name]
|
|
|
|
cert = pki.get_client_cert(
|
2023-10-09 19:58:44 +00:00
|
|
|
get_current_user(), service, serial_number)
|
2020-05-25 18:23:27 +00:00
|
|
|
return jsonify({
|
|
|
|
'data': {
|
|
|
|
'pem': cert.pem()}
|
|
|
|
})
|
|
|
|
|
|
|
|
|
2020-05-27 15:56:10 +00:00
|
|
|
@frontend_views.route(
|
|
|
|
'/client_cert/<service_name>/<serial_number>', methods=['DELETE'])
|
2022-02-19 22:16:13 +00:00
|
|
|
def revoke_client_cert(service_name, serial_number) -> ResponseReturnValue:
|
2022-06-17 11:38:49 +00:00
|
|
|
service = lenticular_services[service_name]
|
|
|
|
cert = pki.get_client_cert(
|
2023-10-09 19:58:44 +00:00
|
|
|
get_current_user(), service, serial_number)
|
2022-06-17 11:38:49 +00:00
|
|
|
pki.revoke_certificate(cert)
|
2020-05-25 18:23:27 +00:00
|
|
|
return jsonify({})
|
2020-05-09 18:00:07 +00:00
|
|
|
|
|
|
|
|
|
|
|
@frontend_views.route(
|
|
|
|
'/client_cert/<service_name>/new',
|
|
|
|
methods=['GET', 'POST'])
|
2022-02-19 22:16:13 +00:00
|
|
|
def client_cert_new(service_name) -> ResponseReturnValue:
|
2022-07-15 08:53:06 +00:00
|
|
|
if service_name not in lenticular_services:
|
|
|
|
return '', 404
|
2022-06-17 11:38:49 +00:00
|
|
|
service = lenticular_services[service_name]
|
2020-05-09 18:00:07 +00:00
|
|
|
form = ClientCertForm()
|
|
|
|
if form.validate_on_submit():
|
|
|
|
valid_time = int(form.data['valid_time']) * timedelta(1, 0, 0)
|
2022-06-17 11:38:49 +00:00
|
|
|
cert = pki.signing_publickey(
|
2023-10-09 19:58:44 +00:00
|
|
|
get_current_user(),
|
2020-05-09 18:00:07 +00:00
|
|
|
service,
|
|
|
|
form.data['publickey'],
|
|
|
|
valid_time=valid_time)
|
2020-05-10 12:34:28 +00:00
|
|
|
return jsonify({
|
2020-05-09 18:00:07 +00:00
|
|
|
'status': 'ok',
|
|
|
|
'data': {
|
|
|
|
'cert': cert.pem(),
|
2022-06-17 11:38:49 +00:00
|
|
|
'ca_cert': pki.get_ca_cert_pem(service)
|
2020-05-09 18:00:07 +00:00
|
|
|
}})
|
|
|
|
elif form.is_submitted():
|
|
|
|
return jsonify({
|
|
|
|
'status': 'error',
|
|
|
|
'errors': form.errors
|
|
|
|
})
|
|
|
|
|
2020-05-25 18:23:27 +00:00
|
|
|
return render_template(
|
|
|
|
'frontend/client_cert_new.html.j2',
|
2020-05-09 18:00:07 +00:00
|
|
|
service=service,
|
|
|
|
form=form)
|
|
|
|
|
2022-06-17 07:44:46 +00:00
|
|
|
@frontend_views.route('/app_token')
|
|
|
|
def app_token() -> ResponseReturnValue:
|
2022-07-15 08:53:06 +00:00
|
|
|
delete_form = AppTokenDeleteForm()
|
|
|
|
form = ClientCertForm()
|
|
|
|
return render_template('frontend/app_token.html.j2',
|
|
|
|
delete_form=delete_form,
|
|
|
|
services=lenticular_services)
|
2022-06-17 07:44:46 +00:00
|
|
|
|
2023-10-22 17:45:37 +00:00
|
|
|
@frontend_views.route('/app_token/new', methods=['GET','POST'])
|
|
|
|
def app_token_new() -> ResponseReturnValue:
|
2022-07-15 08:53:06 +00:00
|
|
|
form = AppTokenForm()
|
|
|
|
|
|
|
|
if form.validate_on_submit():
|
2023-10-09 19:58:44 +00:00
|
|
|
user_any = get_current_user() # type: Any
|
|
|
|
user = user_any # type: User
|
2023-10-22 17:45:37 +00:00
|
|
|
app_token = AppToken.new(user, name="",scopes="")
|
2022-07-15 08:53:06 +00:00
|
|
|
form.populate_obj(app_token)
|
|
|
|
# check for duplicate names
|
2023-10-09 19:58:44 +00:00
|
|
|
for user_app_token in user.app_tokens:
|
2022-07-15 08:53:06 +00:00
|
|
|
if user_app_token.name == app_token.name:
|
|
|
|
return 'name already exist', 400
|
2023-10-09 19:58:44 +00:00
|
|
|
user.app_tokens.append(app_token)
|
2022-07-15 08:53:06 +00:00
|
|
|
db.session.commit()
|
2023-10-22 17:45:37 +00:00
|
|
|
return render_template('frontend/app_token_new_show.html.j2', app_token=app_token)
|
2022-07-15 08:53:06 +00:00
|
|
|
|
|
|
|
|
|
|
|
return render_template('frontend/app_token_new.html.j2',
|
2023-10-22 17:45:37 +00:00
|
|
|
form=form)
|
2022-07-15 08:53:06 +00:00
|
|
|
|
2023-10-22 17:45:37 +00:00
|
|
|
@frontend_views.route('/app_token/<app_token_name>', methods=["POST"])
|
|
|
|
def app_token_delete(app_token_name: str) -> ResponseReturnValue:
|
2022-07-15 08:53:06 +00:00
|
|
|
form = AppTokenDeleteForm()
|
2022-06-17 07:44:46 +00:00
|
|
|
|
2022-07-15 08:53:06 +00:00
|
|
|
if form.validate_on_submit():
|
2023-10-22 17:45:37 +00:00
|
|
|
app_token = get_current_user().get_token_by_name(app_token_name)
|
2022-07-15 08:53:06 +00:00
|
|
|
if app_token is None:
|
|
|
|
return 'not found', 404
|
|
|
|
db.session.delete(app_token)
|
|
|
|
db.session.commit()
|
|
|
|
|
|
|
|
return redirect(url_for('frontend.app_token'))
|
2020-05-09 18:00:07 +00:00
|
|
|
|
2023-12-25 16:28:09 +00:00
|
|
|
## Passkey
|
2022-04-08 19:28:22 +00:00
|
|
|
|
2023-12-25 16:28:09 +00:00
|
|
|
@frontend_views.route('/passkey/list', methods=['GET'])
|
|
|
|
def passkey() -> ResponseReturnValue:
|
|
|
|
"""list registered credentials for current user"""
|
2022-04-08 19:28:22 +00:00
|
|
|
|
2023-12-26 11:55:45 +00:00
|
|
|
user = get_current_user()
|
|
|
|
return render_template(
|
|
|
|
'frontend/passkey_list.html.j2',
|
|
|
|
credentials=user.passkey_credentials,
|
|
|
|
button_form=ButtonForm()
|
|
|
|
)
|
2023-03-17 07:52:33 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
2023-12-25 16:28:09 +00:00
|
|
|
@frontend_views.route('/passkey/new', methods=['GET'])
|
|
|
|
def passkey_new() -> ResponseReturnValue:
|
|
|
|
"""register credential for current user"""
|
|
|
|
public_url = urlparse(current_app.config['PUBLIC_URL'])
|
2022-04-08 19:28:22 +00:00
|
|
|
|
2023-12-26 11:55:45 +00:00
|
|
|
user = get_current_user()
|
2023-12-25 18:44:38 +00:00
|
|
|
form = PasskeyRegisterForm()
|
2022-04-08 19:28:22 +00:00
|
|
|
|
2023-12-25 16:28:09 +00:00
|
|
|
options = webauthn.generate_registration_options(
|
|
|
|
rp_name="Lenticluar Cloud",
|
|
|
|
rp_id=public_url.hostname,
|
|
|
|
user_id=str(user.id),
|
|
|
|
user_name=user.username,
|
|
|
|
authenticator_selection=AuthenticatorSelectionCriteria(
|
|
|
|
user_verification=UserVerificationRequirement.REQUIRED,
|
|
|
|
resident_key=ResidentKeyRequirement.REQUIRED,
|
|
|
|
),
|
|
|
|
exclude_credentials = list(map(lambda x: PublicKeyCredentialDescriptor(id=x.credential_id), user.passkey_credentials))
|
|
|
|
)
|
|
|
|
secret_key = current_app.config['SECRET_KEY']
|
|
|
|
token = jwt.encode({
|
|
|
|
'challenge': b64encode(options.challenge).decode(),
|
|
|
|
'iat': datetime.utcnow() - timedelta(minutes=1),
|
|
|
|
'nbf': datetime.utcnow(),
|
|
|
|
'exp': datetime.utcnow() + timedelta(minutes=15),
|
|
|
|
}, secret_key, algorithm="HS256"
|
|
|
|
)
|
2022-04-08 19:28:22 +00:00
|
|
|
|
2023-12-25 16:28:09 +00:00
|
|
|
return render_template(
|
|
|
|
'frontend/passkey_new.html.j2',
|
|
|
|
form=form,
|
|
|
|
options=webauthn.options_to_json(options),
|
|
|
|
token=token,
|
|
|
|
)
|
2022-04-08 19:28:22 +00:00
|
|
|
|
2023-12-25 16:28:09 +00:00
|
|
|
@frontend_views.route('/passkey/new', methods=['POST'])
|
|
|
|
def passkey_new_process() -> ResponseReturnValue:
|
|
|
|
secret_key = current_app.config['SECRET_KEY']
|
|
|
|
public_url = urlparse(current_app.config['PUBLIC_URL'])
|
|
|
|
user = get_current_user()
|
2022-04-08 19:28:22 +00:00
|
|
|
|
2023-12-25 16:28:09 +00:00
|
|
|
data = request.get_json()
|
|
|
|
try:
|
|
|
|
token = jwt.decode(
|
|
|
|
data['token'], secret_key, algorithms=['HS256'],
|
|
|
|
options = {
|
|
|
|
'require': ["challenge", "exp", "iat", "nbf"],
|
|
|
|
|
|
|
|
})
|
|
|
|
except jwt.exceptions.MissingRequiredClaimError:
|
|
|
|
return jsonify({'message': "invalid token"}), 400
|
|
|
|
challenge = b64decode(token['challenge'])
|
|
|
|
credential = data['credential']
|
|
|
|
name = data['name']
|
|
|
|
|
|
|
|
result = webauthn.verify_registration_response(
|
|
|
|
credential = credential,
|
|
|
|
expected_rp_id = public_url.hostname,
|
|
|
|
expected_challenge = challenge,
|
|
|
|
expected_origin = [ public_url.geturl() ],
|
2023-03-17 07:52:33 +00:00
|
|
|
)
|
2023-12-25 16:28:09 +00:00
|
|
|
if not result.user_verified:
|
|
|
|
return jsonify({ "message": "invalid auth" }), 403
|
|
|
|
|
|
|
|
db.session.add(PasskeyCredential(
|
|
|
|
id=None,
|
|
|
|
user_id=user.id,
|
|
|
|
credential_id=result.credential_id,
|
|
|
|
credential_public_key=result.credential_public_key,
|
|
|
|
name=name,
|
|
|
|
))
|
|
|
|
db.session.commit()
|
|
|
|
logger.info(f"add new passkey for user {user.username}")
|
2022-04-08 19:28:22 +00:00
|
|
|
|
2023-12-25 16:28:09 +00:00
|
|
|
return jsonify({})
|
2022-04-08 19:28:22 +00:00
|
|
|
|
2023-12-25 16:28:09 +00:00
|
|
|
@frontend_views.route('/passkey/delete/<id>', methods=['POST'])
|
|
|
|
def passkey_delete(id: str) -> ResponseReturnValue:
|
|
|
|
"""delete registered credential"""
|
2022-04-08 19:28:22 +00:00
|
|
|
|
2023-12-26 11:57:59 +00:00
|
|
|
user = get_current_user()
|
2023-12-25 16:28:09 +00:00
|
|
|
form = ButtonForm()
|
2023-12-26 11:57:59 +00:00
|
|
|
|
2022-04-08 19:28:22 +00:00
|
|
|
if form.validate_on_submit():
|
2023-12-25 16:28:09 +00:00
|
|
|
cred = PasskeyCredential.query.filter(PasskeyCredential.id == id).first_or_404()
|
2023-12-26 11:57:59 +00:00
|
|
|
if cred.user_id != user.id:
|
|
|
|
return '', 404
|
2023-12-25 16:28:09 +00:00
|
|
|
db.session.delete(cred)
|
|
|
|
db.session.commit()
|
|
|
|
return redirect(url_for('.passkey'))
|
2022-04-08 19:28:22 +00:00
|
|
|
|
2023-12-25 16:28:09 +00:00
|
|
|
return '', HTTPStatus.BAD_REQUEST
|
2022-04-08 19:28:22 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
2020-05-26 20:55:37 +00:00
|
|
|
@frontend_views.route('/password_change')
|
2022-02-19 22:16:13 +00:00
|
|
|
def password_change() -> ResponseReturnValue:
|
2020-05-26 20:55:37 +00:00
|
|
|
form = PasswordChangeForm()
|
|
|
|
return render_template('frontend/password_change.html.j2', form=form)
|
|
|
|
|
|
|
|
|
|
|
|
@frontend_views.route('/password_change', methods=['POST'])
|
2022-02-19 22:16:13 +00:00
|
|
|
def password_change_post() -> ResponseReturnValue:
|
2020-05-26 20:55:37 +00:00
|
|
|
form = PasswordChangeForm()
|
|
|
|
if form.validate():
|
2020-05-27 15:56:10 +00:00
|
|
|
password_old = str(form.data['password_old'])
|
|
|
|
password_new = str(form.data['password_new'])
|
2022-06-18 17:35:05 +00:00
|
|
|
if not PasswordAuthProvider.check_auth_internal(
|
2023-10-09 19:58:44 +00:00
|
|
|
get_current_user(), password_old):
|
2020-05-27 15:56:10 +00:00
|
|
|
return jsonify(
|
|
|
|
{'errors': {'password_old': 'Old Password is invalid'}})
|
2022-07-15 08:53:06 +00:00
|
|
|
|
2023-10-09 19:58:44 +00:00
|
|
|
get_current_user().change_password(password_new)
|
|
|
|
logger.info(f"user {get_current_user().username} changed password")
|
2022-07-15 08:53:06 +00:00
|
|
|
db.session.commit()
|
|
|
|
return jsonify({})
|
2020-05-26 20:55:37 +00:00
|
|
|
return jsonify({'errors': form.errors})
|
|
|
|
|
|
|
|
|
|
|
|
@frontend_views.route('/oauth2_token')
|
2022-04-08 19:28:22 +00:00
|
|
|
async def oauth2_tokens() -> ResponseReturnValue:
|
2020-05-26 20:55:37 +00:00
|
|
|
|
2022-02-19 22:16:13 +00:00
|
|
|
subject = oauth2.custom.get('/userinfo').json()['sub']
|
2023-03-17 07:52:33 +00:00
|
|
|
consent_sessions = await list_o_auth_2_consent_sessions.asyncio(subject=subject, _client=hydra_service.hydra_client)
|
2022-02-19 22:16:13 +00:00
|
|
|
if consent_sessions is None or isinstance( consent_sessions, GenericError):
|
|
|
|
return 'internal error, could not fetch sessions', 500
|
2020-05-27 15:56:10 +00:00
|
|
|
return render_template(
|
|
|
|
'frontend/oauth2_tokens.html.j2',
|
|
|
|
consent_sessions=consent_sessions)
|
|
|
|
|
2020-05-26 20:55:37 +00:00
|
|
|
|
|
|
|
@frontend_views.route('/oauth2_token/<client_id>', methods=['DELETE'])
|
2022-04-08 19:28:22 +00:00
|
|
|
async def oauth2_token_revoke(client_id: str) -> ResponseReturnValue:
|
2022-02-19 22:16:13 +00:00
|
|
|
subject = oauth2.session.get('/userinfo').json()['sub']
|
2023-03-17 07:52:33 +00:00
|
|
|
await revoke_o_auth_2_consent_sessions.asyncio_detailed( _client=hydra_service.hydra_client,
|
2022-02-19 22:16:13 +00:00
|
|
|
subject=subject,
|
2020-05-26 20:55:37 +00:00
|
|
|
client=client_id)
|
|
|
|
|
|
|
|
return jsonify({})
|