Last active
April 14, 2018 04:18
-
-
Save zeratax/6a00db9e29a9f4d1d1b80eac14419165 to your computer and use it in GitHub Desktop.
api endpoint for token protected registration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, request, abort, jsonify, request | |
import hashlib | |
import hmac | |
import requests | |
SERVER_LOCATION = 'https://homeserver.tld/' | |
SHARED_SECRET = b'registration_shared_secret see homeserver.yaml' | |
app = Flask(__name__) | |
@app.route('/register', methods=['POST']) | |
def register(): | |
app.logger.debug('an account registration was requested...') | |
if all(req in request.form for req in ('username', 'password')): | |
username = request.form['username'].rsplit(":")[0].split("@")[1] | |
password = request.form['password'] | |
if username and password: | |
app.logger.debug('creating account %s...' % username) | |
try: | |
account_data = create_account(username, | |
password, | |
SERVER_LOCATION, | |
SHARED_SECRET) | |
except requests.exceptions.HTTPError as e: | |
app.logger.warning(e) | |
abort(400) | |
app.logger.debug('account creation succeded!') | |
return jsonify(account_data) | |
app.logger.debug('account creation failed!') | |
abort(400) | |
def create_account(user, password, server_location, shared_secret, admin=False): | |
mac = hmac.new( | |
key=shared_secret, | |
digestmod=hashlib.sha1, | |
) | |
mac.update(user.encode()) | |
mac.update(b'\x00') | |
mac.update(password.encode()) | |
mac.update(b'\x00') | |
mac.update(b'admin' if admin else b'notadmin') | |
mac = mac.hexdigest() | |
data = { | |
'user': user, | |
'password': password, | |
'mac': mac, | |
'type': 'org.matrix.login.shared_secret', | |
'admin': admin, | |
} | |
server_location = server_location.rstrip('/') | |
app.logger.debug('Sending registration request...') | |
r = requests.post('%s/_matrix/client/api/v1/register' % (server_location,), | |
json=data) | |
r.raise_for_status() | |
return r.json() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment