65 lines
2.1 KiB
PHP
65 lines
2.1 KiB
PHP
<?php
|
|
require __DIR__ . '/_bootstrap.php';
|
|
require __DIR__ . '/_codes.php';
|
|
|
|
/**
|
|
* @OA\Post(
|
|
* path="/password-reset.php",
|
|
* tags={"Auth"},
|
|
* summary="Reset the password with a 6-digit code",
|
|
* description="Revokes every token, so all devices are signed out. Error codes: code_invalid or code_expired.",
|
|
* security={},
|
|
* @OA\RequestBody(required=true, @OA\JsonContent(
|
|
* required={"email","code","password"},
|
|
* @OA\Property(property="email", type="string", format="email"),
|
|
* @OA\Property(property="code", type="string", example="123456"),
|
|
* @OA\Property(property="password", type="string", format="password", minLength=8)
|
|
* )),
|
|
* @OA\Response(response=200, ref="#/components/responses/Success"),
|
|
* @OA\Response(response=422, ref="#/components/responses/ValidationError")
|
|
* )
|
|
*/
|
|
require_method('POST');
|
|
|
|
$in = body();
|
|
$email = trim((string) ($in['email'] ?? ''));
|
|
$code = trim((string) ($in['code'] ?? ''));
|
|
$password = (string) ($in['password'] ?? '');
|
|
|
|
$fields = [];
|
|
if ($email === '') {
|
|
$fields['email'] = ['Required'];
|
|
}
|
|
if ($code === '') {
|
|
$fields['code'] = ['Required'];
|
|
}
|
|
if (strlen($password) < 8) {
|
|
$fields['password'] = ['At least 8 characters'];
|
|
}
|
|
if ($fields) {
|
|
json_error(422, 'Validation failed', $fields);
|
|
}
|
|
|
|
$result = check_code($pdo, 'auth_password_resets', $email, $code);
|
|
if ($result !== 'ok') {
|
|
json_error(422, $result === 'code_expired' ? 'Code expired, request a new one' : 'Invalid code', null, $result);
|
|
}
|
|
|
|
$stmt = $pdo->prepare('SELECT id FROM auth_users WHERE email = ? LIMIT 1');
|
|
$stmt->execute([$email]);
|
|
$userId = $stmt->fetchColumn();
|
|
if (!$userId) {
|
|
json_error(422, 'Invalid code', null, 'code_invalid');
|
|
}
|
|
|
|
// Receiving the code proves the address, so the e-mail counts as verified too.
|
|
$pdo->prepare(
|
|
'UPDATE auth_users
|
|
SET password = ?, email_verified_at = COALESCE(email_verified_at, NOW())
|
|
WHERE id = ?'
|
|
)->execute([password_hash($password, PASSWORD_DEFAULT), $userId]);
|
|
|
|
$pdo->prepare('DELETE FROM api_tokens WHERE user_id = ?')->execute([$userId]);
|
|
|
|
json_ok();
|