Browse Source

Generate a random API key on initial setup (fixes #1118)

Also makes the javascript implementation use the same algorithm for
generating random strings.
Jakob Borg 11 years ago
parent
commit
20d30a80be

+ 5 - 8
gui/scripts/syncthing/app.js

@@ -104,15 +104,12 @@ function decimals(val, num) {
     return decs;
 }
 
-function randomString(len, bits) {
-    bits = bits || 36;
-    var outStr = "",
-        newStr;
-    while (outStr.length < len) {
-        newStr = Math.random().toString(bits).slice(2);
-        outStr += newStr.slice(0, Math.min(newStr.length, (len - outStr.length)));
+function randomString(len) {
+    var i, result = '', chars = '01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-';
+    for (i = 0; i < len; i++) {
+        result += chars[Math.round(Math.random() * (chars.length - 1))];
     }
-    return outStr.toLowerCase();
+    return result;
 }
 
 function isEmptyObject(obj) {

+ 1 - 1
gui/scripts/syncthing/core/controllers/syncthingController.js

@@ -994,7 +994,7 @@ angular.module('syncthing.core')
         };
 
         $scope.setAPIKey = function (cfg) {
-            cfg.APIKey = randomString(30, 32);
+            cfg.APIKey = randomString(32);
         };
 
         $scope.showURPreview = function () {

File diff suppressed because it is too large
+ 0 - 0
internal/auto/gui.files.go


+ 18 - 0
internal/config/config.go

@@ -20,6 +20,7 @@ import (
 	"encoding/xml"
 	"fmt"
 	"io"
+	"math/rand"
 	"os"
 	"path/filepath"
 	"reflect"
@@ -369,6 +370,10 @@ func (cfg *Configuration) prepare(myID protocol.DeviceID) {
 
 	cfg.Options.ListenAddress = uniqueStrings(cfg.Options.ListenAddress)
 	cfg.Options.GlobalAnnServers = uniqueStrings(cfg.Options.GlobalAnnServers)
+
+	if cfg.GUI.APIKey == "" {
+		cfg.GUI.APIKey = randomString(32)
+	}
 }
 
 // ChangeRequiresRestart returns true if updating the configuration requires a
@@ -674,3 +679,16 @@ func (l FolderDeviceConfigurationList) Swap(a, b int) {
 func (l FolderDeviceConfigurationList) Len() int {
 	return len(l)
 }
+
+// randomCharset contains the characters that can make up a randomString().
+const randomCharset = "01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-"
+
+// randomString returns a string of random characters (taken from
+// randomCharset) of the specified length.
+func randomString(l int) string {
+	bs := make([]byte, l)
+	for i := range bs {
+		bs[i] = randomCharset[rand.Intn(len(randomCharset))]
+	}
+	return string(bs)
+}

Some files were not shown because too many files changed in this diff