From cbfdcff2615e901bdc434d06f38a3da8eecbdf8b Mon Sep 17 00:00:00 2001
From: ArthurHoaro <arthur@hoa.ro>
Date: Sun, 31 Jul 2016 10:46:17 +0200
Subject: Prepare settings for the API in the admin page and during the install

API settings:
   - api.enabled
   - api.secret

The API settings will be initialized (and the secret generated) with an update method.
---
 application/Utils.php | 26 ++++++++++++++++++++++++++
 1 file changed, 26 insertions(+)

(limited to 'application/Utils.php')

diff --git a/application/Utils.php b/application/Utils.php
index 0a5b476e..62902341 100644
--- a/application/Utils.php
+++ b/application/Utils.php
@@ -231,3 +231,29 @@ function autoLocale($headerLocale)
     }
     setlocale(LC_ALL, $attempts);
 }
+
+/**
+ * Generates a default API secret.
+ *
+ * Note that the random-ish methods used in this function are predictable,
+ * which makes them NOT suitable for crypto.
+ * BUT the random string is salted with the salt and hashed with the username.
+ * It makes the generated API secret secured enough for Shaarli.
+ *
+ * PHP 7 provides random_int(), designed for cryptography.
+ * More info: http://stackoverflow.com/questions/4356289/php-random-string-generator
+
+ * @param string $username Shaarli login username
+ * @param string $salt     Shaarli password hash salt
+ *
+ * @return string|bool Generated API secret, 12 char length.
+ *                     Or false if invalid parameters are provided (which will make the API unusable).
+ */
+function generate_api_secret($username, $salt)
+{
+    if (empty($username) || empty($salt)) {
+        return false;
+    }
+
+    return str_shuffle(substr(hash_hmac('sha512', uniqid($salt), $username), 10, 12));
+}
-- 
cgit v1.2.3