Skip to content

Commit e42b86a

Browse files
authored
Merge pull request #2327 from akrabat/encode-user-info
Encode user info
2 parents 67a6cb3 + 72309b2 commit e42b86a

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

Slim/Http/Uri.php

+21-2
Original file line numberDiff line numberDiff line change
@@ -378,12 +378,31 @@ public function getUserInfo()
378378
public function withUserInfo($user, $password = null)
379379
{
380380
$clone = clone $this;
381-
$clone->user = $user;
382-
$clone->password = $password ? $password : '';
381+
$clone->user = $this->filterUserInfo($user);
382+
if ($clone->user) {
383+
$clone->password = $password ? $this->filterUserInfo($password) : '';
384+
}
383385

384386
return $clone;
385387
}
386388

389+
/**
390+
* Filters the user info string.
391+
*
392+
* @param string $query The raw uri query string.
393+
* @return string The percent-encoded query string.
394+
*/
395+
protected function filterUserInfo($query)
396+
{
397+
return preg_replace_callback(
398+
'/(?:[^a-zA-Z0-9_\-\.~!\$&\'\(\)\*\+,;=]+|%(?![A-Fa-f0-9]{2}))/u',
399+
function ($match) {
400+
return rawurlencode($match[0]);
401+
},
402+
$query
403+
);
404+
}
405+
387406
/**
388407
* Retrieve the host component of the URI.
389408
*

tests/Http/UriTest.php

+15
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,13 @@ public function testGetUserInfoNone()
180180
$this->assertEquals('', $uri->getUserInfo());
181181
}
182182

183+
public function testGetUserInfoWithUsernameAndPasswordEncodesCorrectly()
184+
{
185+
$uri = Uri::createFromString('https://bob%40example.com:pass%[email protected]:443/foo/bar?abc=123#section3');
186+
187+
$this->assertEquals('bob%40example.com:pass%3Aword', $uri->getUserInfo());
188+
}
189+
183190
public function testWithUserInfo()
184191
{
185192
$uri = $this->uriFactory()->withUserInfo('bob', 'pass');
@@ -188,6 +195,14 @@ public function testWithUserInfo()
188195
$this->assertAttributeEquals('pass', 'password', $uri);
189196
}
190197

198+
public function testWithUserInfoEncodesCorrectly()
199+
{
200+
$uri = $this->uriFactory()->withUserInfo('[email protected]', 'pass:word');
201+
202+
$this->assertAttributeEquals('bob%40example.com', 'user', $uri);
203+
$this->assertAttributeEquals('pass%3Aword', 'password', $uri);
204+
}
205+
191206
public function testWithUserInfoRemovesPassword()
192207
{
193208
$uri = $this->uriFactory()->withUserInfo('bob');

0 commit comments

Comments
 (0)