Added session creation on Mastodon + Add migration

This commit is contained in:
Bofh 2021-11-27 01:36:34 +01:00
parent 40374fa3a7
commit bfc0bde05d
2 changed files with 36 additions and 10 deletions

View File

@ -0,0 +1,7 @@
CREATE TABLE IF NOT EXISTS oauth_tokens (
id serial PRIMARY KEY,
id_user INTEGER NOT NULL,
cookie VARCHAR(64) UNIQUE NOT NULL,
access_token VARCHAR(128) NOT NULL,
created_on TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

View File

@ -36,17 +36,36 @@ if (!preg_match('/^[a-zA-Z0-9_]+$/', $output->acct))
hres(500, 'Server returned incorrect user data, please contact the administrators'); hres(500, 'Server returned incorrect user data, please contact the administrators');
# check user exists by acct # check user exists by acct
$id_user = -1;
$acct = '@'.$output->acct.'@'.preg_replace('/^https:\/\//', '', $payload->instance); $acct = '@'.$output->acct.'@'.preg_replace('/^https:\/\//', '', $payload->instance);
$sm = $db->prepare('SELECT id FROM users WHERE acct = ? LIMIT 1'); $sm = $db->prepare('SELECT id FROM users WHERE acct = ? LIMIT 1');
$sm->execute([$acct]); $sm->execute([$acct]);
if ($sm->fetch() === false) { $user = $sm->fetch();
echo 'User not exists. Create it';
} else {
echo 'User exists. Update data';
}
die;
var_dump($output); if ($user === false)
echo '<br><br>'; {
var_dump($payload); $sm = $db->prepare('INSERT INTO users (acct, account_data, account_type) VALUES (?, ?, ?)');
die; if (!$sm->execute([$acct, json_encode($output), 'mastodon']))
hres(500, 'Server error. Could not create the user on the system. Please contact administrators');
$id_user = $db->lastInsertId();
}
else
{
$sm = $db->prepare('UPDATE users SET account_data = ? WHERE id = ?');
if (!$sm->execute([json_encode($output), $user['id']]))
hres(500, 'Server error. Could not update user account data. Please contact administrators');
$id_user = $user['id'];
}
# create cookie and add access_token
$cookie = hash_hmac('sha256', $auth->access_token.$id_user, 'session');
$sm = $db->prepare('INSERT INTO oauth_tokens (id_user, cookie, access_token) VALUES (?, ?, ?)');
try {
$sm->execute([$id_user, $cookie, $auth->access_token]);
} catch (PDOException $e) {
# TODO: log error
}
# set session cookie and redirect (60 days)
setcookie('rf_sess', $cookie, time()+(60*(60*60*24)), '/');
header('Location: /');