From cfde5646f270fc7c8807bf151f70bbfb3f40ef81 Mon Sep 17 00:00:00 2001
From: Jan-Hendrik Willms <tleilax+studip@gmail.com>
Date: Mon, 10 Feb 2025 09:33:11 +0100
Subject: [PATCH] studip 6.0, fixes #5

---
 CookieAuth.php                            | 88 +++++++++--------------
 migrations/1_setup_user_configuration.php | 26 +++++++
 plugin.manifest                           |  4 +-
 templates/login.php                       | 10 ---
 4 files changed, 61 insertions(+), 67 deletions(-)
 create mode 100644 migrations/1_setup_user_configuration.php
 delete mode 100644 templates/login.php

diff --git a/CookieAuth.php b/CookieAuth.php
index 9445ad9..fedc88f 100644
--- a/CookieAuth.php
+++ b/CookieAuth.php
@@ -15,13 +15,13 @@
  */
 final class CookieAuth extends StudIPPlugin implements SystemPlugin
 {
-    const CONFIG_NAME = 'COOKIE_AUTH_TOKEN';
+    public const CONFIG_NAME = 'COOKIE_AUTH_TOKEN';
 
     /** @property User|null $cookie_login_user */
-    private $cookie_login_user = null;
+    private User|null $cookie_login_user = null;
 
     /** @property string $cookie_name */
-    private $cookie_name;
+    private string $cookie_name;
 
     /**
      * Initialize a new instance of the plugin.
@@ -30,19 +30,14 @@ final class CookieAuth extends StudIPPlugin implements SystemPlugin
     {
         parent::__construct();
 
-        $this->cookie_name = md5(Config::get()->STUDIP_INSTALLATION_ID) . self::class;
+        $this->cookie_name = md5(Config::get()->getValue('STUDIP_INSTALLATION_ID')) . self::class;
 
         if (!User::findCurrent()) {
             $cookie_token = $_COOKIE[$this->cookie_name] ?? null;
             if ($cookie_token) {
-                if (class_exists('UserConfigEntry')) {
-                    $user_config_entry = UserConfigEntry::findOneBySQL("field = ? AND value = ?", [self::CONFIG_NAME, $cookie_token]);
-                    $this->cookie_login_user = User::find($user_config_entry->user_id);
-                } else {
-                    $user_config_entry = ConfigValue::findOneBySQL("field = ? AND value = ?", [self::CONFIG_NAME, $cookie_token]);
-                    if ($user_config_entry) {
-                        $this->cookie_login_user = User::find($user_config_entry->range_id);
-                    }
+                $user_config_entry = ConfigValue::findOneBySQL("field = ? AND value = ?", [self::CONFIG_NAME, $cookie_token]);
+                if ($user_config_entry) {
+                    $this->cookie_login_user = User::find($user_config_entry->range_id);
                 }
 
                 if ($this->cookie_login_user && $this->cookie_login_user->locked) {
@@ -54,56 +49,44 @@ final class CookieAuth extends StudIPPlugin implements SystemPlugin
         if (isset($this->cookie_login_user)) {
             $index = array_keys(Navigation::getItem('/login')->getSubNavigation())[0];
 
-            $navigation = new Navigation(_('Direkter Login'), URLHelper::getURL('plugins.php/' . __CLASS__, ['cid' => null, 'cancel_login' => 1]));
+            $navigation = new Navigation(
+                _('Direkter Login'),
+                PluginEngine::getURL($this, ['cancel_login' => 1], 'login')
+            );
             $navigation->setDescription(sprintf(_('von Nutzer: %s'), $this->cookie_login_user->username));
             Navigation::insertItem('/login/remote_user', $navigation, $index);
-
-            if (
-                StudipVersion::olderThan('5.5')
-                && (
-                    $GLOBALS['auth']->auth['uid'] === ''
-                    || $GLOBALS['auth']->auth['uid'] === 'form'
-                )
-            ) {
-                $selector = StudipVersion::newerThan('5.2')
-                          ? '#loginbox div a'
-                          : 'div.index_main div a';
-                $this->inject_js($selector, 'login.php', [
-                    'username' => $this->cookie_login_user->username,
-                    'url'      => URLHelper::getURL('plugins.php/' . __CLASS__, ['cancel_login' => 1, 'return_to' => $_SERVER['REQUEST_URI']], true),
-                ], 'before');
-            }
         }
 
         if (match_route('dispatch.php/settings/general*')) {
             $user = User::findCurrent();
-            if ($user && $user->getConfiguration()->COOKIE_AUTH_TOKEN && !$this->cookie_login_user) {
+            if (
+                $user
+                && $user->getConfiguration()->getValue(self::CONFIG_NAME)
+                && !$this->cookie_login_user
+            ) {
                 $this->setCookie(
-                    $user->getConfiguration()->COOKIE_AUTH_TOKEN,
+                    $user->getConfiguration()->getValue(self::CONFIG_NAME),
                     strtotime('+1 year')
                 );
-                $this->cookie_login_user = $GLOBALS['user'];
+                $this->cookie_login_user = $user;
             }
             if (isset($_POST['forced_language'])) {
                 if (Request::get('cookie_auth_token')) {
-                    $token = $user->getConfiguration()->COOKIE_AUTH_TOKEN ?: $this->getNewToken();
-                    $user->getConfiguration()->store('COOKIE_AUTH_TOKEN', $token);
+                    $token = $user->getConfiguration()->getValue(self::CONFIG_NAME) ?: $this->getNewToken();
+                    $user->getConfiguration()->store(self::CONFIG_NAME, $token);
                     $this->setCookie(
                         $token,
                         strtotime('+1 year')
                     );
                 } else {
-                    $user->getConfiguration()->delete('COOKIE_AUTH_TOKEN');
+                    $user->getConfiguration()->delete(self::CONFIG_NAME);
                     $this->setCookie('', 0);
                 }
             }
 
             if (Navigation::hasItem('/profile/settings')) {
-                $selector = StudipVersion::newerThan('5.2')
-                          ? 'main#content-wrapper form fieldset'
-                          : '#layout_content form fieldset';
                 $this->inject_js(
-                    $selector,
+                    'main#content-wrapper form fieldset',
                     'settings.php',
                     ['checked' => $this->cookie_login_user],
                     'append'
@@ -112,7 +95,7 @@ final class CookieAuth extends StudIPPlugin implements SystemPlugin
         }
     }
 
-    public function show_action()
+    public function login_action(): void
     {
         $redirect = Request::get('return_to', 'index.php');
 
@@ -121,32 +104,27 @@ final class CookieAuth extends StudIPPlugin implements SystemPlugin
             && (
                 !User::findCurrent()
                 || $this->cookie_login_user->id !== User::findCurrent()->id
-           )
+            )
         ) {
-            $GLOBALS['sess']->regenerate_session_id(['auth']);
-            $GLOBALS['auth']->unauth();
-            $GLOBALS['auth']->auth['jscript'] = true;
-            $GLOBALS['auth']->auth['perm']  = $this->cookie_login_user['perms'];
-            $GLOBALS['auth']->auth['uname'] = $this->cookie_login_user['username'];
-            $GLOBALS['auth']->auth['auth_plugin']  = $this->cookie_login_user['auth_plugin'];
-            $GLOBALS['auth']->auth_set_user_settings($this->cookie_login_user->id);
-            $GLOBALS['auth']->auth['uid'] = $this->cookie_login_user->id;
+            auth()->setAuthenticatedUser($this->cookie_login_user);
         }
 
-        page_close();
         header('Location: ' . URLHelper::getURL($redirect));
-        die();
     }
 
     public static function onEnable($plugin_id)
     {
-        //allow for nobody
+        // allow for nobody
         $rp = new RolePersistence();
         $rp->assignPluginRoles($plugin_id, range(1, 7));
     }
 
-    private function inject_js(string $selector, string $template, array $variables, string $location = 'after')
-    {
+    private function inject_js(
+        string $selector,
+        string $template,
+        array $variables = [],
+        string $location = 'after'
+    ): void {
         $factory = new Flexi_TemplateFactory(__DIR__ . '/templates');
         $snippet = $factory->render($template, $variables);
         $snippet = str_replace("\n", "\\\n", $snippet);
@@ -161,7 +139,7 @@ final class CookieAuth extends StudIPPlugin implements SystemPlugin
         );
     }
 
-    private function setCookie(string $value, int $expires)
+    private function setCookie(string $value, int $expires): void
     {
         $url_parts = parse_url($GLOBALS['ABSOLUTE_URI_STUDIP']);
 
diff --git a/migrations/1_setup_user_configuration.php b/migrations/1_setup_user_configuration.php
new file mode 100644
index 0000000..d42b8b9
--- /dev/null
+++ b/migrations/1_setup_user_configuration.php
@@ -0,0 +1,26 @@
+<?php
+final class SetupUserConfiguration extends Migration
+{
+    public function __construct($verbose = false)
+    {
+        parent::__construct($verbose);
+
+        require_once __DIR__ . '/../CookieAuth.php';
+    }
+
+    public function up()
+    {
+        Config::get()->create(CookieAuth::CONFIG_NAME, [
+            'value'       => '',
+            'type'        => 'string',
+            'range'       => 'user',
+            'section'     => '',
+            'description' => 'Token für die Authentifizierung via CookieAuth',
+        ]);
+    }
+
+    protected function down()
+    {
+        Config::get()->delete(CookieAuth::CONFIG_NAME);
+    }
+}
diff --git a/plugin.manifest b/plugin.manifest
index 73d754f..2eabe6a 100644
--- a/plugin.manifest
+++ b/plugin.manifest
@@ -1,5 +1,5 @@
 pluginname=CookieAuth
 pluginclassname=CookieAuth
 origin=data-quest
-version=10
-studipMinVersion=4.0
+version=1.0
+studipMinVersion=6.0
diff --git a/templates/login.php b/templates/login.php
deleted file mode 100644
index 91616ce..0000000
--- a/templates/login.php
+++ /dev/null
@@ -1,10 +0,0 @@
-<?php
-/**
- * @var string $url
- * @var string $username
- */
-?>
-<a href="<?= htmlReady($url) ?>">
-    <?= sprintf(_('Direkter Login von "%s"'), htmlReady($username)) ?>
-</a>
- /
-- 
GitLab