From bfc0bde05d409e4b29d6883362210c471a4129c5 Mon Sep 17 00:00:00 2001 From: Bastard Operator Date: Sat, 27 Nov 2021 01:36:34 +0100 Subject: [PATCH] Added session creation on Mastodon + Add migration --- .../00004-create-oauth_tokens-table.sql | 7 ++++ src/action/oauth/mastodon.php | 39 ++++++++++++++----- 2 files changed, 36 insertions(+), 10 deletions(-) create mode 100644 migrations/00004-create-oauth_tokens-table.sql diff --git a/migrations/00004-create-oauth_tokens-table.sql b/migrations/00004-create-oauth_tokens-table.sql new file mode 100644 index 0000000..d163ca8 --- /dev/null +++ b/migrations/00004-create-oauth_tokens-table.sql @@ -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 +); diff --git a/src/action/oauth/mastodon.php b/src/action/oauth/mastodon.php index 0e81a6c..7375791 100644 --- a/src/action/oauth/mastodon.php +++ b/src/action/oauth/mastodon.php @@ -36,17 +36,36 @@ if (!preg_match('/^[a-zA-Z0-9_]+$/', $output->acct)) hres(500, 'Server returned incorrect user data, please contact the administrators'); # check user exists by acct +$id_user = -1; $acct = '@'.$output->acct.'@'.preg_replace('/^https:\/\//', '', $payload->instance); $sm = $db->prepare('SELECT id FROM users WHERE acct = ? LIMIT 1'); $sm->execute([$acct]); -if ($sm->fetch() === false) { - echo 'User not exists. Create it'; -} else { - echo 'User exists. Update data'; -} -die; +$user = $sm->fetch(); -var_dump($output); -echo '

'; -var_dump($payload); -die; +if ($user === false) +{ + $sm = $db->prepare('INSERT INTO users (acct, account_data, account_type) VALUES (?, ?, ?)'); + 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: /');