How to create user via rest api and authenticate them ?
Create a file: cockpit/config/api/user/register.php
<?php
$uname = $this->param('name');
$username = $this->param('username');
$email = $this->param('email');
$password = $this->param('password');
$role = $this->param('role');
$created= time();
$app = Cockpit::instance();
$checkuser = $app->dataStorage->findOne('system/users', ['user' => $username]);
$checkemail = $app->dataStorage->findOne('system/users', ['user' => $email]);
if (!$checkuser && !$checkemail) {
$user = [
'active' => true,
'name' => $uname,
'user' => $username,
'email' => $email,
'password' => $app->hash('$password'),
'i18n' => 'en',
'role' => $role,
'theme' => 'auto',
'_modified' => $created,
'_created' => $created
];
$app->dataStorage->save('system/users', $user);
return [
'status' => 'success'];
}
else{
if($checkuser){return $this->stop(['error' => 'username already exist'], 412);}
if($checkemail){return $this->stop(['error' => 'email already exist'], 412);}
}
?>
Now from your app use curl to send relevant user registration data to route cockpit/api/user/auth
Tweak the above code as per as your convenience. I hope it helps. Cheers
1 Like
works for me … thanks
Through this method password is not created! After account creation user can not login.
add the code to create an endpoint to create users in version 2
$restApi->addEndPoint('/auth/signup',[
'POST' => function($params, $app) {
$name = $app->param('name');
$username = $app->param('username');
$email = $app->param('email');
$password = $app->param('password');
$created = time();
// Validar si el email tiene el formato correcto
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return "El formato del email no es válido";
}
// Validar si el campo username está vacío
if (empty($username)) {
return "El campo username no puede estar vacío";
}
// Verificar si el usuario o el email ya existen
$checkuser = $this->dataStorage->findOne('system/users', ['user' => $username]);
$checkemail = $this->dataStorage->findOne('system/users', ['email' => $email]);
if ($checkuser || $checkemail) {
return "Usuario o email ya existen";
}
//crear datos de usuario
$user = [
'active' => true,
'name' => $name,
'user' => $username,
'email' => $email,
'password' => $app->hash($password),
'i18n' => 'es',
'role' => 'admin',
'theme' => 'auto',
'_modified' => $created,
'_created' => $created
];
// Guardar el usuario y obtener el ID
$userId = $this->dataStorage->save('system/users', $user);
if ($userId) {
return array("message" => "Usuario creado con éxito." , "id"=> $userId);
} else {
return "Hubo un error al crear el usuario";
}
}
]);