diff --git a/roac/__init__.py b/roac/__init__.py index d48f9c36c179a9a1b14ac9fb17980ae707daf057..0fd48dbe3d9a5a757d2dda483974fb147d8c3f3f 100644 --- a/roac/__init__.py +++ b/roac/__init__.py @@ -3,7 +3,9 @@ import os import datetime import functools -from flask import Flask, session, request, redirect, abort, Response, url_for, render_template +import click +from flask import Flask, session, request, redirect, abort, Response, url_for, render_template, flash +import requests from requests_oauthlib import OAuth2Session from .models import * @@ -14,7 +16,7 @@ def create_app(test_config=None): app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{}'.format(os.path.join(app.instance_path, 'db.sqlite')) app.config.from_pyfile('default_config.py') if not test_config: - app.config.from_pyfile('config.py', silent=True) + app.config.from_pyfile(os.path.join(app.instance_path, 'config.py'), silent=True) else: app.config.from_mapping(test_config) # OAuth2Session.fetch_token verifies that the passed URIs scheme (the scheme @@ -24,6 +26,36 @@ def create_app(test_config=None): os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' db.init_app(app) + def rocketchat_request(method, path, headers=None, **kwargs): + url = app.config['ROCKETCHAT_BASE_URL'].rstrip('/') + path + headers = headers or {} + headers['X-User-Id'] = app.config['ROCKETCHAT_USER_ID'] + headers['X-Auth-Token'] = app.config['ROCKETCHAT_AUTH_TOKEN'] + return requests.request(method, url, headers=headers, **kwargs) + + def update_blocklist(): + names = list(app.config['STATIC_BLOCK_LIST']) + names += [user.loginname for user in User.query.filter_by(blocked=True).all()] + value = ','.join(names) + rocketchat_request('POST', '/api/v1/settings/Accounts_BlockedUsernameList', json={'value': value}) + + @app.cli.command('add-user') + @click.argument('loginname') + def cli_add_user(loginname): + with app.test_request_context(): + user = User(loginname=loginname) + try: + db.session.add(user) + db.session.commit() + except IntegrityError as ex: + raise click.ClickException(f'Adding user failed: {ex}') from ex + update_blocklist() + + @app.cli.command('update-blocklist') + def cli_update_blocklist(): + with app.test_request_context(): + update_blocklist() + def user_required(func): @functools.wraps(func) def decorator(*args, **kwargs): @@ -35,18 +67,64 @@ def create_app(test_config=None): user = User.query.filter_by(loginname=session['userinfo']['nickname']).one_or_none() if user is None: return render_template('error_unknown_user.html') + request.user = user return func(*args, **kwargs) return decorator @app.route('/') @user_required def index(): - return render_template('index.html') + if request.user.rocketchat_id is None: + return render_template('create.html') + return render_template('sync.html') + + def compute_roles(): + roles = set(app.config['ROCKETCHAT_ROLE_MAP'].get(None, [])) + for group in session['userinfo']['groups']: + roles |= set(app.config['ROCKETCHAT_ROLE_MAP'].get(group, [])) + return list(roles) - @app.route('/create') + @app.route('/create', methods=['POST']) @user_required - def create_account(): - return render_template('index.html') + def create(): + if request.form['password'] != request.form['password2']: + flash('Password mismatch') + return redirect(url_for('index')) + if len(request.form['password']) < 8: + flash('Password too short') + return redirect(url_for('index')) + request.user.unblock() + db.session.commit() + update_blocklist() + data = { + 'username': request.user.loginname, + 'password': request.form['password'], + 'name': request.form['name'], + 'email': request.form['email'], + 'sendWelcomeEmail': True, + 'roles': compute_roles(), + } + if request.form['email'] == session['userinfo']['email']: + data['verified'] = True + try: + resp = rocketchat_request('POST', '/api/v1/users.create', json=data) + resp.raise_for_status() + result = resp.json() + if not result['success']: + raise Exception() + rocketchat_id = result['user']['_id'] + except: + request.user.block() + db.session.commit() + update_blocklist() + flash('Account creation failed, try again later!') + return redirect(url_for('index')) + request.user.block() + request.user.rocketchat_id = rocketchat_id + update_blocklist() + db.session.commit() + flash('Account created!') + return redirect(url_for('index')) @app.route('/oauth/login') def oauth_login(): diff --git a/roac/default_config.py b/roac/default_config.py index de889fee1cf8e158a80a38b7bb92eb322e014edb..ae0d37da74dd2421ab7153ebfc1207b4cb8f07a0 100644 --- a/roac/default_config.py +++ b/roac/default_config.py @@ -5,7 +5,23 @@ OAUTH2_USERINFO_URL = 'http://localhost:5000/oauth2/userinfo' OAUTH2_CLIENT_ID = 'roac' OAUTH2_CLIENT_SECRET = 'testsecret' +# RocketChat API +ROCKETCHAT_BASE_URL = 'https://example.com' +ROCKETCHAT_USER_ID = 'USERID' +ROCKETCHAT_AUTH_TOKEN = 'AUTHTOKEN' + # CSRF protection SESSION_COOKIE_SECURE=True SESSION_COOKIE_HTTPONLY=True SESSION_COOKIE_SAMESITE='Strict' + +# Suppress deprecation warning +SQLALCHEMY_TRACK_MODIFICATIONS=True + +STATIC_BLOCK_LIST = [ + 'admin', +] +ROCKETCHAT_ROLE_MAP = { + None: ['user'], # applies to all users + # OAuth group name -> list of rocket chat role names +} diff --git a/roac/models.py b/roac/models.py index 0c73f1a31e8f83370cb999de4329bd30de841b3b..065ac9d7178f978a4366d9a66520309f0bb60bc5 100644 --- a/roac/models.py +++ b/roac/models.py @@ -1,4 +1,7 @@ +import datetime + from flask_sqlalchemy import SQLAlchemy +from sqlalchemy.ext.hybrid import hybrid_property db = SQLAlchemy() @@ -7,3 +10,17 @@ class User(db.Model): id = db.Column(db.Integer(), primary_key=True, autoincrement=True) loginname = db.Column(db.String, nullable=False) rocketchat_id = db.Column(db.String, nullable=True) + time_unblocked = db.Column(db.DateTime, nullable=True) + + @hybrid_property + def blocked(self): + return db.or_( + self.time_unblocked == None, + self.time_unblocked < datetime.datetime.utcnow() - datetime.timedelta(minutes=5) + ) + + def block(self): + self.time_unblocked = None + + def unblock(self): + self.time_unblocked = datetime.datetime.utcnow() diff --git a/roac/rocketchat.py b/roac/rocketchat.py new file mode 100644 index 0000000000000000000000000000000000000000..80e1611d6dfbe79ba2dbde6126b341d13c1b2437 --- /dev/null +++ b/roac/rocketchat.py @@ -0,0 +1,23 @@ +import requests + +class RocketChat: + def __init__(self, base_url, user_id, api_token): + self.base_url = base_url.rstrip('/') + self.user_id = user_id + self.api_token = api_token + self.session = requests.Session() + self.session.headers['X-User-Id'] = user_id + self.session.headers['X-Auth-Token'] = api_token + + def bulid_url(self, endpoint): + return f'{self.base_url}/api/v1/{endpoint}' + + def get_setting(self, name): + self.session.get(self.build_url(f'settings/{name}')) + + def update_setting(self, name, value): + self.session.post(self.build_url(f'settings/{name}'), data={'value': value}) + + def create_user(self, username, email, name, password): + data = {'username': username, + self.session.post(self.base_url + '/api/v1/users.create/', data={'value': value}) diff --git a/roac/static/rocketchat_logo.svg b/roac/static/rocketchat_logo.svg new file mode 100644 index 0000000000000000000000000000000000000000..5a72e53f7ea6ac6ca8be9198b2eb8f0c47e3702f --- /dev/null +++ b/roac/static/rocketchat_logo.svg @@ -0,0 +1 @@ +<svg width="2500" height="2139" viewBox="0 0 256 219" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid"><path d="M255.95 109.307c0-12.853-3.844-25.173-11.43-36.63-6.81-10.283-16.351-19.385-28.355-27.057-23.18-14.806-53.647-22.963-85.782-22.963-10.734 0-21.315.907-31.577 2.705-6.366-5.96-13.82-11.322-21.707-15.56C34.964-10.62.022 9.322.022 9.322s32.487 26.688 27.204 50.08C12.693 73.821 4.814 91.207 4.814 109.307c0 .056.003.115.003.173 0 .057-.003.113-.003.174 0 18.1 7.876 35.486 22.412 49.902C32.509 182.95.022 209.639.022 209.639s34.942 19.939 77.077-.48c7.886-4.238 15.338-9.603 21.707-15.56 10.264 1.796 20.843 2.702 31.577 2.702 32.137 0 62.601-8.151 85.782-22.958 12.004-7.671 21.545-16.77 28.356-27.058 7.585-11.455 11.43-23.781 11.43-36.628 0-.06-.003-.115-.003-.174l.002-.176z" fill="#C1272D"/><path d="M130.383 40.828c59.505 0 107.746 30.814 107.746 68.824 0 38.007-48.241 68.823-107.746 68.823-13.25 0-25.94-1.532-37.662-4.325-11.915 14.332-38.125 34.26-63.587 27.82 8.282-8.895 20.552-23.926 17.926-48.686-15.262-11.873-24.422-27.07-24.422-43.632-.003-38.013 48.238-68.824 107.745-68.824" fill="#FFF"/><path d="M130.383 126.18c7.906 0 14.314-6.408 14.314-14.314 0-7.905-6.408-14.313-14.314-14.313-7.905 0-14.313 6.408-14.313 14.313 0 7.906 6.408 14.314 14.313 14.314zm49.764 0c7.905 0 14.314-6.408 14.314-14.314 0-7.905-6.409-14.313-14.314-14.313s-14.313 6.408-14.313 14.313c0 7.906 6.408 14.314 14.313 14.314zm-99.53-.003c7.904 0 14.311-6.407 14.311-14.31 0-7.904-6.407-14.312-14.31-14.312-7.905 0-14.312 6.408-14.312 14.311 0 7.904 6.407 14.311 14.311 14.311z" fill="#C1272D"/><path d="M130.383 169.42c-13.25 0-25.94-1.33-37.662-3.75-10.52 10.969-32.188 25.714-54.643 25.172-2.959 4.484-6.175 8.15-8.944 11.126 25.462 6.44 51.672-13.486 63.587-27.82 11.723 2.795 24.414 4.325 37.662 4.325 59.027 0 106.962-30.326 107.726-67.915-.764 32.582-48.699 58.861-107.726 58.861z" fill="#CCC"/></svg> \ No newline at end of file diff --git a/roac/templates/base.html b/roac/templates/base.html index 93476127f781f6e119d5c242667d365a89365422..46b66b83f4dca160485e4f09e1e10042c59e6d68 100644 --- a/roac/templates/base.html +++ b/roac/templates/base.html @@ -17,17 +17,31 @@ {% endblock %} </head> <body> - <div class="container mt-2"> - <div class="row"> - {% for message in get_flashed_messages() %} - <div class="alert alert-primary col-12" role="alert">{{ message }}</div> - {% endfor %} + <main role="main" class="container mt-3"> + <div class="row justify-content-center"> + <div class="col-lg-6 col-md-10 px-0"> + <div class="row"> + {% for message in get_flashed_messages() %} + <div class="col-12"> + <div class="alert alert-primary" role="alert">{{ message }}</div> + </div> + {% endfor %} + </div> + </div> + </div> + <div class="row justify-content-center"> + <div class="col-lg-6 col-md-10" style="background: #f7f7f7; box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); padding: 30px;"> + <div class="text-center mb-3"> + <img alt="branding logo" src="{{ url_for('static', filename='rocketchat_logo.svg') }}" class="col-lg-8 col-md-12" > + </div> + <div class="text-center"> + <h2>Single Sign-On Connector</h2> + <h4><a class="text-muted" href="https://chat.rc3.world/">chat.rc3.world</a></h4> + </div> + {% block body %} + {% endblock body %} + </div> </div> - </div> - - <main role="main" class="container"> - {% block body %} - {% endblock body %} </main> </body> </html> diff --git a/roac/templates/create.html b/roac/templates/create.html new file mode 100644 index 0000000000000000000000000000000000000000..453af9626889a279de4feebbd529f8995c39aaf3 --- /dev/null +++ b/roac/templates/create.html @@ -0,0 +1,34 @@ +{% extends 'base.html' %} +{% block body %} +<form class="form" method="POST" action="{{ url_for('create') }}"> + <div class="form-group col-12"> + <p>Your CCCV SSO loginname was reserved on chat.rc3.world. You can create an account with your loginname with the form below.</p> + </div> + <div class="form-group col-12"> + <label for="username">Username</label> + <input type="text" class="form-control" id="username" readonly value="{{ request.user.loginname }}"> + </div> + <div class="form-group col-12"> + <label for="name">Displayname</label> + <input type="text" class="form-control" id="name" name="name" value="{{ session.userinfo.name }}"> + </div> + <div class="form-group col-12"> + <label for="email">E-Mail Address</label> + <input type="text" class="form-control" id="email" name="email" value="{{ session.userinfo.email }}"> + </div> + <div class="form-group col-12"> + <label for="password1">Password</label> + <input type="password" class="form-control" id="password1" name="password" required> + <small class="form-text text-muted"> + At least 8 characters. Please do <b>not</b> reuse your SSO password! + </small> + </div> + <div class="form-group col-12"> + <label for="password2">Repeat Password</label> + <input type="password" class="form-control" id="password2" name="password2" required> + </div> + <div class="form-group col-12"> + <button type="submit" class="btn btn-primary btn-block">Create Account on chat.rc3.world</button> + </div> +</form> +{% endblock %} diff --git a/roac/templates/error_unknown_user.html b/roac/templates/error_unknown_user.html new file mode 100644 index 0000000000000000000000000000000000000000..77c327e9c5ea1b2585396dba0f9c62fc78ebd7b9 --- /dev/null +++ b/roac/templates/error_unknown_user.html @@ -0,0 +1,4 @@ +{% extends 'base.html' %} +{% block body %} +<p>Your SSO loginname was not reserved on RocketChat. There is nothing for you to do here.</p> +{% endblock %} diff --git a/roac/templates/sync.html b/roac/templates/sync.html new file mode 100644 index 0000000000000000000000000000000000000000..f5b6c14d30ae173c08a63d7d9f0ff22b16709271 --- /dev/null +++ b/roac/templates/sync.html @@ -0,0 +1,4 @@ +{% extends 'base.html' %} +{% block body %} +<p>You already created an account on chat.rc3.world with your loginname.</p> +{% endblock %}