Skip to content

Commit

Permalink
feat(ui): verify that a given username is valid when adding accounts
Browse files Browse the repository at this point in the history
  • Loading branch information
marcantondahmen committed Aug 1, 2021
1 parent f2f8102 commit 283a41a
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 4 deletions.
43 changes: 39 additions & 4 deletions automad/ui/controllers/accounts.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
namespace Automad\UI\Controllers;

use Automad\Core\Request;
use Automad\Core\Resolve;
use Automad\UI\Components\Grid\Users;
use Automad\UI\Models\Accounts as ModelsAccounts;
use Automad\UI\Response;
Expand Down Expand Up @@ -64,14 +65,18 @@ public static function add() {
$password1 = Request::post('password1');
$password2 = Request::post('password2');

$error = ModelsAccounts::add($username, $password1, $password2);
if (!self::validUsername($username)) {
return self::invalidUsernameResponse();
}

if ($error) {
if ($error = ModelsAccounts::add($username, $password1, $password2)) {
$Response->setError($error);
} else {
$Response->setSuccess(Text::get('success_added') . ' "' . $username . '"');

return $Response;
}

$Response->setSuccess(Text::get('success_added') . ' "' . $username . '"');

return $Response;
}

Expand Down Expand Up @@ -100,6 +105,12 @@ public static function edit() {
*/
public static function install() {
if (!empty($_POST)) {
if (!self::validUsername(Request::post('username'))) {
$Response = self::invalidUsernameResponse();

return $Response->getError();
}

return ModelsAccounts::install(
Request::post('username'),
Request::post('password1'),
Expand Down Expand Up @@ -136,4 +147,28 @@ private static function delete($users) {

return $Response;
}

/**
* A response containing the invalid username error message.
*
* @return \Automad\UI\Response the response object
*/
private static function invalidUsernameResponse() {
$Response = new Response();
$Response->setError(Text::get('error_invalid_username') . ' "a-z", "A-Z", ".", "-", "_", "@"');

return $Response;
}

/**
* Verify if a given username is valid.
*
* @param string $username
* @return boolean true in case the username is valid
*/
private static function validUsername($username) {
preg_match('/[^@\w\.\-]/', $username, $matches);

return empty($matches);
}
}
4 changes: 4 additions & 0 deletions automad/ui/lang/english.txt
Original file line number Diff line number Diff line change
Expand Up @@ -749,6 +749,10 @@ error_import: The file import has failed!

-

error_invalid_username: Invalid username! A username can only contain the following characters:

-

error_json: Invalid JSON! The contents of the configuration file is not formatted correctly.

-
Expand Down

0 comments on commit 283a41a

Please sign in to comment.