federator/php/dio/user.php

111 lines
3.4 KiB
PHP

<?php
/**
* SPDX-FileCopyrightText: 2024 Sascha Nitsch (grumpydeveloper) https://contentnation.net/@grumpydevelop
* SPDX-License-Identifier: GPL-3.0-or-later
*
* @author Sascha Nitsch (grumpydeveloper)
**/
namespace Federator\DIO;
/**
* IO functions related to users
*/
class User
{
/**
* add local user based on given user object received from remote service
* @param \mysqli $dbh database handle
* @param \Federator\Data\User $user user object to use
* @param string $_user user/profile name
* @return void
*/
protected static function addLocalUser($dbh, $user, $_user)
{
echo "a new user\n";
// needed fields: RSA key pair, user name (handle)
$private_key = openssl_pkey_new();
if ($private_key === false) {
throw new \Federator\Exceptions\ServerError();
}
$public = openssl_pkey_get_details($private_key)['key'];
$private = '';
openssl_pkey_export($private_key, $private);
$sql = 'insert into users (id, externalid, rsapublic, rsaprivate) values (?, ?, ?, ?)';
$stmt = $dbh->prepare($sql);
if ($stmt === false) {
throw new \Federator\Exceptions\ServerError();
}
$stmt->bind_param("ssss", $_user, $user->externalid, $public, $private);
$stmt->execute();
$stmt->close();
}
/**
* extend the given user with internal data
* @param \mysqli $dbh database handle
* @param \Federator\Data\User $user user to extend
* @param string $_user user/profile name
*/
protected static function extendUser(\mysqli $dbh, $user, $_user) : void
{
$sql = 'select id from users where id=?';
$stmt = $dbh->prepare($sql);
if ($stmt === false) {
throw new \Federator\Exceptions\ServerError();
}
$stmt->bind_param("s", $_user);
$ret = $stmt->bind_result($user->id);
$stmt->execute();
if ($ret) {
$stmt->fetch();
}
$stmt->close();
// if a new user, create own database entry with additionally needed info
if ($user->id === null) {
self::addLocalUser($dbh, $user, $_user);
}
// no further processing for now
}
/**
* get User by session id
*
* @param \mysqli $dbh
* database handle
* @param string $_session
* session
* @param string $_user
* user/profile name
* @param \Federator\Connector\Connector $connector
* connector to fetch use with
* @param \Federator\Cache\Cache|null $cache
* optional caching service
* @return \Federator\Data\User|false
*/
public static function getUserBySession($dbh, $_session, $_user, $connector, $cache)
{
$saveToCache = false;
$user = false;
if ($cache !== null) {
$user = $cache->getRemoteUserBySession($_session, $_user);
}
if ($user === false) {
// ask connector for user-id
$user = $connector->getRemoteUserBySession($_session, $_user);
$saveToCache = true;
}
if ($user === false) {
return false;
}
self::extendUser($dbh, $user, $_user);
if ($cache !== null && $saveToCache) {
$cache->saveRemoteUserBySession($_session, $_user, $user);
}
return $user;
}
}