1 Commits

Author SHA1 Message Date
81c3ff5dc0 apply Apache License 2018-03-19 15:16:51 +01:00
14 changed files with 589 additions and 731 deletions

View File

@@ -1,5 +1,4 @@
<?php <?php
/** /**
* Copyright 2018 Matthias Kesler * Copyright 2018 Matthias Kesler
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,157 +13,157 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
class MatrixConnection { class MatrixConnection
{
private $hs;
private $at;
private $hs; function __construct($homeserver, $access_token) {
private $at; $this->hs = $homeserver;
$this->at = $access_token;
}
function __construct($homeserver, $access_token) { function send($room_id, $message) {
$this->hs = $homeserver; if (!$this->at) {
$this->at = $access_token; error_log("No access token defined");
} return false;
}
function send($room_id, $message) { $send_message = NULL;
if (!$this->at) { if (!$message) {
error_log("No access token defined"); error_log("no message to send");
return false; return false;
} } elseif(is_array($message)) {
$send_message = $message;
} elseif ($message instanceof MatrixMessage) {
$send_message = $message->get_object();
} else {
error_log("message is of not valid type\n");
return false;
}
$send_message = NULL; $url="https://".$this->hs."/_matrix/client/r0/rooms/"
if (!$message) { . urlencode($room_id) ."/send/m.room.message?access_token=".$this->at;
error_log("no message to send"); $handle = curl_init($url);
return false; curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
} elseif (is_array($message)) { curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
$send_message = $message; curl_setopt($handle, CURLOPT_TIMEOUT, 60);
} elseif ($message instanceof MatrixMessage) { curl_setopt($handle, CURLOPT_POSTFIELDS, json_encode($send_message));
$send_message = $message->get_object(); curl_setopt($handle, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
} else {
error_log("message is of not valid type\n");
return false;
}
$url = "https://" . $this->hs . "/_matrix/client/r0/rooms/" $response = $this->exec_curl_request($handle);
. urlencode($room_id) . "/send/m.room.message?access_token=" . $this->at; return isset($response["event_id"]);
$handle = curl_init($url); }
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($handle, CURLOPT_TIMEOUT, 60);
curl_setopt($handle, CURLOPT_POSTFIELDS, json_encode($send_message));
curl_setopt($handle, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
$response = $this->exec_curl_request($handle); function send_msg($room_id, $message) {
return isset($response["event_id"]); return $this->send($room_id, array(
} "msgtype" => "m.notice",
"body" => $message
)
);
}
function send_msg($room_id, $message) { function hasUser($username) {
return $this->send($room_id, array( if (!$username) {
"msgtype" => "m.notice", throw new Exception ("no user given to lookup");
"body" => $message }
)
);
}
function hasUser($username) { $url = "https://".$this->hs."/_matrix/client/r0/profile/@" . $username . ":" . $this->hs;
if (!$username) { $handle = curl_init($url);
throw new Exception("no user given to lookup"); curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
} curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($handle, CURLOPT_TIMEOUT, 60);
curl_setopt($handle, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
$url = "https://" . $this->hs . "/_matrix/client/r0/profile/@" . $username . ":" . $this->hs; $res = $this->exec_curl_request($handle);
$handle = curl_init($url); return !(isset($res["errcode"]) && $res["errcode"] == "M_UNKNOWN");
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); }
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($handle, CURLOPT_TIMEOUT, 60);
curl_setopt($handle, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
$res = $this->exec_curl_request($handle); function register($username, $password, $shared_secret) {
return !(isset($res["errcode"]) && $res["errcode"] == "M_UNKNOWN"); if (!$username) {
} error_log("no username provided");
}
if (!$password) {
error_log("no message to send");
}
function register($username, $password, $shared_secret) { $mac = hash_hmac('sha1', $username, $shared_secret);
if (!$username) {
error_log("no username provided");
}
if (!$password) {
error_log("no message to send");
}
$mac = hash_hmac('sha1', $username, $shared_secret); $data = array(
"username" => $username,
"password" => $password,
"mac" => $mac,
);
$url = "https://".$this->hs."/_matrix/client/v2_alpha/register";
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($handle, CURLOPT_TIMEOUT, 60);
curl_setopt($handle, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
curl_setopt($handle, CURLOPT_POSTFIELDS, json_encode($data));
$data = array( return $this->exec_curl_request($handle);
"username" => $username, }
"password" => $password,
"mac" => $mac,
);
$url = "https://" . $this->hs . "/_matrix/client/v2_alpha/register";
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($handle, CURLOPT_TIMEOUT, 60);
curl_setopt($handle, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
curl_setopt($handle, CURLOPT_POSTFIELDS, json_encode($data));
return $this->exec_curl_request($handle); function exec_curl_request($handle) {
} $response = curl_exec($handle);
function exec_curl_request($handle) { if ($response === false) {
$response = curl_exec($handle); $errno = curl_errno($handle);
if ($response === false) { $error = curl_error($handle);
$errno = curl_errno($handle); error_log("Curl returned error $errno: $error\n");
$error = curl_error($handle); curl_close($handle);
error_log("Curl returned error $errno: $error\n"); return false;
curl_close($handle); }
return false;
}
$http_code = intval(curl_getinfo($handle, CURLINFO_HTTP_CODE));
curl_close($handle);
if ($http_code >= 500) { $http_code = intval(curl_getinfo($handle, CURLINFO_HTTP_CODE));
// do not want to DDOS server if something goes wrong curl_close($handle);
sleep(10);
return false;
} else if ($http_code != 200) {
$response = json_decode($response, true);
error_log("Request has failed with error {$response['error']}\n");
if ($http_code == 401) {
throw new Exception('Invalid access token provided');
}
} else {
$response = json_decode($response, true);
}
return $response;
}
if ($http_code >= 500) {
// do not want to DDOS server if something goes wrong
sleep(10);
return false;
} else if ($http_code != 200) {
$response = json_decode($response, true);
error_log("Request has failed with error {$response['error']}\n");
if ($http_code == 401) {
throw new Exception('Invalid access token provided');
}
} else {
$response = json_decode($response, true);
}
return $response;
}
} }
class MatrixMessage { class MatrixMessage
{
private $message;
private $message; function __construct() {
$this->message = ["msgtype" => "m.notice"];
}
function __construct() { function set_type($msgtype) {
$this->message = ["msgtype" => "m.notice"]; $this->message["msgtype"] = $msgtype;
} }
function set_type($msgtype) { function set_format($format) {
$this->message["msgtype"] = $msgtype; $this->message["format"] = $format;
} }
function set_format($format) { function set_body($body) {
$this->message["format"] = $format; $this->message["body"] = $body;
} }
function set_body($body) { function set_formatted_body($fbody, $format="org.matrix.custom.html") {
$this->message["body"] = $body; $this->message["formatted_body"] = $fbody;
} $this->message["format"] = $format;
}
function set_formatted_body($fbody, $format = "org.matrix.custom.html") {
$this->message["formatted_body"] = $fbody;
$this->message["format"] = $format;
}
function get_object() {
return $this->message;
}
function get_object() {
return $this->message;
}
} }
?> ?>

View File

@@ -14,34 +14,17 @@ This is done in several steps:
2nd step: Implement the other apis to integrade [mxisd](https://github.com/kamax-io/mxisd/blob/master/docs/backends/rest.md) 2nd step: Implement the other apis to integrade [mxisd](https://github.com/kamax-io/mxisd/blob/master/docs/backends/rest.md)
This bot takes care for user accounts. So it stores the credentials itself and provides ways to access them via matrix-synapse-rest-auth or mxisd.
## How to install ## How to install
- Copy `config.sample.php` to `config.php` and configure the bot as you can find there - Copy `config.sample.php` to `config.php` and configure the bot as you can find there
- Configure your webserver to publish the folder `public`. - Configure your webserver to publish the folder `public` and configure.
The folder `internal` contains files that can be accessed by mxisd or matrix-synapse-rest-auth or else via a reverse proxy The folder `internal` contains files that can be accessed by mxisd or matrix-synapse-rest-auth
- To integrate with [matrix-synapse-rest-auth](https://github.com/kamax-io/matrix-synapse-rest-auth): - To integrate with matrix-synapse-rest-auth:
- `/_matrix-internal/identity/v1/check_credentials` should map to `internal/login.php` - `/_matrix-internal/identity/v1/check_credentials` should map to `internal/login.php`
- To integrate with [mxisd](https://github.com/kamax-io/mxisd): Have a look at [the docs](https://github.com/kamax-io/mxisd/blob/master/docs/backends/rest.md) and apply as follows: - To integrate with mxisd: Have a look at [the docs](https://github.com/kamax-io/mxisd/blob/master/docs/backends/rest.md) and apply as follows:
| Key | file which handles that | Description | | Key | file which handles that | Description |
|--------------------------------|-------------------------------|------------------------------------------------------| |--------------------------------|-------------------------------|------------------------------------------------------|
| rest.endpoints.auth | internal/login.php | Validate credentials and get user profile | | rest.endpoints.auth | internal/login.php | Validate credentials and get user profile |
| rest.endpoints.directory | internal/directory_search.php | Search for users by arbitrary input | | rest.endpoints.directory | internal/directory_search.php | Search for users by arbitrary input |
| rest.endpoints.identity.single | internal/identity_single.php | Endpoint to query a single 3PID | | rest.endpoints.identity.single | internal/identity_single.php | Endpoint to query a single 3PID |
| rest.endpoints.identity.bulk | internal/identity_bulk.php | Endpoint to query a list of 3PID | | rest.endpoints.identity.bulk | internal/identity_bulk.php | Endpoint to query a list of 3PID |
## Implement usage of additional features:
### Use the ChangePasswortInterceptor:
You need a reverse proxy which maps `/_matrix/client/r0/account/password` to `internal/intercept_change_password.php`.
Here is an example for nginx:
```
location /_matrix/client/r0/account/password {
proxy_pass http://localhost/mxbot/internal/intercept_change_password.php;
proxy_set_header X-Forwarded-For $remote_addr;
}
```

View File

@@ -1,22 +1,26 @@
<?php <?php
$config = [ $config = [
"homeserver" => "example.com", "homeserver" => "example.com",
"access_token" => "To be used for sending the registration notification", "access_token" => "To be used for sending the registration notification",
// Which e-mail-adresse shall the bot use to send e-mails?
"register_email" => 'register_bot@example.com', // Which e-mail-adresse shall the bot use to send e-mails?
// Where should the bot post registration requests to? "register_email" => 'register_bot@example.com',
"register_room" => '$registerRoomID:example.com', // Where should the bot post registration requests to?
// Where is the public part of the bot located? make sure you have a / at the end "register_room" => '$registerRoomID:example.com',
"webroot" => "https://myregisterdomain.net/",
// optional: Do you have a place where howTo's are located? If not leave this value out // Where is the public part of the bot located? make sure you have a / at the end
"howToURL" => "https://my-url-for-storing-howTos.net", "webroot" => "https://myregisterdomain.net/",
// When you want to collect the password on registration set this to true
"getPasswordOnRegistration" => false, // optional: Do you have a place where howTo's are located? If not leave this value out
// to define where the data should be stored: "howToURL" => "https://my-url-for-storing-howTos.net",
"databaseURI" => "sqlite:" . dirname(__FILE__) . "/db_file.sqlite",
// credentials for sqlite not used // When you want to collect the password on registration set this to true
"databaseUser" => "dbUser123", "getPasswordOnRegistration" => false,
"databasePass" => "secretPassword",
] // to define where the data should be stored:
"databaseURI" => "sqlite:" . dirname(__FILE__) . "/db_file.sqlite",
// credentials for sqlite not used
"databaseUser" => "dbUser123",
"databasePass" => "secretPassword",
]
?> ?>

154
cron.php
View File

@@ -1,5 +1,4 @@
<?php <?php
/** /**
* Copyright 2018 Matthias Kesler * Copyright 2018 Matthias Kesler
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
@@ -19,86 +18,89 @@ require_once("mail_templates.php");
require_once("database.php"); require_once("database.php");
$sql = "SELECT id, first_name, last_name, username, email, state, note, verify_token, admin_token FROM registrations " $sql = "SELECT id, first_name, last_name, username, email, state, note, verify_token, admin_token FROM registrations "
. "WHERE state = " . RegisterState::PendingEmailSend ."WHERE state = ". RegisterState::PendingEmailSend
. " OR state = " . RegisterState::PendingAdminSend . " OR state = " . RegisterState::PendingAdminSend
. " OR state = " . RegisterState::PendingRegistration . " OR state = " . RegisterState::PendingRegistration
. " OR state = " . RegisterState::PendingSendRegistrationMail . " OR state = " . RegisterState::PendingSendRegistrationMail
. " OR state = " . RegisterState::RegistrationDeclined . " OR state = " . RegisterState::RegistrationDeclined
. " OR state = " . RegisterState::AllDone . ";"; . " OR state = " . RegisterState::AllDone . ";";
foreach ($mx_db->query($sql) as $row) { foreach ($mx_db->query($sql) as $row) {
$first_name = $row["first_name"]; $first_name = $row["first_name"];
$last_name = $row["last_name"]; $last_name = $row["last_name"];
$username = $row["username"]; $username = $row["username"];
$email = $row["email"]; $email = $row["email"];
$state = $row["state"]; $state = $row["state"];
try { try {
switch ($state) { switch ($state) {
case RegisterState::PendingEmailSend: case RegisterState::PendingEmailSend:
$verify_url = $config["webroot"] . "/verify.php?t=" . $row["verify_token"]; $verify_url = $config["webroot"] . "/verify.php?t=" . $row["verify_token"];
$success = send_mail_pending_verification( $success = send_mail_pending_verification(
$config["homeserver"], $row["first_name"] . " " . $row["last_name"], $row["email"], $verify_url); $config["homeserver"],
$row["first_name"] . " " . $row["last_name"],
$row["email"],
$verify_url);
if ($success) { if ($success) {
$mx_db->setRegistrationStateById(RegisterState::PendingEmailVerify, $row["id"]); $mx_db->setRegistrationStateById(RegisterState::PendingEmailVerify, $row["id"]);
} else { } else {
throw new Exception("Could not send mail to " . $row["first_name"] . " " . $row["last_name"] . "(" . $row["id"] . ")"); throw new Exception("Could not send mail to ".$row["first_name"]." ".$row["last_name"]."(".$row["id"].")");
} }
break; break;
case RegisterState::PendingAdminSend: case RegisterState::PendingAdminSend:
require_once("MatrixConnection.php"); require_once("MatrixConnection.php");
$adminUrl = $config["webroot"] . "/verify_admin.php?t=" . $row["admin_token"]; $adminUrl = $config["webroot"] . "/verify_admin.php?t=" . $row["admin_token"];
$mxConn = new MatrixConnection($config["homeserver"], $config["access_token"]); $mxConn = new MatrixConnection($config["homeserver"], $config["access_token"]);
$mxMsg = new MatrixMessage(); $mxMsg = new MatrixMessage();
$mxMsg->set_body($first_name . ' ' . $last_name . " möchte sich registrieren und hat folgende Notiz hinterlassen:\r\n" $mxMsg->set_body($first_name . ' ' . $last_name . " möchte sich registrieren und hat folgende Notiz hinterlassen:\r\n"
. $row["note"] . "\r\n" . $row["note"] . "\r\n"
. "Zum Bearbeiten hier klicken:\r\n" . $adminUrl); . "Zum Bearbeiten hier klicken:\r\n" . $adminUrl);
$mxMsg->set_formatted_body($first_name . ' ' . $last_name . " möchte sich registrieren und hat folgende Notiz hinterlassen:<br />" $mxMsg->set_formatted_body($first_name . ' ' . $last_name . " möchte sich registrieren und hat folgende Notiz hinterlassen:<br />"
. $row["note"] . "<br />" . $row["note"] . "<br />"
. "Zum Bearbeiten <a href=\"" . $adminUrl . "\">hier</a> klicken"); . "Zum Bearbeiten <a href=\"". $adminUrl . "\">hier</a> klicken");
$mxMsg->set_type("m.text"); $mxMsg->set_type("m.text");
$response = $mxConn->send($config["register_room"], $mxMsg); $response = $mxConn->send($config["register_room"], $mxMsg);
if ($response) { if ($response) {
$mx_db->setRegistrationStateById(RegisterState::PendingAdminVerify, $row["id"]); $mx_db->setRegistrationStateById(RegisterState::PendingAdminVerify, $row["id"]);
send_mail_pending_approval($config["homeserver"], $first_name . " " . $last_name, $email); send_mail_pending_approval($config["homeserver"], $first_name . " " . $last_name, $email);
} else { } else {
throw new Exception("Could not send notification for " . $row["first_name"] . " " . $row["last_name"] . "(" . $row["id"] . ") to admins."); throw new Exception("Could not send notification for ".$row["first_name"]." ".$row["last_name"]."(".$row["id"].") to admins.");
} }
break; break;
case RegisterState::PendingRegistration: case RegisterState::PendingRegistration:
// Registration got accepted but registration failed // Registration got accepted but registration failed
$password = $mx_db->addUser($row["first_name"], $row["last_name"], $row["username"], $row["email"]); $password = $mx_db->addUser($row["first_name"], $row["last_name"], $row["username"], $row["email"]);
if ($password != NULL) { if ($password != NULL) {
// send registration_success // send registration_success
$res = send_mail_registration_success($config["homeserver"], $first_name . " " . $last_name, $email, $username, $password, $config["howToURL"]); $res = send_mail_registration_success($config["homeserver"], $first_name . " " . $last_name, $email, $username, $password, $config["howToURL"]);
if ($res) { if ($res) {
$mx_db->setRegistrationStateById(RegisterState::AllDone, $row["id"]); $mx_db->setRegistrationStateById(RegisterState::AllDone, $row["id"]);
} else { } else {
$mx_db->setRegistrationStateById(RegisterState::PendingSendRegistrationMail, $row["id"]); $mx_db->setRegistrationStateById(RegisterState::PendingSendRegistrationMail, $row["id"]);
} }
} else { } else {
send_mail_registration_allowed_but_failed($config["homeserver"], $first_name . " " . $last_name, $email); send_mail_registration_allowed_but_failed($config["homeserver"], $first_name . " " . $last_name, $email);
$mxMsg = new MatrixMessage(); $mxMsg = new MatrixMessage();
$mxMsg->set_type("m.text"); $mxMsg->set_type("m.text");
$mxMsg->set_body("Fehler beim Registrieren von " . $first_name . " " . $last_name . "."); $mxMsg->set_body("Fehler beim Registrieren von " . $first_name . " " . $last_name . ".");
$mxConn->send($config["register_room"], $mxMsg); $mxConn->send($config["register_room"], $mxMsg);
throw new Exception($language["REGISTRATION_FAILED"]); throw new Exception($language["REGISTRATION_FAILED"]);
} }
break; break;
case RegisterState::PendingSendRegistrationMail: case RegisterState::PendingSendRegistrationMail:
print ("Error: Unhandled state: PendingSendRegistrationMail for " . $first_name . " " . $last_name . " (" . $username . ")\n"); print ("Error: Unhandled state: PendingSendRegistrationMail for " . $first_name . " " . $last_name . " (" . $username . ")\n");
break; break;
case RegisterState::RegistrationDeclined: case RegisterState::RegistrationDeclined:
case RegisterState::AllDone: case RegisterState::AllDone:
// do reqular cleanup // do reqular cleanup
break; break;
} }
} catch (Exception $e) { } catch (Exception $e) {
print("Error while handling cron for " . $first_name . " " . $last_name . " (" . $username . ")\n"); print("Error while handling cron for " . $first_name . " " . $last_name . " (" . $username . ")\n");
print($e->getMessage()); print($e->getMessage());
} }
} }
?> ?>

View File

@@ -1,5 +1,4 @@
<?php <?php
/** /**
* Copyright 2018 Matthias Kesler * Copyright 2018 Matthias Kesler
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
@@ -16,63 +15,65 @@
*/ */
require_once("config.php"); require_once("config.php");
if (!isset($config["databaseURI"])) { if (!isset($config["databaseURI"])) {
throw new Exception("malformed configuration: databaseURI not defined"); throw new Exception ("malformed configuration: databaseURI not defined");
} }
abstract class RegisterState { abstract class RegisterState
{
// Sending an E-Mail failed in the first attempt. Will retry later
const PendingEmailSend = 0;
// User got a mail. We wait for it to verfiy
const PendingEmailVerify = 1;
// Sending a message to the register room failed on first attempt
const PendingAdminSend = 5;
// No admin has verified the registration yet
const PendingAdminVerify = 6;
// Registration failed on first attempt. Will retry
const PendingRegistration = 7;
// Sending an E-Mail failed in the first attempt. Will retry later // in this case we have to reset the password of the user (or should we store it for this case?)
const PendingEmailSend = 0; const PendingSendRegistrationMail = 8;
// User got a mail. We wait for it to verfiy
const PendingEmailVerify = 1;
// Sending a message to the register room failed on first attempt
const PendingAdminSend = 5;
// No admin has verified the registration yet
const PendingAdminVerify = 6;
// Registration failed on first attempt. Will retry
const PendingRegistration = 7;
// in this case we have to reset the password of the user (or should we store it for this case?)
const PendingSendRegistrationMail = 8;
// State to allow persisting in the database although an admin declined it.
// Will be removed regularly
const RegistrationAccepted = 7;
const RegistrationDeclined = 13;
// User got successfully registered. Will be cleaned up later
const AllDone = 100;
// State to allow persisting in the database although an admin declined it.
// Will be removed regularly
const RegistrationAccepted = 7;
const RegistrationDeclined = 13;
// User got successfully registered. Will be cleaned up later
const AllDone = 100;
} }
class mxDatabase { class mxDatabase
{
private $db = NULL;
private $db = NULL; /**
* Creates mxDatabase object
/** * @param config object which has following members:
* Creates mxDatabase object * databaseURI: path to the sqlite file where the credentials should be stored
* @param config object which has following members: * or a param which can be used to connect to a database with PDO
* databaseURI: path to the sqlite file where the credentials should be stored * databaseUser and databasePass when authentication is required
* or a param which can be used to connect to a database with PDO * register_email which email does the register bot have (here used for providing lookup)
* databaseUser and databasePass when authentication is required */
* register_email which email does the register bot have (here used for providing lookup) function __construct($config) {
*/ if (empty($config)) {
function __construct($config) { throw new Exception("config is empty");
if (empty($config)) { }
throw new Exception("config is empty"); if (!isset($config["databaseURI"])) {
} throw new Exception("'databaseURI' not defined");
if (!isset($config["databaseURI"])) { }
throw new Exception("'databaseURI' not defined"); $db_input = $config["databaseURI"];
} $user = '';
$db_input = $config["databaseURI"]; $password = '';
$user = ''; if (isset($config["databaseUser"]) && isset($config["databasePass"])) {
$password = ''; // only use it when both are defined
if (isset($config["databaseUser"]) && isset($config["databasePass"])) { $user = $config["databaseUser"];
// only use it when both are defined $password = $config["databasePass"];
$user = $config["databaseUser"]; }
$password = $config["databasePass"]; // create database file when not existent yet
} $this->db = new PDO($db_input, $user, $password);
// create database file when not existent yet $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db = new PDO($db_input, $user, $password); $this->db->exec("CREATE TABLE IF NOT EXISTS registrations(
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db->exec("CREATE TABLE IF NOT EXISTS registrations(
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
state INT DEFAULT 0, state INT DEFAULT 0,
first_name TEXT, first_name TEXT,
@@ -85,7 +86,7 @@ class mxDatabase {
admin_token TEXT, admin_token TEXT,
request_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP request_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)"); )");
$this->db->exec("CREATE TABLE IF NOT EXISTS logins ( $this->db->exec("CREATE TABLE IF NOT EXISTS logins (
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
active INT DEFAULT 1, active INT DEFAULT 1,
first_name TEXT, first_name TEXT,
@@ -96,273 +97,255 @@ class mxDatabase {
create_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP, create_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_modified TIMESTAMP DEFAULT CURRENT_TIMESTAMP last_modified TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)"); )");
// make sure the bot is allowed to login // make sure the bot is allowed to login
if (!$this->userRegistered("register_bot")) { if (!$this->userRegistered("register_bot")) {
$password = $this->addUser("Register", "Bot", "register_bot", $config["register_email"]); $password = $this->addUser("Register", "Bot", "register_bot", $config["register_email"]);
$config["register_password"] = $password; $config["register_password"] = $password;
$myfile = fopen(dirname(__FILE__) . "/config.json", "w"); $myfile = fopen(dirname(__FILE__) . "/config.json", "w");
fwrite($myfile, json_encode($config, JSON_PRETTY_PRINT)); fwrite($myfile, json_encode($config, JSON_PRETTY_PRINT));
fclose($myfile); fclose($myfile);
} }
// set writeable when not set already // set writeable when not set already
if (strpos($db_input, "sqlite") === 0) { if (strpos($db_input, "sqlite") === 0) {
$sqlite_file = substr($db_input, strlen("sqlite:")); $sqlite_file = substr($db_input, strlen("sqlite:"));
if (!is_writable($sqlite_file)) { if (!is_writable($sqlite_file)) {
chmod($sqlite_file, 0660); chmod($sqlite_file, 0660);
} }
unset($sqlite_file); unset($sqlite_file);
} }
} }
/** /**
* WARNING: This allows accessing the database directly. * WARNING: This allows accessing the database directly.
* This was only be added for convenience. You are advised to not use this function extensively * This was only be added for convenience. You are advised to not use this function extensively
* *
* @param sql String wich will be passed directly to the database * @param sql String wich will be passed directly to the database
* @return Response of PDO::query() * @return Response of PDO::query()
*/ */
function query($sql) { function query($sql) {
return $this->db->query($sql); return $this->db->query($sql);
} }
function setRegistrationStateVerify($state, $token) { function setRegistrationStateVerify($state, $token) {
$sql = "UPDATE registrations SET state = " . $state $sql = "UPDATE registrations SET state = " . $state
. " WHERE verify_token = '" . $token . "';"; . " WHERE verify_token = '" . $token . "';";
return $this->db->exec($sql); return $this->db->exec($sql);
} }
function setRegistrationStateById($state, $id) { function setRegistrationStateById($state, $id) {
$sql = "UPDATE registrations SET state = " . $state $sql = "UPDATE registrations SET state = " . $state
. " WHERE id = '" . $id . "';"; . " WHERE id = '" . $id . "';";
return $this->db->exec($sql); return $this->db->exec($sql);
} }
function setRegistrationStateAdmin($state, $token) { function setRegistrationStateAdmin($state, $token) {
$sql = "UPDATE registrations SET state = " . $state $sql = "UPDATE registrations SET state = " . $state
. " WHERE admin_token = '" . $token . "';"; . " WHERE admin_token = '" . $token . "';";
return $this->db->exec($sql); return $this->db->exec($sql);
} }
function setRegistrationState($state, $token) { function setRegistrationState($state, $token) {
$sql = "UPDATE registrations SET state = " . $state $sql = "UPDATE registrations SET state = " . $state
. " WHERE verify_token = '" . $token . "' OR admin_token = '" . $token . "';"; . " WHERE verify_token = '" . $token . "' OR admin_token = '" . $token . "';";
return $this->db->exec($sql); return $this->db->exec($sql);
} }
function userPendingRegistrations($username) { function userPendingRegistrations($username) {
$sql = "SELECT COUNT(*) FROM registrations WHERE username = '" . $username . "' AND NOT state = " $sql = "SELECT COUNT(*) FROM registrations WHERE username = '" . $username . "' AND NOT state = "
. RegisterState::RegistrationDeclined . " LIMIT 1;"; . RegisterState::RegistrationDeclined . " LIMIT 1;";
$res = $this->db->query($sql); $res = $this->db->query($sql);
if ($res->fetchColumn() > 0) { if ($res->fetchColumn() > 0) {
return true; return true;
} }
return false; return false;
} }
function userRegistered($username) {
$sql = "SELECT COUNT(*) FROM logins WHERE localpart = '" . $username . "' LIMIT 1;";
$res = $this->db->query($sql);
if ($res->fetchColumn() > 0) {
return true;
}
return false;
}
function userRegistered($username) { /**
$sql = "SELECT COUNT(*) FROM logins WHERE localpart = '" . $username . "' LIMIT 1;"; * Adds user to the database. Next steps should be sending a verify-mail to the user
$res = $this->db->query($sql); * @param first_name First name of the user
if ($res->fetchColumn() > 0) { * @param last_name Sirname of the user
return true; * @param username the future localpart of that user
} * @param note Note the user typed in to give a hint
return false; * @param email E-Mail-Adress which will be stored into the database.
} * This will be send to the server on first login
*
* @return ["verify_token"]
*/
function addRegistration($first_name, $last_name, $username, $note, $email) {
if ($this->userPendingRegistrations($username)) {
throw new Exception("USERNAME_PENDING_REGISTRATION");
}
if ($this->userRegistered($username)) {
throw new Exception("USERNAME_REGISTERED");
}
/** $verify_token = bin2hex(random_bytes(16));
* Adds user to the database. Next steps should be sending a verify-mail to the user $admin_token = bin2hex(random_bytes(16));
* @param first_name First name of the user
* @param last_name Sirname of the user
* @param username the future localpart of that user
* @param note Note the user typed in to give a hint
* @param email E-Mail-Adress which will be stored into the database.
* This will be send to the server on first login
*
* @return ["verify_token"]
*/
function addRegistration($first_name, $last_name, $username, $note, $email) {
if ($this->userPendingRegistrations($username)) {
throw new Exception("USERNAME_PENDING_REGISTRATION");
}
if ($this->userRegistered($username)) {
throw new Exception("USERNAME_REGISTERED");
}
$verify_token = bin2hex(random_bytes(16)); $this->db->exec("INSERT INTO registrations
$admin_token = bin2hex(random_bytes(16));
$this->db->exec("INSERT INTO registrations
(first_name, last_name, username, note, email, verify_token, admin_token) (first_name, last_name, username, note, email, verify_token, admin_token)
VALUES ('" . $first_name . "','" . $last_name . "','" . $username . "','" . $note . "','" VALUES ('" . $first_name."','" . $last_name . "','" . $username . "','" . $note . "','"
. $email . "','" . $verify_token . "','" . $admin_token . "')"); . $email."','" .$verify_token."','" .$admin_token."')");
return [ return [
"verify_token" => $verify_token, "verify_token"=> $verify_token,
]; ];
} }
/** /**
* Gets the user for the verify_admin page. * Gets the user for the verify_admin page.
* *
* @return ArrayOfUser|NULL Array with "first_name, last_name, username, note and email" * @return ArrayOfUser|NULL Array with "first_name, last_name, username, note and email"
* as members * as members
*/ */
function getUserForApproval($admin_token) { function getUserForApproval($admin_token) {
$sql = "SELECT COUNT(*) FROM registrations WHERE admin_token = '" . $admin_token . "'" $sql = "SELECT COUNT(*) FROM registrations WHERE admin_token = '" . $admin_token . "'"
. " AND state = " . RegisterState::PendingAdminVerify . " LIMIT 1;"; . " AND state = " . RegisterState::PendingAdminVerify . " LIMIT 1;";
$res = $this->db->query($sql); $res = $this->db->query($sql);
$first_name = NULL; $last_name = NULL; $username = NULL; $note = NULL; $email = NULL;
if ($res->fetchColumn() > 0) { if ($res->fetchColumn() > 0) {
$sql = "SELECT first_name, last_name, username, note, email FROM registrations" $sql = "SELECT first_name, last_name, username, note, email FROM registrations"
. " WHERE admin_token = '" . $admin_token . "'" . " WHERE admin_token = '" . $admin_token . "'"
. " AND state = " . RegisterState::PendingAdminVerify . " AND state = " . RegisterState::PendingAdminVerify
. " LIMIT 1;"; . " LIMIT 1;";
foreach ($this->db->query($sql) as $row) { foreach ($this->db->query($sql) as $row) {
// will only be executed once // will only be executed once
return $row; return $row;
} }
} }
return NULL; return NULL;
} }
/** /**
* Gets the user when it opens the page to verify its mail * Gets the user when it opens the page to verify its mail
* *
* @return ArrayOfUser|NULL Array with "first_name, last_name, note, email and admin_token" * @return ArrayOfUser|NULL Array with "first_name, last_name, note, email and admin_token"
* as members * as members
*/ */
function getUserForVerify($verify_token) { function getUserForVerify($verify_token) {
$sql = "SELECT COUNT(*) FROM registrations WHERE verify_token = '" . $verify_token . "'" $sql = "SELECT COUNT(*) FROM registrations WHERE verify_token = '" . $verify_token . "'"
. " AND state = " . RegisterState::PendingEmailVerify . " LIMIT 1;"; . " AND state = " . RegisterState::PendingEmailVerify . " LIMIT 1;";
$res = $this->db->query($sql); $res = $this->db->query($sql);
$first_name = NULL; $last_name = NULL; $username = NULL; $note = NULL; $email = NULL;
if ($res->fetchColumn() > 0) { if ($res->fetchColumn() > 0) {
$sql = "SELECT first_name, last_name, note, email, admin_token FROM registrations " $sql = "SELECT first_name, last_name, note, email, admin_token FROM registrations "
. " WHERE verify_token = '" . $verify_token . "'" . " WHERE verify_token = '" . $verify_token . "'"
. " AND state = " . RegisterState::PendingEmailVerify . " LIMIT 1;"; . " AND state = " . RegisterState::PendingEmailVerify . " LIMIT 1;";
foreach ($this->db->query($sql) as $row) { foreach ($this->db->query($sql) as $row) {
// will only be executed once // will only be executed once
return $row; return $row;
} }
} }
return NULL; return NULL;
} }
function getUserForLogin($localpart, $password) { function getUserForLogin($localpart, $password) {
$sql = "SELECT COUNT(*) FROM logins WHERE localpart = '" . $localpart $sql = "SELECT COUNT(*) FROM logins WHERE localpart = '" . $localpart
. "' AND active = 1 LIMIT 1;"; . "' AND active = 1 LIMIT 1;";
$res = $this->db->query($sql); $res = $this->db->query($sql);
if ($res->fetchColumn() > 0) { if ($res->fetchColumn() > 0) {
$sql = "SELECT first_name, last_name, email, password_hash FROM logins " $sql = "SELECT first_name, last_name, email, password_hash FROM logins "
. " WHERE localpart = '" . $localpart . "' AND active = 1 LIMIT 1;"; . " WHERE localpart = '" . $localpart . "' AND active = 1 LIMIT 1;";
foreach ($this->db->query($sql) as $row) { foreach ($this->db->query($sql) as $row) {
if (password_verify($password, $row["password_hash"])) { if (password_verify($password, $row["password_hash"])) {
return $row; return $row;
} }
} }
} }
return NULL; return NULL;
} }
/** /**
* adds User to be able to login afterwards. * adds User to be able to login afterwards.
* @param first_name First name of the user * @param first_name First name of the user
* @param last_name Sirname of the user * @param last_name Sirname of the user
* @param username the future localpart of that user * @param username the future localpart of that user
* @param email E-Mail-Adress which will be stored into the database. * @param email E-Mail-Adress which will be stored into the database.
* This will be send to the server on first login * This will be send to the server on first login
* *
* @return password|NULL with member password as this method generates a * @return password|NULL with member password as this method generates a
* password and saves that into the database * password and saves that into the database
* NULL when failed * NULL when failed
* *
*/ */
function addUser($first_name, $last_name, $username, $email) { function addUser($first_name, $last_name, $username, $email) {
// check if user already exists and abort in that case // check if user already exists and abort in that case
if ($this->userRegistered($username)) { if ($this->userRegistered($username)) {
return NULL; return NULL;
} }
// generate a password with 10 characters // generate a password with 10 characters
$password = bin2hex(openssl_random_pseudo_bytes(5)); $password = bin2hex(openssl_random_pseudo_bytes(5));
$password_hash = password_hash($password, PASSWORD_BCRYPT, ["cost" => 12]); $password_hash = password_hash($password, PASSWORD_BCRYPT, ["cost"=>12]);
$sql = "INSERT INTO logins (first_name, last_name, localpart, password_hash, email) VALUES " $sql = "INSERT INTO logins (first_name, last_name, localpart, password_hash, email) VALUES "
. "('" . $first_name . "','" . $last_name . "','" . $username . "','" . "('" . $first_name."','" . $last_name . "','" . $username . "','"
. $password_hash . "','" . $email . "');"; . $password_hash . "','" . $email . "');";
if ($this->db->exec($sql)) { if ($this->db->exec($sql)) {
return $password; return $password;
} }
return NULL; return NULL;
} }
function updatePassword($localpart, $old_password, $new_password) { function searchUserByName($search_term) {
$user = $this->getUserForLogin($localpart, $old_password); $term = filter_var($search_term, FILTER_SANITIZE_STRING);
if ($user == NULL) { $result = array();
throw new Exception("user with that credentials not found"); $sql = "SELECT COUNT(*) FROM logins WHERE"
} . " localpart LIKE '" . $term . "%' AND active = 1;";
$res = $this->db->query($sql);
// The credentials were fine. So now set the new password if ($res->fetchColumn() > 0) {
$password_hash = password_hash($new_password, PASSWORD_BCRYPT, ["cost" => 12]); $sql = "SELECT first_name, last_name, localpart FROM logins WHERE"
. " localpart LIKE '" . $term . "%' AND active = 1;";
foreach ($this->db->query($sql) as $row) {
array_push($result, [
"display_name" => $row["first_name"] . " " . $row["last_name"],
"user_id" => $row["localpart"],
]);
}
}
return $result;
}
$sql = "UPDATE logins SET password_hash = '" . $password_hash . "'" function searchUserByEmail($search_term) {
. "WHERE localpart = '" . $localpart . "'"; $term = filter_var($search_term, FILTER_SANITIZE_STRING);
$result = array();
if ($this->db->exec($sql)) { $sql = "SELECT COUNT(*) FROM logins WHERE"
return true; . " email = '" . $term . "' AND active = 1;";
} $res = $this->db->query($sql);
return false;
}
function searchUserByName($search_term) {
$term = filter_var($search_term, FILTER_SANITIZE_STRING);
$result = array();
$sql = "SELECT COUNT(*) FROM logins WHERE"
. " localpart LIKE '" . $term . "%' AND active = 1;";
$res = $this->db->query($sql);
if ($res->fetchColumn() > 0) {
$sql = "SELECT first_name, last_name, localpart FROM logins WHERE"
. " localpart LIKE '" . $term . "%' AND active = 1;";
foreach ($this->db->query($sql) as $row) {
array_push($result, [
"display_name" => $row["first_name"] . " " . $row["last_name"],
"user_id" => $row["localpart"],
]);
}
}
return $result;
}
function searchUserByEmail($search_term) {
$term = filter_var($search_term, FILTER_SANITIZE_STRING);
$result = array();
$sql = "SELECT COUNT(*) FROM logins WHERE"
. " email = '" . $term . "' AND active = 1;";
$res = $this->db->query($sql);
if ($res->fetchColumn() > 0) {
$sql = "SELECT first_name, last_name, localpart FROM logins WHERE"
. " email = '" . $term . "' AND active = 1;";
foreach ($this->db->query($sql) as $row) {
array_push($result, [
"display_name" => $row["first_name"] . " " . $row["last_name"],
"user_id" => $row["localpart"],
]);
}
}
return $result;
}
if ($res->fetchColumn() > 0) {
$sql = "SELECT first_name, last_name, localpart FROM logins WHERE"
. " email = '" . $term . "' AND active = 1;";
foreach ($this->db->query($sql) as $row) {
array_push($result, [
"display_name" => $row["first_name"] . " " . $row["last_name"],
"user_id" => $row["localpart"],
]);
}
}
return $result;
}
} }
if (!isset($mx_db)) { if (!isset($mx_db)) {
$mx_db = new mxDatabase($config); $mx_db = new mxDatabase($config);
} }
?> ?>

View File

@@ -1,33 +0,0 @@
<?php
/**
* Copyright 2018 Matthias Kesler
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function stripLocalpart($mxid) {
$localpart = NULL;
if (!empty($mxid)) {
// A mxid would start with an @ so we start at the 2. position
$sepPos = strpos($mxid, ':', 1);
if ($sepPos === false) {
// : not found. Assume mxid is localpart
// TODO: further checks
$localpart = $mxid;
} else {
$localpart = substr($mxid, 1, strpos($mxid, ':') - 1);
}
}
return $localpart;
}
?>

View File

@@ -1,5 +1,4 @@
<?php <?php
/** /**
* Copyright 2018 Matthias Kesler * Copyright 2018 Matthias Kesler
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
@@ -15,7 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
require_once("../database.php"); require_once("../database.php");
$response = [ $response=[
"limited" => false, "limited" => false,
"result" => [], "result" => [],
]; ];
@@ -24,7 +23,7 @@ try {
$inputJSON = file_get_contents('php://input'); $inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE); $input = json_decode($inputJSON, TRUE);
if (empty($input)) { if (empty($input)) {
throw new Exception('no valid json as input present'); throw new Exception('no valid json as input present');
} }
if (!isset($input["by"])) { if (!isset($input["by"])) {
throw new Exception('"by" is not defined'); throw new Exception('"by" is not defined');
@@ -40,8 +39,9 @@ try {
$response["result"] = $mx_db->searchUserByEmail($input["search_term"]); $response["result"] = $mx_db->searchUserByEmail($input["search_term"]);
break; break;
default: default:
throw new Exception('unknown type for "by" param'); throw new Exception("unknown type for \"by\" param");
} }
} catch (Exception $e) { } catch (Exception $e) {
error_log("failed with error: " . $e->getMessage()); error_log("failed with error: " . $e->getMessage());
$response["error"] = $e->getMessage(); $response["error"] = $e->getMessage();

View File

@@ -1,5 +1,4 @@
<?php <?php
/** /**
* Copyright 2018 Matthias Kesler * Copyright 2018 Matthias Kesler
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
@@ -22,7 +21,7 @@ try {
$inputJSON = file_get_contents('php://input'); $inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE); $input = json_decode($inputJSON, TRUE);
if (!isset($input)) { if (!isset($input)) {
throw new Exception('request body is no valid json'); throw new Exception('request body is no valid json');
} }
if (!isset($input["lookup"])) { if (!isset($input["lookup"])) {
@@ -38,28 +37,26 @@ try {
if (!isset($lookup["address"])) { if (!isset($lookup["address"])) {
throw new Exception('"lookup.address" is not defined'); throw new Exception('"lookup.address" is not defined');
} }
$res2 = NULL; $res2 = array();
switch ($lookup["medium"]) { switch ($lookup["medium"]) {
case "email": case "email":
$res2 = $mx_db->searchUserByEmail($lookup["address"]); $res2 = $mx_db->searchUserByEmail($lookup["address"]);
if (!empty($res2)) { if (!empty($res2)) {
array_push($response["lookup"], [ array_push($response["lookup"], [
"medium" => $lookup["medium"], "medium" => $lookup["medium"],
"address" => $lookup["address"], "address" => $lookup["address"],
"id" => [ "id" => [
"type" => "localpart", "type" => "localpart",
"value" => $res2[0]["user_id"], "value" => $res2[0]["user_id"],
]
] ]
]
); );
} }
break; break;
case "msisdn": case "msisdn":
// This is reserved for number lookups
throw new Exception("unimplemented lookup medium");
break; break;
default: default:
throw new Exception("unknown lookup medium"); throw new Exception("unknown type for \"by\" param");
} }
} }
} catch (Exception $e) { } catch (Exception $e) {

View File

@@ -1,5 +1,4 @@
<?php <?php
/** /**
* Copyright 2018 Matthias Kesler * Copyright 2018 Matthias Kesler
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
@@ -20,7 +19,7 @@ try {
$inputJSON = file_get_contents('php://input'); $inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE); $input = json_decode($inputJSON, TRUE);
if (empty($input)) { if (empty($input)) {
throw new Exception('no valid json as input present'); throw new Exception('no valid json as input present');
} }
if (!isset($input["lookup"])) { if (!isset($input["lookup"])) {
throw new Exception('"lookup" is not defined'); throw new Exception('"lookup" is not defined');
@@ -31,7 +30,7 @@ try {
if (!isset($input["lookup"]["address"])) { if (!isset($input["lookup"]["address"])) {
throw new Exception('"lookup.address" is not defined'); throw new Exception('"lookup.address" is not defined');
} }
$res2 = NULL; $res2 = array();
switch ($input["lookup"]["medium"]) { switch ($input["lookup"]["medium"]) {
case "email": case "email":
$res2 = $mx_db->searchUserByEmail($input["lookup"]["address"]); $res2 = $mx_db->searchUserByEmail($input["lookup"]["address"]);
@@ -47,19 +46,15 @@ try {
] ]
]; ];
} }
break;
case "msisdn":
// This is reserved for number lookups
throw new Exception("unimplemented lookup medium");
break; break;
default: default:
throw new Exception("unknown lookup medium"); throw new Exception("unknown type for \"by\" param");
} }
} catch (Exception $e) { } catch (Exception $e) {
error_log("ídentity_single failed with error: " . $e->getMessage()); error_log("ídentity_bulk failed with error: " . $e->getMessage());
$response = [ $response["error"] = $e->getMessage();
"error" => $e->getMessage()
];
} }
print (json_encode($response, JSON_PRETTY_PRINT) . "\n"); print (json_encode($response, JSON_PRETTY_PRINT) . "\n");
?> ?>

View File

@@ -1,69 +0,0 @@
<?php
/**
* Copyright 2018 Matthias Kesler
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// URL for this: /_matrix/client/r0/account/password?access_token=$ACCESS_TOKEN
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
print ("{}");
// return with success
exit();
}
$response = new stdClass;
try {
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);
if (empty($input)) {
throw new Exception('no valid json as input present');
}
if (!isset($input["auth"])) {
throw new Exception('"auth" is not defined');
}
if (!isset($input["auth"]["user"]) || !isset($input["auth"]["password"])) {
throw new Exception('"auth.user" or "auth.password" is not defined');
}
if (!isset($input["auth"]["type"]) || $input["auth"]["type"] !== "m.login.password") {
throw new Exception('no or unknown auth.type');
}
if (!isset($input["new_password"])) {
throw new Exception('"new_password" is not defined');
}
require_once("../helpers.php");
$localpart = stripLocalpart($input["auth"]["user"]);
if (empty($localpart)) {
throw new Exception("localpart cannot be identified");
}
require_once("../database.php");
if (!$mx_db->updatePassword(
$localpart, $input["auth"]["password"], $input["new_password"]
)) {
throw new Exception("invalid credentials or another error while updating");
}
} catch (Exception $e) {
header("HTTP/1.0 500 Internal Error");
error_log("failed with error: " . $e->getMessage());
$response = [
"errorcode" => "M_UNKNOWN",
"error" => $e->getMessage(),
];
}
print (json_encode($response, JSON_PRETTY_PRINT));
?>

View File

@@ -1,5 +1,4 @@
<?php <?php
/** /**
* Copyright 2018 Matthias Kesler * Copyright 2018 Matthias Kesler
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
@@ -21,21 +20,18 @@ $response = [
]; ];
require_once("../database.php"); require_once("../database.php");
abstract class LoginRequester { abstract class LoginRequester {
const UNDEFINED = 0; const UNDEFINED = 0;
const MXISD = 1; const MXISD = 1;
const RestAuth = 2; const RestAuth = 2;
} }
$loginRequester = LoginRequester::UNDEFINED; $loginRequester = LoginRequester::UNDEFINED;
try { try {
$inputJSON = file_get_contents('php://input'); $inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE); $input = json_decode($inputJSON, TRUE);
$mxid = $localpart = NULL; $mxid = NULL;
$localpart = NULL;
if (isset($input["user"])) { if (isset($input["user"])) {
if (isset($input["user"]["localpart"])) { if (isset($input["user"]["localpart"])) {
$localpart = $input["user"]["localpart"]; $localpart = $input["user"]["localpart"];
@@ -49,27 +45,32 @@ try {
$mxid = $input["user"]["mxid"]; $mxid = $input["user"]["mxid"];
$loginRequester = LoginRequester::MXISD; $loginRequester = LoginRequester::MXISD;
} }
} else {
throw new Exception('"user" not in request body');
} }
// prefer the localpart attribute of mxisd. But in case of matrix-synapse-rest-auth // prefer the localpart attribute of mxisd. But in case of matrix-synapse-rest-auth
// we have to parse it on our own // we have to parse it on our own
if (empty($localpart)) { if (empty($localpart) && !empty($mxid)) {
require_once("../helpers.php"); // A mxid would start with an @ so we start at the 2. position
$localpart = stripLocalpart($mxid); $sepPos = strpos($mxid,':', 1);
if ($sepPos === false) {
// : not found. Assume mxid is localpart
// TODO: further checks
$localpart = $mxid;
} else {
$localpart = substr($mxid, 1, strpos($mxid,':') - 1 );
}
} }
if (empty($localpart)) { if (empty($localpart)) {
throw new Exception("localpart cannot be identified"); throw new Exception ("localpart cannot be identified");
} }
$password = NULL; $password = NULL;
if (isset($input["user"]["password"])) { if (isset($input["user"]) && isset($input["user"]["password"])) {
$password = $input["user"]["password"]; $password = $input["user"]["password"];
} }
if (empty($password)) { if (empty($password)) {
throw new Exception("password is not present"); throw new Exception ("password is not present");
} }
$user = $mx_db->getUserForLogin($localpart, $password); $user = $mx_db->getUserForLogin($localpart, $password);
@@ -101,7 +102,6 @@ try {
// only return that it was successful. // only return that it was successful.
// we do not know how the data shall be transmitted so we do nothing with it // we do not know how the data shall be transmitted so we do nothing with it
$response["auth"]["success"] = false; $response["auth"]["success"] = false;
$response["auth"]["error"] = "unidentified requester";
break; break;
} }
} catch (Exception $e) { } catch (Exception $e) {

View File

@@ -1,5 +1,4 @@
<?php <?php
/** /**
* Copyright 2018 Matthias Kesler * Copyright 2018 Matthias Kesler
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");

View File

@@ -1,5 +1,4 @@
<?php <?php
/** /**
* Copyright 2018 Matthias Kesler * Copyright 2018 Matthias Kesler
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
@@ -15,13 +14,13 @@
* limitations under the License. * limitations under the License.
*/ */
$lang = "de-de"; $lang = "de-de";
if (isset($_GET['lang'])) { if(isset($_GET['lang'])){
$lang = filter_var($_GET['lang'], FILTER_SANITIZE_STRING); $lang = filter_var($_GET['lang'], FILTER_SANITIZE_STRING);
} }
$lang_file = dirname(__FILE__) . "/lang/lang." . $lang . ".php"; $lang_file = dirname(__FILE__) . "/lang/lang.".$lang.".php";
if (!file_exists($lang_file)) { if (!file_exists($lang_file)) {
error_log("Translation for " . $lang . " not found. Fallback to 'de-de'"); error_log("Translation for " . $lang . " not found. Fallback to 'de-de'");
$lang = "de-de"; $lang = "de-de";
} }
require_once($lang_file); require_once($lang_file);
unset($lang_file); unset($lang_file);

View File

@@ -1,5 +1,4 @@
<?php <?php
/** /**
* Copyright 2018 Matthias Kesler * Copyright 2018 Matthias Kesler
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
@@ -15,15 +14,15 @@
* limitations under the License. * limitations under the License.
*/ */
function send_mail($receiver, $subject, $body) { function send_mail($receiver, $subject, $body) {
include("config.php"); include("config.php");
$headers = "From: " . $config["register_email"] . "\r\n" $headers = "From: " . $config["register_email"] . "\r\n"
. "Content-Type: text/plain;charset=utf-8"; . "Content-Type: text/plain;charset=utf-8";
return mail($receiver, $subject, $body, $headers); return mail($receiver, $subject, $body, $headers);
} }
function send_mail_pending_verification($homeserver, $user, $receiver, $verify_url) { function send_mail_pending_verification($homeserver, $user, $receiver, $verify_url) {
$subject = "Bitte bestätige Registrierung auf $homeserver"; $subject = "Bitte bestätige Registrierung auf $homeserver";
$body = "Guten Tag " . $user . ", $body = "Guten Tag " . $user . ",
Du hast anscheinend versucht dich auf $homeserver zu registrieren. Du hast anscheinend versucht dich auf $homeserver zu registrieren.
Hier gibt es eine zweistufige Registrierung. Hier gibt es eine zweistufige Registrierung.
@@ -40,12 +39,12 @@ Danach ist eine Re-Registrierung mit deinem gewünschten Nutzernamen für andere
Vielen Dank für dein Verständnis. Vielen Dank für dein Verständnis.
Das Administratoren-Team von " . $homeserver; Das Administratoren-Team von " . $homeserver;
return send_mail($receiver, $subject, $body); return send_mail($receiver, $subject, $body );
} }
function send_mail_pending_approval($homeserver, $user, $receiver) { function send_mail_pending_approval($homeserver, $user, $receiver) {
$subject = "Registrierung wartet auf Bestätigung durch Administratoren"; $subject = "Registrierung wartet auf Bestätigung durch Administratoren";
$body = "Guten Tag " . $user . ", $body = "Guten Tag " . $user . ",
Deine Registrierungsanfrage wurde verifiziert und wird nun durch die Administratoren überprüft. Deine Registrierungsanfrage wurde verifiziert und wird nun durch die Administratoren überprüft.
@@ -54,12 +53,12 @@ Du bekommst eine weitere E-Mail, sobald deine Registrierung bestätigt oder able
Vielen Dank für dein Verständnis. Vielen Dank für dein Verständnis.
Das Administratoren-Team von " . $homeserver; Das Administratoren-Team von " . $homeserver;
return send_mail($receiver, $subject, $body); return send_mail($receiver, $subject, $body );
} }
function send_mail_registration_allowed_but_failed($homeserver, $user, $receiver) { function send_mail_registration_allowed_but_failed($homeserver, $user, $receiver) {
$subject = "Registrierung auf $homeserver genehmigt."; $subject = "Registrierung auf $homeserver genehmigt.";
$body = "Guten Tag " . $user . ", $body = "Guten Tag " . $user . ",
Deine Registrierungsanfrage wurde durch die Administratoren bestätigt. Deine Registrierungsanfrage wurde durch die Administratoren bestätigt.
@@ -68,12 +67,13 @@ Wir hoffen, das Problem ist bald behoben.
Wir melden uns, wenn die Registrierung erfolgreich war. Wir melden uns, wenn die Registrierung erfolgreich war.
Das Administratoren-Team von " . $homeserver; Das Administratoren-Team von " . $homeserver;
return send_mail($receiver, $subject, $body); return send_mail($receiver, $subject, $body);
} }
function send_mail_registration_success($homeserver, $user, $receiver, $username, $password, $howToURL) { function send_mail_registration_success($homeserver, $user, $receiver, $username, $password, $howToURL) {
$subject = "Registrierung auf $homeserver erfolgreich."; $subject = "Registrierung auf $homeserver erfolgreich.";
$body = "Guten Tag " . $user . ", $body = "Guten Tag " . $user . ",
Deine Registrierungsanfrage wurde durch die Administratoren bestätigt. Deine Registrierungsanfrage wurde durch die Administratoren bestätigt.
@@ -81,42 +81,41 @@ Zum Anmelden kannst du folgende Zugangsdaten verwenden:
Nutzername: $username Nutzername: $username
Passwort: $password Passwort: $password
Hinweis: Das Passwort kannst du aktuell über die App selbst ändern. Auch wenn das Passwort nirgends Hinweis: Aktuell ist es nicht möglich, das Passwort selbst zu ändern. Sobald die Funktionalität zur
im Klartext gespeichert wird, kann jemand Zugriff auf diese Mail erlangen und so den Zugriff bekommen. Verfügung steht, gibt es aber einen Hinweis.
"; ";
/* /*
Wichtig: Bitte ändere das Passwort direkt nach der Anmeldung. Wichtig: Bitte ändere das Passwort direkt nach der Anmeldung.
Es wird zwar von unserer Seite nicht gespeichert, doch fremde könnten Zugriff auf diese E-Mail Es wird zwar von unserer Seite nicht gespeichert, doch fremde könnten Zugriff auf diese E-Mail
erhalten und so deinen Account kompromittieren. erhalten und so deinen Account kompromittieren.
*/ */
if (!empty($howToURL)) { if (!empty($howToURL)) {
$body .= " $body .= "
Zu weiteren Hilfestellungen findest du hier eine Auflistung von verschiedenen Zu weiteren Hilfestellungen findest du hier eine Auflistung von verschiedenen
Anleitungen zu verschiedenen Clients: Anleitungen zu verschiedenen Clients:
$howToURL\n"; $howToURL\n";
} }
$body .= " $body .= "
Viel Spaß bei der Verwendung von $homeserver. Viel Spaß bei der Verwendung von $homeserver.
Bei Fragen findest du nach der Anmeldung ein paar Räume in denen du sie stellen kannst. Bei Fragen findest du nach der Anmeldung ein paar Räume in denen du sie stellen kannst.
Das Administratoren-Team von " . $homeserver; Das Administratoren-Team von " . $homeserver;
return send_mail($receiver, $subject, $body); return send_mail($receiver, $subject, $body);
}
}
function send_mail_registration_decline($homeserver, $user, $receiver, $reason) { function send_mail_registration_decline($homeserver, $user, $receiver, $reason) {
$subject = "Registrierung auf $homeserver abgelehnt."; $subject = "Registrierung auf $homeserver abgelehnt.";
$body = "Guten Tag " . $user . ", $body = "Guten Tag " . $user . ",
Deine Registrierungsanfrage wurde durch die Administratoren abgelehnt.\n"; Deine Registrierungsanfrage wurde durch die Administratoren abgelehnt.\n";
if (empty($reason)) { if (empty($reason)) {
$body .= "\nEs wurde kein Grund angegeben\n"; $body .= "\nEs wurde kein Grund angegeben\n";
} else { } else {
$body .= "\nAls Grund wurde folgendes angegeben:\n$reason\n"; $body .= "\nAls Grund wurde folgendes angegeben:\n$reason\n";
} }
$body .= "\nDas Administratoren-Team von " . $homeserver; $body .= "\nDas Administratoren-Team von " . $homeserver;
return send_mail($receiver, $subject, $body); return send_mail($receiver, $subject, $body );
} }
?> ?>