matrix-synapse-rest-passwor.../rest_auth_provider.py

212 lines
7.4 KiB
Python
Raw Permalink Normal View History

2017-08-31 04:15:22 +08:00
# -*- coding: utf-8 -*-
#
# REST endpoint Authentication module for Matrix synapse
2019-05-18 07:46:21 +08:00
# Copyright (C) 2017 Kamax Sarl
2017-08-31 04:15:22 +08:00
#
2019-05-18 07:46:21 +08:00
# https://www.kamax.io/
2017-08-31 04:15:22 +08:00
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import logging
import requests
import json
import time
2017-08-31 04:15:22 +08:00
logger = logging.getLogger(__name__)
2017-08-31 04:15:22 +08:00
class RestAuthProvider(object):
def __init__(self, config, account_handler):
self.account_handler = account_handler
if not config.endpoint:
raise RuntimeError('Missing endpoint config')
self.endpoint = config.endpoint
self.regLower = config.regLower
2017-10-08 10:52:08 +08:00
self.config = config
logger.info('Endpoint: %s', self.endpoint)
logger.info('Enforce lowercase username during registration: %s', self.regLower)
2017-08-31 04:15:22 +08:00
2020-09-29 20:14:05 +08:00
async def check_password(self, user_id, password):
2017-08-31 04:15:22 +08:00
logger.info("Got password check for " + user_id)
data = {'user': {'id': user_id, 'password': password}}
r = requests.post(self.endpoint + '/_matrix-internal/identity/v1/check_credentials', json=data)
2017-08-31 04:15:22 +08:00
r.raise_for_status()
r = r.json()
if not r["auth"]:
2017-08-31 04:15:22 +08:00
reason = "Invalid JSON data returned from REST endpoint"
logger.warning(reason)
raise RuntimeError(reason)
auth = r["auth"]
2017-08-31 04:15:22 +08:00
if not auth["success"]:
logger.info("User not authenticated")
2020-09-29 20:14:05 +08:00
return False
2017-08-31 04:15:22 +08:00
2017-09-27 00:18:13 +08:00
localpart = user_id.split(":", 1)[0][1:]
logger.info("User %s authenticated", user_id)
2017-08-31 04:15:22 +08:00
2017-10-08 10:52:08 +08:00
registration = False
2020-09-29 20:14:05 +08:00
if not (await self.account_handler.check_user_exists(user_id)):
2017-08-31 04:15:22 +08:00
logger.info("User %s does not exist yet, creating...", user_id)
if localpart != localpart.lower() and self.regLower:
logger.info('User %s was cannot be created due to username lowercase policy', localpart)
2020-09-29 20:14:05 +08:00
return False
2020-09-29 20:14:05 +08:00
user_id, access_token = (await self.account_handler.register(localpart=localpart))
2017-10-08 10:52:08 +08:00
registration = True
2017-08-31 04:15:22 +08:00
logger.info("Registration based on REST data was successful for %s", user_id)
else:
logger.info("User %s already exists, registration skipped", user_id)
if auth["profile"]:
logger.info("Handling profile data")
profile = auth["profile"]
2020-09-29 20:14:05 +08:00
store = self.account_handler._hs.get_profile_handler().store
2017-10-08 10:52:08 +08:00
if "display_name" in profile and ((registration and self.config.setNameOnRegister) or (self.config.setNameOnLogin)):
display_name = profile["display_name"]
logger.info("Setting display name to '%s' based on profile data", display_name)
2020-09-29 20:14:05 +08:00
await store.set_profile_displayname(localpart, display_name)
2017-10-08 10:52:08 +08:00
else:
logger.info("Display name was not set because it was not given or policy restricted it")
if (self.config.updateThreepid):
if "three_pids" in profile:
logger.info("Handling 3PIDs")
external_3pids = []
for threepid in profile["three_pids"]:
medium = threepid["medium"].lower()
address = threepid["address"].lower()
external_3pids.append({"medium": medium, "address": address})
logger.info("Looking for 3PID %s:%s in user profile", medium, address)
validated_at = time_msec()
2020-09-29 20:14:05 +08:00
if not (await store.get_user_id_by_threepid(medium, address)):
logger.info("3PID is not present, adding")
2020-09-29 20:14:05 +08:00
await store.user_add_threepid(
user_id,
medium,
address,
validated_at,
validated_at
)
else:
logger.info("3PID is present, skipping")
if (self.config.replaceThreepid):
2020-09-29 20:14:05 +08:00
for threepid in (await store.user_get_threepids(user_id)):
medium = threepid["medium"].lower()
address = threepid["address"].lower()
if {"medium": medium, "address": address} not in external_3pids:
logger.info("3PID is not present in external datastore, deleting")
2020-09-29 20:14:05 +08:00
await store.user_delete_threepid(
user_id,
medium,
address
)
else:
logger.info("3PIDs were not updated due to policy")
else:
logger.info("No profile data")
2017-08-31 04:15:22 +08:00
2020-09-29 20:14:05 +08:00
return True
2017-08-31 04:15:22 +08:00
@staticmethod
def parse_config(config):
# verify config sanity
_require_keys(config, ["endpoint"])
class _RestConfig(object):
endpoint = ''
regLower = True
2017-10-08 10:52:08 +08:00
setNameOnRegister = True
setNameOnLogin = False
updateThreepid = True
replaceThreepid = False
2017-08-31 04:15:22 +08:00
rest_config = _RestConfig()
rest_config.endpoint = config["endpoint"]
try:
rest_config.regLower = config['policy']['registration']['username']['enforceLowercase']
except TypeError:
# we don't care
pass
except KeyError:
# we don't care
pass
2017-10-08 10:52:08 +08:00
try:
rest_config.setNameOnRegister = config['policy']['registration']['profile']['name']
except TypeError:
# we don't care
pass
except KeyError:
# we don't care
pass
2017-10-08 10:52:08 +08:00
try:
rest_config.setNameOnLogin = config['policy']['login']['profile']['name']
except TypeError:
# we don't care
pass
except KeyError:
# we don't care
pass
try:
rest_config.updateThreepid = config['policy']['all']['threepid']['update']
except TypeError:
# we don't care
pass
except KeyError:
# we don't care
pass
try:
rest_config.replaceThreepid = config['policy']['all']['threepid']['replace']
except TypeError:
# we don't care
pass
except KeyError:
# we don't care
pass
2017-08-31 04:15:22 +08:00
return rest_config
2017-08-31 04:15:22 +08:00
def _require_keys(config, required):
missing = [key for key in required if key not in config]
if missing:
raise Exception(
"REST Auth enabled but missing required config values: {}".format(
", ".join(missing)
)
)
def time_msec():
"""Get the current timestamp in milliseconds
"""
return int(time.time() * 1000)