Completed
Pull Request — master (#4212)
by Individual IT
13:52
created
apps/federatedfilesharing/lib/AddressHandler.php 1 patch
Indentation   +118 added lines, -118 removed lines patch added patch discarded remove patch
@@ -33,122 +33,122 @@
 block discarded – undo
33 33
  */
34 34
 class AddressHandler {
35 35
 
36
-	/** @var IL10N */
37
-	private $l;
38
-
39
-	/** @var IURLGenerator */
40
-	private $urlGenerator;
41
-
42
-	/** @var ICloudIdManager */
43
-	private $cloudIdManager;
44
-
45
-	/**
46
-	 * AddressHandler constructor.
47
-	 *
48
-	 * @param IURLGenerator $urlGenerator
49
-	 * @param IL10N $il10n
50
-	 * @param ICloudIdManager $cloudIdManager
51
-	 */
52
-	public function __construct(
53
-		IURLGenerator $urlGenerator,
54
-		IL10N $il10n,
55
-		ICloudIdManager $cloudIdManager
56
-	) {
57
-		$this->l = $il10n;
58
-		$this->urlGenerator = $urlGenerator;
59
-		$this->cloudIdManager = $cloudIdManager;
60
-	}
61
-
62
-	/**
63
-	 * split user and remote from federated cloud id
64
-	 *
65
-	 * @param string $address federated share address
66
-	 * @return array [user, remoteURL]
67
-	 * @throws HintException
68
-	 */
69
-	public function splitUserRemote($address) {
70
-		try {
71
-			$cloudId = $this->cloudIdManager->resolveCloudId($address);
72
-			return [$cloudId->getUser(), $cloudId->getRemote()];
73
-		} catch (\InvalidArgumentException $e) {
74
-			$hint = $this->l->t('Invalid Federated Cloud ID');
75
-			throw new HintException('Invalid Federated Cloud ID', $hint, 0, $e);
76
-		}
77
-	}
78
-
79
-	/**
80
-	 * generate remote URL part of federated ID
81
-	 *
82
-	 * @return string url of the current server
83
-	 */
84
-	public function generateRemoteURL() {
85
-		$url = $this->urlGenerator->getAbsoluteURL('/');
86
-		return $url;
87
-	}
88
-
89
-	/**
90
-	 * check if two federated cloud IDs refer to the same user
91
-	 *
92
-	 * @param string $user1
93
-	 * @param string $server1
94
-	 * @param string $user2
95
-	 * @param string $server2
96
-	 * @return bool true if both users and servers are the same
97
-	 */
98
-	public function compareAddresses($user1, $server1, $user2, $server2) {
99
-		$normalizedServer1 = strtolower($this->removeProtocolFromUrl($server1));
100
-		$normalizedServer2 = strtolower($this->removeProtocolFromUrl($server2));
101
-
102
-		if (rtrim($normalizedServer1, '/') === rtrim($normalizedServer2, '/')) {
103
-			// FIXME this should be a method in the user management instead
104
-			\OCP\Util::emitHook(
105
-				'\OCA\Files_Sharing\API\Server2Server',
106
-				'preLoginNameUsedAsUserName',
107
-				array('uid' => &$user1)
108
-			);
109
-			\OCP\Util::emitHook(
110
-				'\OCA\Files_Sharing\API\Server2Server',
111
-				'preLoginNameUsedAsUserName',
112
-				array('uid' => &$user2)
113
-			);
114
-
115
-			if ($user1 === $user2) {
116
-				return true;
117
-			}
118
-		}
119
-
120
-		return false;
121
-	}
122
-
123
-	/**
124
-	 * remove protocol from URL
125
-	 *
126
-	 * @param string $url
127
-	 * @return string
128
-	 */
129
-	public function removeProtocolFromUrl($url) {
130
-		if (strpos($url, 'https://') === 0) {
131
-			return substr($url, strlen('https://'));
132
-		} else if (strpos($url, 'http://') === 0) {
133
-			return substr($url, strlen('http://'));
134
-		}
135
-
136
-		return $url;
137
-	}
138
-
139
-	/**
140
-	 * check if the url contain the protocol (http or https)
141
-	 *
142
-	 * @param string $url
143
-	 * @return bool
144
-	 */
145
-	public function urlContainProtocol($url) {
146
-		if (strpos($url, 'https://') === 0 ||
147
-			strpos($url, 'http://') === 0) {
148
-
149
-			return true;
150
-		}
151
-
152
-		return false;
153
-	}
36
+    /** @var IL10N */
37
+    private $l;
38
+
39
+    /** @var IURLGenerator */
40
+    private $urlGenerator;
41
+
42
+    /** @var ICloudIdManager */
43
+    private $cloudIdManager;
44
+
45
+    /**
46
+     * AddressHandler constructor.
47
+     *
48
+     * @param IURLGenerator $urlGenerator
49
+     * @param IL10N $il10n
50
+     * @param ICloudIdManager $cloudIdManager
51
+     */
52
+    public function __construct(
53
+        IURLGenerator $urlGenerator,
54
+        IL10N $il10n,
55
+        ICloudIdManager $cloudIdManager
56
+    ) {
57
+        $this->l = $il10n;
58
+        $this->urlGenerator = $urlGenerator;
59
+        $this->cloudIdManager = $cloudIdManager;
60
+    }
61
+
62
+    /**
63
+     * split user and remote from federated cloud id
64
+     *
65
+     * @param string $address federated share address
66
+     * @return array [user, remoteURL]
67
+     * @throws HintException
68
+     */
69
+    public function splitUserRemote($address) {
70
+        try {
71
+            $cloudId = $this->cloudIdManager->resolveCloudId($address);
72
+            return [$cloudId->getUser(), $cloudId->getRemote()];
73
+        } catch (\InvalidArgumentException $e) {
74
+            $hint = $this->l->t('Invalid Federated Cloud ID');
75
+            throw new HintException('Invalid Federated Cloud ID', $hint, 0, $e);
76
+        }
77
+    }
78
+
79
+    /**
80
+     * generate remote URL part of federated ID
81
+     *
82
+     * @return string url of the current server
83
+     */
84
+    public function generateRemoteURL() {
85
+        $url = $this->urlGenerator->getAbsoluteURL('/');
86
+        return $url;
87
+    }
88
+
89
+    /**
90
+     * check if two federated cloud IDs refer to the same user
91
+     *
92
+     * @param string $user1
93
+     * @param string $server1
94
+     * @param string $user2
95
+     * @param string $server2
96
+     * @return bool true if both users and servers are the same
97
+     */
98
+    public function compareAddresses($user1, $server1, $user2, $server2) {
99
+        $normalizedServer1 = strtolower($this->removeProtocolFromUrl($server1));
100
+        $normalizedServer2 = strtolower($this->removeProtocolFromUrl($server2));
101
+
102
+        if (rtrim($normalizedServer1, '/') === rtrim($normalizedServer2, '/')) {
103
+            // FIXME this should be a method in the user management instead
104
+            \OCP\Util::emitHook(
105
+                '\OCA\Files_Sharing\API\Server2Server',
106
+                'preLoginNameUsedAsUserName',
107
+                array('uid' => &$user1)
108
+            );
109
+            \OCP\Util::emitHook(
110
+                '\OCA\Files_Sharing\API\Server2Server',
111
+                'preLoginNameUsedAsUserName',
112
+                array('uid' => &$user2)
113
+            );
114
+
115
+            if ($user1 === $user2) {
116
+                return true;
117
+            }
118
+        }
119
+
120
+        return false;
121
+    }
122
+
123
+    /**
124
+     * remove protocol from URL
125
+     *
126
+     * @param string $url
127
+     * @return string
128
+     */
129
+    public function removeProtocolFromUrl($url) {
130
+        if (strpos($url, 'https://') === 0) {
131
+            return substr($url, strlen('https://'));
132
+        } else if (strpos($url, 'http://') === 0) {
133
+            return substr($url, strlen('http://'));
134
+        }
135
+
136
+        return $url;
137
+    }
138
+
139
+    /**
140
+     * check if the url contain the protocol (http or https)
141
+     *
142
+     * @param string $url
143
+     * @return bool
144
+     */
145
+    public function urlContainProtocol($url) {
146
+        if (strpos($url, 'https://') === 0 ||
147
+            strpos($url, 'http://') === 0) {
148
+
149
+            return true;
150
+        }
151
+
152
+        return false;
153
+    }
154 154
 }
Please login to merge, or discard this patch.
apps/federation/templates/settings-admin.php 1 patch
Indentation   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -28,10 +28,10 @@
 block discarded – undo
28 28
 				<?php if((int)$trustedServer['status'] === TrustedServers::STATUS_OK) { ?>
29 29
 					<span class="status success"></span>
30 30
 				<?php
31
-				} elseif(
32
-					(int)$trustedServer['status'] === TrustedServers::STATUS_PENDING ||
33
-					(int)$trustedServer['status'] === TrustedServers::STATUS_ACCESS_REVOKED
34
-				) { ?>
31
+                } elseif(
32
+                    (int)$trustedServer['status'] === TrustedServers::STATUS_PENDING ||
33
+                    (int)$trustedServer['status'] === TrustedServers::STATUS_ACCESS_REVOKED
34
+                ) { ?>
35 35
 					<span class="status indeterminate"></span>
36 36
 				<?php } else {?>
37 37
 					<span class="status error"></span>
Please login to merge, or discard this patch.
apps/federation/lib/DAV/FedAuth.php 1 patch
Indentation   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -29,40 +29,40 @@
 block discarded – undo
29 29
 
30 30
 class FedAuth extends AbstractBasic {
31 31
 
32
-	/** @var DbHandler */
33
-	private $db;
32
+    /** @var DbHandler */
33
+    private $db;
34 34
 
35
-	/**
36
-	 * FedAuth constructor.
37
-	 *
38
-	 * @param DbHandler $db
39
-	 */
40
-	public function __construct(DbHandler $db) {
41
-		$this->db = $db;
42
-		$this->principalPrefix = 'principals/system/';
35
+    /**
36
+     * FedAuth constructor.
37
+     *
38
+     * @param DbHandler $db
39
+     */
40
+    public function __construct(DbHandler $db) {
41
+        $this->db = $db;
42
+        $this->principalPrefix = 'principals/system/';
43 43
 
44
-		// setup realm
45
-		$defaults = new \OCP\Defaults();
46
-		$this->realm = $defaults->getName();
47
-	}
44
+        // setup realm
45
+        $defaults = new \OCP\Defaults();
46
+        $this->realm = $defaults->getName();
47
+    }
48 48
 
49
-	/**
50
-	 * Validates a username and password
51
-	 *
52
-	 * This method should return true or false depending on if login
53
-	 * succeeded.
54
-	 *
55
-	 * @param string $username
56
-	 * @param string $password
57
-	 * @return bool
58
-	 */
59
-	protected function validateUserPass($username, $password) {
60
-		return $this->db->auth($username, $password);
61
-	}
49
+    /**
50
+     * Validates a username and password
51
+     *
52
+     * This method should return true or false depending on if login
53
+     * succeeded.
54
+     *
55
+     * @param string $username
56
+     * @param string $password
57
+     * @return bool
58
+     */
59
+    protected function validateUserPass($username, $password) {
60
+        return $this->db->auth($username, $password);
61
+    }
62 62
 
63
-	/**
64
-	 * @inheritdoc
65
-	 */
66
-	function challenge(RequestInterface $request, ResponseInterface $response) {
67
-	}
63
+    /**
64
+     * @inheritdoc
65
+     */
66
+    function challenge(RequestInterface $request, ResponseInterface $response) {
67
+    }
68 68
 }
Please login to merge, or discard this patch.
apps/federation/lib/Controller/SettingsController.php 1 patch
Indentation   +86 added lines, -86 removed lines patch added patch discarded remove patch
@@ -34,91 +34,91 @@
 block discarded – undo
34 34
 
35 35
 class SettingsController extends Controller {
36 36
 
37
-	/** @var IL10N */
38
-	private $l;
39
-
40
-	/** @var  TrustedServers */
41
-	private $trustedServers;
42
-
43
-	/**
44
-	 * @param string $AppName
45
-	 * @param IRequest $request
46
-	 * @param IL10N $l10n
47
-	 * @param TrustedServers $trustedServers
48
-	 */
49
-	public function __construct($AppName,
50
-								IRequest $request,
51
-								IL10N $l10n,
52
-								TrustedServers $trustedServers
53
-	) {
54
-		parent::__construct($AppName, $request);
55
-		$this->l = $l10n;
56
-		$this->trustedServers = $trustedServers;
57
-	}
58
-
59
-
60
-	/**
61
-	 * add server to the list of trusted ownClouds
62
-	 *
63
-	 * @param string $url
64
-	 * @return DataResponse
65
-	 * @throws HintException
66
-	 */
67
-	public function addServer($url) {
68
-		$this->checkServer($url);
69
-		$id = $this->trustedServers->addServer($url);
70
-
71
-		return new DataResponse(
72
-			[
73
-				'url' => $url,
74
-				'id' => $id,
75
-				'message' => (string) $this->l->t('Added to the list of trusted servers')
76
-			]
77
-		);
78
-	}
79
-
80
-	/**
81
-	 * add server to the list of trusted ownClouds
82
-	 *
83
-	 * @param int $id
84
-	 * @return DataResponse
85
-	 */
86
-	public function removeServer($id) {
87
-		$this->trustedServers->removeServer($id);
88
-		return new DataResponse();
89
-	}
90
-
91
-	/**
92
-	 * enable/disable to automatically add servers to the list of trusted servers
93
-	 * once a federated share was created and accepted successfully
94
-	 *
95
-	 * @param bool $autoAddServers
96
-	 */
97
-	public function autoAddServers($autoAddServers) {
98
-		$this->trustedServers->setAutoAddServers($autoAddServers);
99
-	}
100
-
101
-	/**
102
-	 * check if the server should be added to the list of trusted servers or not
103
-	 *
104
-	 * @param string $url
105
-	 * @return bool
106
-	 * @throws HintException
107
-	 */
108
-	protected function checkServer($url) {
109
-		if ($this->trustedServers->isTrustedServer($url) === true) {
110
-			$message = 'Server is already in the list of trusted servers.';
111
-			$hint = $this->l->t('Server is already in the list of trusted servers.');
112
-			throw new HintException($message, $hint);
113
-		}
114
-
115
-		if ($this->trustedServers->isOwnCloudServer($url) === false) {
116
-			$message = 'No server to federate with found';
117
-			$hint = $this->l->t('No server to federate with found');
118
-			throw new HintException($message, $hint);
119
-		}
120
-
121
-		return true;
122
-	}
37
+    /** @var IL10N */
38
+    private $l;
39
+
40
+    /** @var  TrustedServers */
41
+    private $trustedServers;
42
+
43
+    /**
44
+     * @param string $AppName
45
+     * @param IRequest $request
46
+     * @param IL10N $l10n
47
+     * @param TrustedServers $trustedServers
48
+     */
49
+    public function __construct($AppName,
50
+                                IRequest $request,
51
+                                IL10N $l10n,
52
+                                TrustedServers $trustedServers
53
+    ) {
54
+        parent::__construct($AppName, $request);
55
+        $this->l = $l10n;
56
+        $this->trustedServers = $trustedServers;
57
+    }
58
+
59
+
60
+    /**
61
+     * add server to the list of trusted ownClouds
62
+     *
63
+     * @param string $url
64
+     * @return DataResponse
65
+     * @throws HintException
66
+     */
67
+    public function addServer($url) {
68
+        $this->checkServer($url);
69
+        $id = $this->trustedServers->addServer($url);
70
+
71
+        return new DataResponse(
72
+            [
73
+                'url' => $url,
74
+                'id' => $id,
75
+                'message' => (string) $this->l->t('Added to the list of trusted servers')
76
+            ]
77
+        );
78
+    }
79
+
80
+    /**
81
+     * add server to the list of trusted ownClouds
82
+     *
83
+     * @param int $id
84
+     * @return DataResponse
85
+     */
86
+    public function removeServer($id) {
87
+        $this->trustedServers->removeServer($id);
88
+        return new DataResponse();
89
+    }
90
+
91
+    /**
92
+     * enable/disable to automatically add servers to the list of trusted servers
93
+     * once a federated share was created and accepted successfully
94
+     *
95
+     * @param bool $autoAddServers
96
+     */
97
+    public function autoAddServers($autoAddServers) {
98
+        $this->trustedServers->setAutoAddServers($autoAddServers);
99
+    }
100
+
101
+    /**
102
+     * check if the server should be added to the list of trusted servers or not
103
+     *
104
+     * @param string $url
105
+     * @return bool
106
+     * @throws HintException
107
+     */
108
+    protected function checkServer($url) {
109
+        if ($this->trustedServers->isTrustedServer($url) === true) {
110
+            $message = 'Server is already in the list of trusted servers.';
111
+            $hint = $this->l->t('Server is already in the list of trusted servers.');
112
+            throw new HintException($message, $hint);
113
+        }
114
+
115
+        if ($this->trustedServers->isOwnCloudServer($url) === false) {
116
+            $message = 'No server to federate with found';
117
+            $hint = $this->l->t('No server to federate with found');
118
+            throw new HintException($message, $hint);
119
+        }
120
+
121
+        return true;
122
+    }
123 123
 
124 124
 }
Please login to merge, or discard this patch.
apps/federation/lib/Controller/OCSAuthAPIController.php 1 patch
Indentation   +133 added lines, -133 removed lines patch added patch discarded remove patch
@@ -46,138 +46,138 @@
 block discarded – undo
46 46
  */
47 47
 class OCSAuthAPIController extends OCSController{
48 48
 
49
-	/** @var ISecureRandom  */
50
-	private $secureRandom;
51
-
52
-	/** @var IJobList */
53
-	private $jobList;
54
-
55
-	/** @var TrustedServers */
56
-	private $trustedServers;
57
-
58
-	/** @var DbHandler */
59
-	private $dbHandler;
60
-
61
-	/** @var ILogger */
62
-	private $logger;
63
-
64
-	/**
65
-	 * OCSAuthAPI constructor.
66
-	 *
67
-	 * @param string $appName
68
-	 * @param IRequest $request
69
-	 * @param ISecureRandom $secureRandom
70
-	 * @param IJobList $jobList
71
-	 * @param TrustedServers $trustedServers
72
-	 * @param DbHandler $dbHandler
73
-	 * @param ILogger $logger
74
-	 */
75
-	public function __construct(
76
-		$appName,
77
-		IRequest $request,
78
-		ISecureRandom $secureRandom,
79
-		IJobList $jobList,
80
-		TrustedServers $trustedServers,
81
-		DbHandler $dbHandler,
82
-		ILogger $logger
83
-	) {
84
-		parent::__construct($appName, $request);
85
-
86
-		$this->secureRandom = $secureRandom;
87
-		$this->jobList = $jobList;
88
-		$this->trustedServers = $trustedServers;
89
-		$this->dbHandler = $dbHandler;
90
-		$this->logger = $logger;
91
-	}
92
-
93
-	/**
94
-	 * @NoCSRFRequired
95
-	 * @PublicPage
96
-	 *
97
-	 * request received to ask remote server for a shared secret
98
-	 *
99
-	 * @param string $url
100
-	 * @param string $token
101
-	 * @return Http\DataResponse
102
-	 * @throws OCSForbiddenException
103
-	 */
104
-	public function requestSharedSecret($url, $token) {
105
-		if ($this->trustedServers->isTrustedServer($url) === false) {
106
-			$this->logger->error('remote server not trusted (' . $url . ') while requesting shared secret', ['app' => 'federation']);
107
-			throw new OCSForbiddenException();
108
-		}
109
-
110
-		// if both server initiated the exchange of the shared secret the greater
111
-		// token wins
112
-		$localToken = $this->dbHandler->getToken($url);
113
-		if (strcmp($localToken, $token) > 0) {
114
-			$this->logger->info(
115
-				'remote server (' . $url . ') presented lower token. We will initiate the exchange of the shared secret.',
116
-				['app' => 'federation']
117
-			);
118
-			throw new OCSForbiddenException();
119
-		}
120
-
121
-		// we ask for the shared secret so we no longer have to ask the other server
122
-		// to request the shared secret
123
-		$this->jobList->remove('OCA\Federation\BackgroundJob\RequestSharedSecret',
124
-			[
125
-				'url' => $url,
126
-				'token' => $localToken
127
-			]
128
-		);
129
-
130
-		$this->jobList->add(
131
-			'OCA\Federation\BackgroundJob\GetSharedSecret',
132
-			[
133
-				'url' => $url,
134
-				'token' => $token,
135
-			]
136
-		);
137
-
138
-		return new Http\DataResponse();
139
-	}
140
-
141
-	/**
142
-	 * @NoCSRFRequired
143
-	 * @PublicPage
144
-	 *
145
-	 * create shared secret and return it
146
-	 *
147
-	 * @param string $url
148
-	 * @param string $token
149
-	 * @return Http\DataResponse
150
-	 * @throws OCSForbiddenException
151
-	 */
152
-	public function getSharedSecret($url, $token) {
153
-		if ($this->trustedServers->isTrustedServer($url) === false) {
154
-			$this->logger->error('remote server not trusted (' . $url . ') while getting shared secret', ['app' => 'federation']);
155
-			throw new OCSForbiddenException();
156
-		}
157
-
158
-		if ($this->isValidToken($url, $token) === false) {
159
-			$expectedToken = $this->dbHandler->getToken($url);
160
-			$this->logger->error(
161
-				'remote server (' . $url . ') didn\'t send a valid token (got "' . $token . '" but expected "'. $expectedToken . '") while getting shared secret',
162
-				['app' => 'federation']
163
-			);
164
-			throw new OCSForbiddenException();
165
-		}
166
-
167
-		$sharedSecret = $this->secureRandom->generate(32);
168
-
169
-		$this->trustedServers->addSharedSecret($url, $sharedSecret);
170
-		// reset token after the exchange of the shared secret was successful
171
-		$this->dbHandler->addToken($url, '');
172
-
173
-		return new Http\DataResponse([
174
-			'sharedSecret' => $sharedSecret
175
-		]);
176
-	}
177
-
178
-	protected function isValidToken($url, $token) {
179
-		$storedToken = $this->dbHandler->getToken($url);
180
-		return hash_equals($storedToken, $token);
181
-	}
49
+    /** @var ISecureRandom  */
50
+    private $secureRandom;
51
+
52
+    /** @var IJobList */
53
+    private $jobList;
54
+
55
+    /** @var TrustedServers */
56
+    private $trustedServers;
57
+
58
+    /** @var DbHandler */
59
+    private $dbHandler;
60
+
61
+    /** @var ILogger */
62
+    private $logger;
63
+
64
+    /**
65
+     * OCSAuthAPI constructor.
66
+     *
67
+     * @param string $appName
68
+     * @param IRequest $request
69
+     * @param ISecureRandom $secureRandom
70
+     * @param IJobList $jobList
71
+     * @param TrustedServers $trustedServers
72
+     * @param DbHandler $dbHandler
73
+     * @param ILogger $logger
74
+     */
75
+    public function __construct(
76
+        $appName,
77
+        IRequest $request,
78
+        ISecureRandom $secureRandom,
79
+        IJobList $jobList,
80
+        TrustedServers $trustedServers,
81
+        DbHandler $dbHandler,
82
+        ILogger $logger
83
+    ) {
84
+        parent::__construct($appName, $request);
85
+
86
+        $this->secureRandom = $secureRandom;
87
+        $this->jobList = $jobList;
88
+        $this->trustedServers = $trustedServers;
89
+        $this->dbHandler = $dbHandler;
90
+        $this->logger = $logger;
91
+    }
92
+
93
+    /**
94
+     * @NoCSRFRequired
95
+     * @PublicPage
96
+     *
97
+     * request received to ask remote server for a shared secret
98
+     *
99
+     * @param string $url
100
+     * @param string $token
101
+     * @return Http\DataResponse
102
+     * @throws OCSForbiddenException
103
+     */
104
+    public function requestSharedSecret($url, $token) {
105
+        if ($this->trustedServers->isTrustedServer($url) === false) {
106
+            $this->logger->error('remote server not trusted (' . $url . ') while requesting shared secret', ['app' => 'federation']);
107
+            throw new OCSForbiddenException();
108
+        }
109
+
110
+        // if both server initiated the exchange of the shared secret the greater
111
+        // token wins
112
+        $localToken = $this->dbHandler->getToken($url);
113
+        if (strcmp($localToken, $token) > 0) {
114
+            $this->logger->info(
115
+                'remote server (' . $url . ') presented lower token. We will initiate the exchange of the shared secret.',
116
+                ['app' => 'federation']
117
+            );
118
+            throw new OCSForbiddenException();
119
+        }
120
+
121
+        // we ask for the shared secret so we no longer have to ask the other server
122
+        // to request the shared secret
123
+        $this->jobList->remove('OCA\Federation\BackgroundJob\RequestSharedSecret',
124
+            [
125
+                'url' => $url,
126
+                'token' => $localToken
127
+            ]
128
+        );
129
+
130
+        $this->jobList->add(
131
+            'OCA\Federation\BackgroundJob\GetSharedSecret',
132
+            [
133
+                'url' => $url,
134
+                'token' => $token,
135
+            ]
136
+        );
137
+
138
+        return new Http\DataResponse();
139
+    }
140
+
141
+    /**
142
+     * @NoCSRFRequired
143
+     * @PublicPage
144
+     *
145
+     * create shared secret and return it
146
+     *
147
+     * @param string $url
148
+     * @param string $token
149
+     * @return Http\DataResponse
150
+     * @throws OCSForbiddenException
151
+     */
152
+    public function getSharedSecret($url, $token) {
153
+        if ($this->trustedServers->isTrustedServer($url) === false) {
154
+            $this->logger->error('remote server not trusted (' . $url . ') while getting shared secret', ['app' => 'federation']);
155
+            throw new OCSForbiddenException();
156
+        }
157
+
158
+        if ($this->isValidToken($url, $token) === false) {
159
+            $expectedToken = $this->dbHandler->getToken($url);
160
+            $this->logger->error(
161
+                'remote server (' . $url . ') didn\'t send a valid token (got "' . $token . '" but expected "'. $expectedToken . '") while getting shared secret',
162
+                ['app' => 'federation']
163
+            );
164
+            throw new OCSForbiddenException();
165
+        }
166
+
167
+        $sharedSecret = $this->secureRandom->generate(32);
168
+
169
+        $this->trustedServers->addSharedSecret($url, $sharedSecret);
170
+        // reset token after the exchange of the shared secret was successful
171
+        $this->dbHandler->addToken($url, '');
172
+
173
+        return new Http\DataResponse([
174
+            'sharedSecret' => $sharedSecret
175
+        ]);
176
+    }
177
+
178
+    protected function isValidToken($url, $token) {
179
+        $storedToken = $this->dbHandler->getToken($url);
180
+        return hash_equals($storedToken, $token);
181
+    }
182 182
 
183 183
 }
Please login to merge, or discard this patch.
apps/federation/lib/AppInfo/Application.php 1 patch
Indentation   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -42,100 +42,100 @@
 block discarded – undo
42 42
 
43 43
 class Application extends \OCP\AppFramework\App {
44 44
 
45
-	/**
46
-	 * @param array $urlParams
47
-	 */
48
-	public function __construct($urlParams = array()) {
49
-		parent::__construct('federation', $urlParams);
50
-		$this->registerService();
51
-		$this->registerMiddleware();
52
-	}
53
-
54
-	private function registerService() {
55
-		$container = $this->getContainer();
56
-
57
-		$container->registerService('addServerMiddleware', function(IAppContainer $c) {
58
-			return new AddServerMiddleware(
59
-				$c->getAppName(),
60
-				\OC::$server->getL10N($c->getAppName()),
61
-				\OC::$server->getLogger()
62
-			);
63
-		});
64
-
65
-		$container->registerService('DbHandler', function(IAppContainer $c) {
66
-			return new DbHandler(
67
-				\OC::$server->getDatabaseConnection(),
68
-				\OC::$server->getL10N($c->getAppName())
69
-			);
70
-		});
71
-
72
-		$container->registerService('TrustedServers', function(IAppContainer $c) {
73
-			$server = $c->getServer();
74
-			return new TrustedServers(
75
-				$c->query('DbHandler'),
76
-				$server->getHTTPClientService(),
77
-				$server->getLogger(),
78
-				$server->getJobList(),
79
-				$server->getSecureRandom(),
80
-				$server->getConfig(),
81
-				$server->getEventDispatcher()
82
-			);
83
-		});
84
-
85
-		$container->registerService('SettingsController', function (IAppContainer $c) {
86
-			$server = $c->getServer();
87
-			return new SettingsController(
88
-				$c->getAppName(),
89
-				$server->getRequest(),
90
-				$server->getL10N($c->getAppName()),
91
-				$c->query('TrustedServers')
92
-			);
93
-		});
94
-
95
-	}
96
-
97
-	private function registerMiddleware() {
98
-		$container = $this->getContainer();
99
-		$container->registerMiddleware('addServerMiddleware');
100
-	}
101
-
102
-	/**
103
-	 * listen to federated_share_added hooks to auto-add new servers to the
104
-	 * list of trusted servers.
105
-	 */
106
-	public function registerHooks() {
107
-
108
-		$container = $this->getContainer();
109
-		$hooksManager = new Hooks($container->query('TrustedServers'));
110
-
111
-		Util::connectHook(
112
-				'OCP\Share',
113
-				'federated_share_added',
114
-				$hooksManager,
115
-				'addServerHook'
116
-		);
117
-
118
-		$dispatcher = $this->getContainer()->getServer()->getEventDispatcher();
119
-		$dispatcher->addListener('OCA\DAV\Connector\Sabre::authInit', function($event) use($container) {
120
-			if ($event instanceof SabrePluginEvent) {
121
-				$authPlugin = $event->getServer()->getPlugin('auth');
122
-				if ($authPlugin instanceof Plugin) {
123
-					$h = new DbHandler($container->getServer()->getDatabaseConnection(),
124
-							$container->getServer()->getL10N('federation')
125
-					);
126
-					$authPlugin->addBackend(new FedAuth($h));
127
-				}
128
-			}
129
-		});
130
-	}
131
-
132
-	/**
133
-	 * @return SyncFederationAddressBooks
134
-	 */
135
-	public function getSyncService() {
136
-		$syncService = \OC::$server->query('CardDAVSyncService');
137
-		$dbHandler = $this->getContainer()->query('DbHandler');
138
-		return new SyncFederationAddressBooks($dbHandler, $syncService);
139
-	}
45
+    /**
46
+     * @param array $urlParams
47
+     */
48
+    public function __construct($urlParams = array()) {
49
+        parent::__construct('federation', $urlParams);
50
+        $this->registerService();
51
+        $this->registerMiddleware();
52
+    }
53
+
54
+    private function registerService() {
55
+        $container = $this->getContainer();
56
+
57
+        $container->registerService('addServerMiddleware', function(IAppContainer $c) {
58
+            return new AddServerMiddleware(
59
+                $c->getAppName(),
60
+                \OC::$server->getL10N($c->getAppName()),
61
+                \OC::$server->getLogger()
62
+            );
63
+        });
64
+
65
+        $container->registerService('DbHandler', function(IAppContainer $c) {
66
+            return new DbHandler(
67
+                \OC::$server->getDatabaseConnection(),
68
+                \OC::$server->getL10N($c->getAppName())
69
+            );
70
+        });
71
+
72
+        $container->registerService('TrustedServers', function(IAppContainer $c) {
73
+            $server = $c->getServer();
74
+            return new TrustedServers(
75
+                $c->query('DbHandler'),
76
+                $server->getHTTPClientService(),
77
+                $server->getLogger(),
78
+                $server->getJobList(),
79
+                $server->getSecureRandom(),
80
+                $server->getConfig(),
81
+                $server->getEventDispatcher()
82
+            );
83
+        });
84
+
85
+        $container->registerService('SettingsController', function (IAppContainer $c) {
86
+            $server = $c->getServer();
87
+            return new SettingsController(
88
+                $c->getAppName(),
89
+                $server->getRequest(),
90
+                $server->getL10N($c->getAppName()),
91
+                $c->query('TrustedServers')
92
+            );
93
+        });
94
+
95
+    }
96
+
97
+    private function registerMiddleware() {
98
+        $container = $this->getContainer();
99
+        $container->registerMiddleware('addServerMiddleware');
100
+    }
101
+
102
+    /**
103
+     * listen to federated_share_added hooks to auto-add new servers to the
104
+     * list of trusted servers.
105
+     */
106
+    public function registerHooks() {
107
+
108
+        $container = $this->getContainer();
109
+        $hooksManager = new Hooks($container->query('TrustedServers'));
110
+
111
+        Util::connectHook(
112
+                'OCP\Share',
113
+                'federated_share_added',
114
+                $hooksManager,
115
+                'addServerHook'
116
+        );
117
+
118
+        $dispatcher = $this->getContainer()->getServer()->getEventDispatcher();
119
+        $dispatcher->addListener('OCA\DAV\Connector\Sabre::authInit', function($event) use($container) {
120
+            if ($event instanceof SabrePluginEvent) {
121
+                $authPlugin = $event->getServer()->getPlugin('auth');
122
+                if ($authPlugin instanceof Plugin) {
123
+                    $h = new DbHandler($container->getServer()->getDatabaseConnection(),
124
+                            $container->getServer()->getL10N('federation')
125
+                    );
126
+                    $authPlugin->addBackend(new FedAuth($h));
127
+                }
128
+            }
129
+        });
130
+    }
131
+
132
+    /**
133
+     * @return SyncFederationAddressBooks
134
+     */
135
+    public function getSyncService() {
136
+        $syncService = \OC::$server->query('CardDAVSyncService');
137
+        $dbHandler = $this->getContainer()->query('DbHandler');
138
+        return new SyncFederationAddressBooks($dbHandler, $syncService);
139
+    }
140 140
 
141 141
 }
Please login to merge, or discard this patch.
apps/federation/lib/Command/SyncFederationAddressBooks.php 1 patch
Indentation   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -31,45 +31,45 @@
 block discarded – undo
31 31
 
32 32
 class SyncFederationAddressBooks extends Command {
33 33
 
34
-	/** @var \OCA\Federation\SyncFederationAddressBooks */
35
-	private $syncService;
34
+    /** @var \OCA\Federation\SyncFederationAddressBooks */
35
+    private $syncService;
36 36
 
37
-	/**
38
-	 * @param \OCA\Federation\SyncFederationAddressBooks $syncService
39
-	 */
40
-	function __construct(\OCA\Federation\SyncFederationAddressBooks $syncService) {
41
-		parent::__construct();
37
+    /**
38
+     * @param \OCA\Federation\SyncFederationAddressBooks $syncService
39
+     */
40
+    function __construct(\OCA\Federation\SyncFederationAddressBooks $syncService) {
41
+        parent::__construct();
42 42
 
43
-		$this->syncService = $syncService;
44
-	}
43
+        $this->syncService = $syncService;
44
+    }
45 45
 
46
-	protected function configure() {
47
-		$this
48
-			->setName('federation:sync-addressbooks')
49
-			->setDescription('Synchronizes addressbooks of all federated clouds');
50
-	}
46
+    protected function configure() {
47
+        $this
48
+            ->setName('federation:sync-addressbooks')
49
+            ->setDescription('Synchronizes addressbooks of all federated clouds');
50
+    }
51 51
 
52
-	/**
53
-	 * @param InputInterface $input
54
-	 * @param OutputInterface $output
55
-	 * @return int
56
-	 */
57
-	protected function execute(InputInterface $input, OutputInterface $output) {
52
+    /**
53
+     * @param InputInterface $input
54
+     * @param OutputInterface $output
55
+     * @return int
56
+     */
57
+    protected function execute(InputInterface $input, OutputInterface $output) {
58 58
 
59
-		$progress = new ProgressBar($output);
60
-		$progress->start();
61
-		$this->syncService->syncThemAll(function($url, $ex) use ($progress, $output) {
62
-			if ($ex instanceof \Exception) {
63
-				$output->writeln("Error while syncing $url : " . $ex->getMessage());
59
+        $progress = new ProgressBar($output);
60
+        $progress->start();
61
+        $this->syncService->syncThemAll(function($url, $ex) use ($progress, $output) {
62
+            if ($ex instanceof \Exception) {
63
+                $output->writeln("Error while syncing $url : " . $ex->getMessage());
64 64
 
65
-			} else {
66
-				$progress->advance();
67
-			}
68
-		});
65
+            } else {
66
+                $progress->advance();
67
+            }
68
+        });
69 69
 
70
-		$progress->finish();
71
-		$output->writeln('');
70
+        $progress->finish();
71
+        $output->writeln('');
72 72
 
73
-		return 0;
74
-	}
73
+        return 0;
74
+    }
75 75
 }
Please login to merge, or discard this patch.
apps/federation/lib/SyncFederationAddressBooks.php 1 patch
Indentation   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -32,52 +32,52 @@
 block discarded – undo
32 32
 
33 33
 class SyncFederationAddressBooks {
34 34
 
35
-	/** @var DbHandler */
36
-	protected $dbHandler;
35
+    /** @var DbHandler */
36
+    protected $dbHandler;
37 37
 
38
-	/** @var SyncService */
39
-	private $syncService;
38
+    /** @var SyncService */
39
+    private $syncService;
40 40
 
41
-	/**
42
-	 * @param DbHandler $dbHandler
43
-	 * @param SyncService $syncService
44
-	 */
45
-	function __construct(DbHandler $dbHandler, SyncService $syncService) {
46
-		$this->syncService = $syncService;
47
-		$this->dbHandler = $dbHandler;
48
-	}
41
+    /**
42
+     * @param DbHandler $dbHandler
43
+     * @param SyncService $syncService
44
+     */
45
+    function __construct(DbHandler $dbHandler, SyncService $syncService) {
46
+        $this->syncService = $syncService;
47
+        $this->dbHandler = $dbHandler;
48
+    }
49 49
 
50
-	/**
51
-	 * @param \Closure $callback
52
-	 */
53
-	public function syncThemAll(\Closure $callback) {
50
+    /**
51
+     * @param \Closure $callback
52
+     */
53
+    public function syncThemAll(\Closure $callback) {
54 54
 
55
-		$trustedServers = $this->dbHandler->getAllServer();
56
-		foreach ($trustedServers as $trustedServer) {
57
-			$url = $trustedServer['url'];
58
-			$callback($url, null);
59
-			$sharedSecret = $trustedServer['shared_secret'];
60
-			$syncToken = $trustedServer['sync_token'];
55
+        $trustedServers = $this->dbHandler->getAllServer();
56
+        foreach ($trustedServers as $trustedServer) {
57
+            $url = $trustedServer['url'];
58
+            $callback($url, null);
59
+            $sharedSecret = $trustedServer['shared_secret'];
60
+            $syncToken = $trustedServer['sync_token'];
61 61
 
62
-			if (is_null($sharedSecret)) {
63
-				continue;
64
-			}
65
-			$targetBookId = $trustedServer['url_hash'];
66
-			$targetPrincipal = "principals/system/system";
67
-			$targetBookProperties = [
68
-					'{DAV:}displayname' => $url
69
-			];
70
-			try {
71
-				$newToken = $this->syncService->syncRemoteAddressBook($url, 'system', $sharedSecret, $syncToken, $targetBookId, $targetPrincipal, $targetBookProperties);
72
-				if ($newToken !== $syncToken) {
73
-					$this->dbHandler->setServerStatus($url, TrustedServers::STATUS_OK, $newToken);
74
-				}
75
-			} catch (\Exception $ex) {
76
-				if ($ex->getCode() === Http::STATUS_UNAUTHORIZED) {
77
-					$this->dbHandler->setServerStatus($url, TrustedServers::STATUS_ACCESS_REVOKED);
78
-				}
79
-				$callback($url, $ex);
80
-			}
81
-		}
82
-	}
62
+            if (is_null($sharedSecret)) {
63
+                continue;
64
+            }
65
+            $targetBookId = $trustedServer['url_hash'];
66
+            $targetPrincipal = "principals/system/system";
67
+            $targetBookProperties = [
68
+                    '{DAV:}displayname' => $url
69
+            ];
70
+            try {
71
+                $newToken = $this->syncService->syncRemoteAddressBook($url, 'system', $sharedSecret, $syncToken, $targetBookId, $targetPrincipal, $targetBookProperties);
72
+                if ($newToken !== $syncToken) {
73
+                    $this->dbHandler->setServerStatus($url, TrustedServers::STATUS_OK, $newToken);
74
+                }
75
+            } catch (\Exception $ex) {
76
+                if ($ex->getCode() === Http::STATUS_UNAUTHORIZED) {
77
+                    $this->dbHandler->setServerStatus($url, TrustedServers::STATUS_ACCESS_REVOKED);
78
+                }
79
+                $callback($url, $ex);
80
+            }
81
+        }
82
+    }
83 83
 }
Please login to merge, or discard this patch.
apps/federation/lib/TrustedServers.php 1 patch
Indentation   +237 added lines, -237 removed lines patch added patch discarded remove patch
@@ -38,241 +38,241 @@
 block discarded – undo
38 38
 
39 39
 class TrustedServers {
40 40
 
41
-	/** after a user list was exchanged at least once successfully */
42
-	const STATUS_OK = 1;
43
-	/** waiting for shared secret or initial user list exchange */
44
-	const STATUS_PENDING = 2;
45
-	/** something went wrong, misconfigured server, software bug,... user interaction needed */
46
-	const STATUS_FAILURE = 3;
47
-	/** remote server revoked access */
48
-	const STATUS_ACCESS_REVOKED = 4;
49
-
50
-	/** @var  dbHandler */
51
-	private $dbHandler;
52
-
53
-	/** @var  IClientService */
54
-	private $httpClientService;
55
-
56
-	/** @var ILogger */
57
-	private $logger;
58
-
59
-	/** @var IJobList */
60
-	private $jobList;
61
-
62
-	/** @var ISecureRandom */
63
-	private $secureRandom;
64
-
65
-	/** @var IConfig */
66
-	private $config;
67
-
68
-	/** @var EventDispatcherInterface */
69
-	private $dispatcher;
70
-
71
-	/**
72
-	 * @param DbHandler $dbHandler
73
-	 * @param IClientService $httpClientService
74
-	 * @param ILogger $logger
75
-	 * @param IJobList $jobList
76
-	 * @param ISecureRandom $secureRandom
77
-	 * @param IConfig $config
78
-	 * @param EventDispatcherInterface $dispatcher
79
-	 */
80
-	public function __construct(
81
-		DbHandler $dbHandler,
82
-		IClientService $httpClientService,
83
-		ILogger $logger,
84
-		IJobList $jobList,
85
-		ISecureRandom $secureRandom,
86
-		IConfig $config,
87
-		EventDispatcherInterface $dispatcher
88
-	) {
89
-		$this->dbHandler = $dbHandler;
90
-		$this->httpClientService = $httpClientService;
91
-		$this->logger = $logger;
92
-		$this->jobList = $jobList;
93
-		$this->secureRandom = $secureRandom;
94
-		$this->config = $config;
95
-		$this->dispatcher = $dispatcher;
96
-	}
97
-
98
-	/**
99
-	 * add server to the list of trusted servers
100
-	 *
101
-	 * @param $url
102
-	 * @return int server id
103
-	 */
104
-	public function addServer($url) {
105
-		$url = $this->updateProtocol($url);
106
-		$result = $this->dbHandler->addServer($url);
107
-		if ($result) {
108
-			$token = $this->secureRandom->generate(16);
109
-			$this->dbHandler->addToken($url, $token);
110
-			$this->jobList->add(
111
-				'OCA\Federation\BackgroundJob\RequestSharedSecret',
112
-				[
113
-					'url' => $url,
114
-					'token' => $token
115
-				]
116
-			);
117
-		}
118
-
119
-		return $result;
120
-	}
121
-
122
-	/**
123
-	 * enable/disable to automatically add servers to the list of trusted servers
124
-	 * once a federated share was created and accepted successfully
125
-	 *
126
-	 * @param bool $status
127
-	 */
128
-	public function setAutoAddServers($status) {
129
-		$value = $status ? '1' : '0';
130
-		$this->config->setAppValue('federation', 'autoAddServers', $value);
131
-	}
132
-
133
-	/**
134
-	 * return if we automatically add servers to the list of trusted servers
135
-	 * once a federated share was created and accepted successfully
136
-	 *
137
-	 * @return bool
138
-	 */
139
-	public function getAutoAddServers() {
140
-		$value = $this->config->getAppValue('federation', 'autoAddServers', '0');
141
-		return $value === '1';
142
-	}
143
-
144
-	/**
145
-	 * get shared secret for the given server
146
-	 *
147
-	 * @param string $url
148
-	 * @return string
149
-	 */
150
-	public function getSharedSecret($url) {
151
-		return $this->dbHandler->getSharedSecret($url);
152
-	}
153
-
154
-	/**
155
-	 * add shared secret for the given server
156
-	 *
157
-	 * @param string $url
158
-	 * @param $sharedSecret
159
-	 */
160
-	public function addSharedSecret($url, $sharedSecret) {
161
-		$this->dbHandler->addSharedSecret($url, $sharedSecret);
162
-	}
163
-
164
-	/**
165
-	 * remove server from the list of trusted servers
166
-	 *
167
-	 * @param int $id
168
-	 */
169
-	public function removeServer($id) {
170
-		$server = $this->dbHandler->getServerById($id);
171
-		$this->dbHandler->removeServer($id);
172
-		$event = new GenericEvent($server['url_hash']);
173
-		$this->dispatcher->dispatch('OCP\Federation\TrustedServerEvent::remove', $event);
174
-	}
175
-
176
-	/**
177
-	 * get all trusted servers
178
-	 *
179
-	 * @return array
180
-	 */
181
-	public function getServers() {
182
-		return $this->dbHandler->getAllServer();
183
-	}
184
-
185
-	/**
186
-	 * check if given server is a trusted ownCloud server
187
-	 *
188
-	 * @param string $url
189
-	 * @return bool
190
-	 */
191
-	public function isTrustedServer($url) {
192
-		return $this->dbHandler->serverExists($url);
193
-	}
194
-
195
-	/**
196
-	 * set server status
197
-	 *
198
-	 * @param string $url
199
-	 * @param int $status
200
-	 */
201
-	public function setServerStatus($url, $status) {
202
-		$this->dbHandler->setServerStatus($url, $status);
203
-	}
204
-
205
-	/**
206
-	 * @param string $url
207
-	 * @return int
208
-	 */
209
-	public function getServerStatus($url) {
210
-		return $this->dbHandler->getServerStatus($url);
211
-	}
212
-
213
-	/**
214
-	 * check if URL point to a ownCloud/Nextcloud server
215
-	 *
216
-	 * @param string $url
217
-	 * @return bool
218
-	 */
219
-	public function isOwnCloudServer($url) {
220
-		$isValidOwnCloud = false;
221
-		$client = $this->httpClientService->newClient();
222
-		try {
223
-			$result = $client->get(
224
-				$url . '/status.php',
225
-				[
226
-					'timeout' => 3,
227
-					'connect_timeout' => 3,
228
-				]
229
-			);
230
-			if ($result->getStatusCode() === Http::STATUS_OK) {
231
-				$isValidOwnCloud = $this->checkOwnCloudVersion($result->getBody());
232
-
233
-			}
234
-		} catch (\Exception $e) {
235
-			$this->logger->debug('No Nextcloud server: ' . $e->getMessage());
236
-			return false;
237
-		}
238
-
239
-		return $isValidOwnCloud;
240
-	}
241
-
242
-	/**
243
-	 * check if ownCloud version is >= 9.0
244
-	 *
245
-	 * @param $status
246
-	 * @return bool
247
-	 * @throws HintException
248
-	 */
249
-	protected function checkOwnCloudVersion($status) {
250
-		$decoded = json_decode($status, true);
251
-		if (!empty($decoded) && isset($decoded['version'])) {
252
-			if (!version_compare($decoded['version'], '9.0.0', '>=')) {
253
-				throw new HintException('Remote server version is too low. 9.0 is required.');
254
-			}
255
-			return true;
256
-		}
257
-		return false;
258
-	}
259
-
260
-	/**
261
-	 * check if the URL contain a protocol, if not add https
262
-	 *
263
-	 * @param string $url
264
-	 * @return string
265
-	 */
266
-	protected function updateProtocol($url) {
267
-		if (
268
-			strpos($url, 'https://') === 0
269
-			|| strpos($url, 'http://') === 0
270
-		) {
271
-
272
-			return $url;
273
-
274
-		}
275
-
276
-		return 'https://' . $url;
277
-	}
41
+    /** after a user list was exchanged at least once successfully */
42
+    const STATUS_OK = 1;
43
+    /** waiting for shared secret or initial user list exchange */
44
+    const STATUS_PENDING = 2;
45
+    /** something went wrong, misconfigured server, software bug,... user interaction needed */
46
+    const STATUS_FAILURE = 3;
47
+    /** remote server revoked access */
48
+    const STATUS_ACCESS_REVOKED = 4;
49
+
50
+    /** @var  dbHandler */
51
+    private $dbHandler;
52
+
53
+    /** @var  IClientService */
54
+    private $httpClientService;
55
+
56
+    /** @var ILogger */
57
+    private $logger;
58
+
59
+    /** @var IJobList */
60
+    private $jobList;
61
+
62
+    /** @var ISecureRandom */
63
+    private $secureRandom;
64
+
65
+    /** @var IConfig */
66
+    private $config;
67
+
68
+    /** @var EventDispatcherInterface */
69
+    private $dispatcher;
70
+
71
+    /**
72
+     * @param DbHandler $dbHandler
73
+     * @param IClientService $httpClientService
74
+     * @param ILogger $logger
75
+     * @param IJobList $jobList
76
+     * @param ISecureRandom $secureRandom
77
+     * @param IConfig $config
78
+     * @param EventDispatcherInterface $dispatcher
79
+     */
80
+    public function __construct(
81
+        DbHandler $dbHandler,
82
+        IClientService $httpClientService,
83
+        ILogger $logger,
84
+        IJobList $jobList,
85
+        ISecureRandom $secureRandom,
86
+        IConfig $config,
87
+        EventDispatcherInterface $dispatcher
88
+    ) {
89
+        $this->dbHandler = $dbHandler;
90
+        $this->httpClientService = $httpClientService;
91
+        $this->logger = $logger;
92
+        $this->jobList = $jobList;
93
+        $this->secureRandom = $secureRandom;
94
+        $this->config = $config;
95
+        $this->dispatcher = $dispatcher;
96
+    }
97
+
98
+    /**
99
+     * add server to the list of trusted servers
100
+     *
101
+     * @param $url
102
+     * @return int server id
103
+     */
104
+    public function addServer($url) {
105
+        $url = $this->updateProtocol($url);
106
+        $result = $this->dbHandler->addServer($url);
107
+        if ($result) {
108
+            $token = $this->secureRandom->generate(16);
109
+            $this->dbHandler->addToken($url, $token);
110
+            $this->jobList->add(
111
+                'OCA\Federation\BackgroundJob\RequestSharedSecret',
112
+                [
113
+                    'url' => $url,
114
+                    'token' => $token
115
+                ]
116
+            );
117
+        }
118
+
119
+        return $result;
120
+    }
121
+
122
+    /**
123
+     * enable/disable to automatically add servers to the list of trusted servers
124
+     * once a federated share was created and accepted successfully
125
+     *
126
+     * @param bool $status
127
+     */
128
+    public function setAutoAddServers($status) {
129
+        $value = $status ? '1' : '0';
130
+        $this->config->setAppValue('federation', 'autoAddServers', $value);
131
+    }
132
+
133
+    /**
134
+     * return if we automatically add servers to the list of trusted servers
135
+     * once a federated share was created and accepted successfully
136
+     *
137
+     * @return bool
138
+     */
139
+    public function getAutoAddServers() {
140
+        $value = $this->config->getAppValue('federation', 'autoAddServers', '0');
141
+        return $value === '1';
142
+    }
143
+
144
+    /**
145
+     * get shared secret for the given server
146
+     *
147
+     * @param string $url
148
+     * @return string
149
+     */
150
+    public function getSharedSecret($url) {
151
+        return $this->dbHandler->getSharedSecret($url);
152
+    }
153
+
154
+    /**
155
+     * add shared secret for the given server
156
+     *
157
+     * @param string $url
158
+     * @param $sharedSecret
159
+     */
160
+    public function addSharedSecret($url, $sharedSecret) {
161
+        $this->dbHandler->addSharedSecret($url, $sharedSecret);
162
+    }
163
+
164
+    /**
165
+     * remove server from the list of trusted servers
166
+     *
167
+     * @param int $id
168
+     */
169
+    public function removeServer($id) {
170
+        $server = $this->dbHandler->getServerById($id);
171
+        $this->dbHandler->removeServer($id);
172
+        $event = new GenericEvent($server['url_hash']);
173
+        $this->dispatcher->dispatch('OCP\Federation\TrustedServerEvent::remove', $event);
174
+    }
175
+
176
+    /**
177
+     * get all trusted servers
178
+     *
179
+     * @return array
180
+     */
181
+    public function getServers() {
182
+        return $this->dbHandler->getAllServer();
183
+    }
184
+
185
+    /**
186
+     * check if given server is a trusted ownCloud server
187
+     *
188
+     * @param string $url
189
+     * @return bool
190
+     */
191
+    public function isTrustedServer($url) {
192
+        return $this->dbHandler->serverExists($url);
193
+    }
194
+
195
+    /**
196
+     * set server status
197
+     *
198
+     * @param string $url
199
+     * @param int $status
200
+     */
201
+    public function setServerStatus($url, $status) {
202
+        $this->dbHandler->setServerStatus($url, $status);
203
+    }
204
+
205
+    /**
206
+     * @param string $url
207
+     * @return int
208
+     */
209
+    public function getServerStatus($url) {
210
+        return $this->dbHandler->getServerStatus($url);
211
+    }
212
+
213
+    /**
214
+     * check if URL point to a ownCloud/Nextcloud server
215
+     *
216
+     * @param string $url
217
+     * @return bool
218
+     */
219
+    public function isOwnCloudServer($url) {
220
+        $isValidOwnCloud = false;
221
+        $client = $this->httpClientService->newClient();
222
+        try {
223
+            $result = $client->get(
224
+                $url . '/status.php',
225
+                [
226
+                    'timeout' => 3,
227
+                    'connect_timeout' => 3,
228
+                ]
229
+            );
230
+            if ($result->getStatusCode() === Http::STATUS_OK) {
231
+                $isValidOwnCloud = $this->checkOwnCloudVersion($result->getBody());
232
+
233
+            }
234
+        } catch (\Exception $e) {
235
+            $this->logger->debug('No Nextcloud server: ' . $e->getMessage());
236
+            return false;
237
+        }
238
+
239
+        return $isValidOwnCloud;
240
+    }
241
+
242
+    /**
243
+     * check if ownCloud version is >= 9.0
244
+     *
245
+     * @param $status
246
+     * @return bool
247
+     * @throws HintException
248
+     */
249
+    protected function checkOwnCloudVersion($status) {
250
+        $decoded = json_decode($status, true);
251
+        if (!empty($decoded) && isset($decoded['version'])) {
252
+            if (!version_compare($decoded['version'], '9.0.0', '>=')) {
253
+                throw new HintException('Remote server version is too low. 9.0 is required.');
254
+            }
255
+            return true;
256
+        }
257
+        return false;
258
+    }
259
+
260
+    /**
261
+     * check if the URL contain a protocol, if not add https
262
+     *
263
+     * @param string $url
264
+     * @return string
265
+     */
266
+    protected function updateProtocol($url) {
267
+        if (
268
+            strpos($url, 'https://') === 0
269
+            || strpos($url, 'http://') === 0
270
+        ) {
271
+
272
+            return $url;
273
+
274
+        }
275
+
276
+        return 'https://' . $url;
277
+    }
278 278
 }
Please login to merge, or discard this patch.