xiaowang/kirby/config/api/routes/auth.php

109 lines
2.5 KiB
PHP
Raw Normal View History

2021-10-29 18:05:46 +02:00
<?php
use Kirby\Exception\InvalidArgumentException;
use Kirby\Exception\NotFoundException;
/**
* Authentication
*/
return [
2022-08-31 16:08:03 +02:00
[
'pattern' => 'auth',
'method' => 'GET',
'action' => function () {
if ($user = $this->kirby()->auth()->user()) {
return $this->resolve($user)->view('auth');
}
2021-10-29 18:05:46 +02:00
2022-08-31 16:08:03 +02:00
throw new NotFoundException('The user cannot be found');
}
],
[
'pattern' => 'auth/code',
'method' => 'POST',
'auth' => false,
'action' => function () {
$auth = $this->kirby()->auth();
2021-10-29 18:05:46 +02:00
2022-08-31 16:08:03 +02:00
// csrf token check
if ($auth->type() === 'session' && $auth->csrf() === false) {
throw new InvalidArgumentException('Invalid CSRF token');
}
2021-10-29 18:05:46 +02:00
2022-08-31 16:08:03 +02:00
$user = $auth->verifyChallenge($this->requestBody('code'));
2021-10-29 18:05:46 +02:00
2022-08-31 16:08:03 +02:00
return [
'code' => 200,
'status' => 'ok',
'user' => $this->resolve($user)->view('auth')->toArray()
];
}
],
[
'pattern' => 'auth/login',
'method' => 'POST',
'auth' => false,
'action' => function () {
$auth = $this->kirby()->auth();
$methods = $this->kirby()->system()->loginMethods();
2021-10-29 18:05:46 +02:00
2022-08-31 16:08:03 +02:00
// csrf token check
if ($auth->type() === 'session' && $auth->csrf() === false) {
throw new InvalidArgumentException('Invalid CSRF token');
}
2021-10-29 18:05:46 +02:00
2022-08-31 16:08:03 +02:00
$email = $this->requestBody('email');
$long = $this->requestBody('long');
$password = $this->requestBody('password');
2021-10-29 18:05:46 +02:00
2022-08-31 16:08:03 +02:00
if ($password) {
if (isset($methods['password']) !== true) {
throw new InvalidArgumentException('Login with password is not enabled');
}
2021-10-29 18:05:46 +02:00
2022-08-31 16:08:03 +02:00
if (
isset($methods['password']['2fa']) === true &&
$methods['password']['2fa'] === true
) {
$status = $auth->login2fa($email, $password, $long);
} else {
$user = $auth->login($email, $password, $long);
}
} else {
if (isset($methods['code']) === true) {
$mode = 'login';
} elseif (isset($methods['password-reset']) === true) {
$mode = 'password-reset';
} else {
throw new InvalidArgumentException('Login without password is not enabled');
}
2021-10-29 18:05:46 +02:00
2022-08-31 16:08:03 +02:00
$status = $auth->createChallenge($email, $long, $mode);
}
2021-10-29 18:05:46 +02:00
2022-08-31 16:08:03 +02:00
if (isset($user)) {
return [
'code' => 200,
'status' => 'ok',
'user' => $this->resolve($user)->view('auth')->toArray()
];
} else {
return [
'code' => 200,
'status' => 'ok',
'challenge' => $status->challenge()
];
}
}
],
[
'pattern' => 'auth/logout',
'method' => 'POST',
'auth' => false,
'action' => function () {
$this->kirby()->auth()->logout();
return true;
}
],
2021-10-29 18:05:46 +02:00
];