360 lines
12 KiB
PHP
360 lines
12 KiB
PHP
<?php
|
|
/**
|
|
* Holds the auth controllers.
|
|
* @package Sakura
|
|
*/
|
|
|
|
namespace Sakura\Controllers;
|
|
|
|
use Phroute\Phroute\Exception\HttpMethodNotAllowedException;
|
|
use Sakura\ActionCode;
|
|
use Sakura\Config;
|
|
use Sakura\CurrentSession;
|
|
use Sakura\DB;
|
|
use Sakura\Net;
|
|
use Sakura\User;
|
|
|
|
/**
|
|
* Authentication controllers.
|
|
* @package Sakura
|
|
* @author Julian van de Groep <me@flash.moe>
|
|
*/
|
|
class AuthController extends Controller
|
|
{
|
|
/**
|
|
* Touch the login rate limit.
|
|
* @param int $user The ID of the user that attempted to log in.
|
|
* @param bool $success Whether the login attempt was successful.
|
|
*/
|
|
protected function touchRateLimit(int $user, bool $success = false): void
|
|
{
|
|
DB::table('login_attempts')
|
|
->insert([
|
|
'attempt_success' => $success ? 1 : 0,
|
|
'attempt_timestamp' => time(),
|
|
'attempt_ip' => Net::pton(Net::ip()),
|
|
'user_id' => $user,
|
|
]);
|
|
}
|
|
|
|
protected function authenticate(User $user): void
|
|
{
|
|
// Generate a session key
|
|
$session = CurrentSession::create(
|
|
$user->id,
|
|
Net::ip(),
|
|
get_country_code(),
|
|
clean_string($_SERVER['HTTP_USER_AGENT'] ?? '')
|
|
);
|
|
|
|
$cookiePrefix = config('cookie.prefix');
|
|
setcookie("{$cookiePrefix}id", $user->id, time() + 604800, '/');
|
|
setcookie("{$cookiePrefix}session", $session->key, time() + 604800, '/');
|
|
|
|
$this->touchRateLimit($user->id, true);
|
|
}
|
|
|
|
/**
|
|
* End the current session.
|
|
* @throws HttpMethodNotAllowedException
|
|
*/
|
|
public function logout(): void
|
|
{
|
|
if (!session_check()) {
|
|
throw new HttpMethodNotAllowedException;
|
|
}
|
|
|
|
// Destroy the active session
|
|
CurrentSession::stop();
|
|
}
|
|
|
|
/**
|
|
* Login page.
|
|
* @return string
|
|
*/
|
|
public function login(): string
|
|
{
|
|
if (!session_check()) {
|
|
return $this->json(['error' => 'Your session expired! Please refresh and try again.']);
|
|
}
|
|
|
|
// Get request variables
|
|
$username = $_POST['username'] ?? null;
|
|
$password = $_POST['password'] ?? null;
|
|
|
|
// Check if we haven't hit the rate limit
|
|
$rates = DB::table('login_attempts')
|
|
->where('attempt_ip', Net::pton(Net::ip()))
|
|
->where('attempt_timestamp', '>', time() - 1800)
|
|
->where('attempt_success', '0')
|
|
->count();
|
|
|
|
if ($rates > 4) {
|
|
return $this->json(['error' => 'Your have hit the login rate limit, try again later.']);
|
|
}
|
|
|
|
$user = User::construct(clean_string($username, true, true));
|
|
|
|
// Check if the user that's trying to log in actually exists
|
|
if ($user->id === 0) {
|
|
$this->touchRateLimit($user->id);
|
|
return $this->json(['error' => 'The user you tried to log into does not exist.']);
|
|
}
|
|
|
|
if ($user->passwordExpired()) {
|
|
return $this->json(['error' => 'Your password expired.']);
|
|
}
|
|
|
|
if (!$user->verifyPassword($password)) {
|
|
$this->touchRateLimit($user->id);
|
|
return $this->json(['error' => 'The password you entered was invalid.']);
|
|
}
|
|
|
|
// Check if the user has the required privs to log in
|
|
if (!$user->activated) {
|
|
$this->touchRateLimit($user->id);
|
|
return $this->json(['error' => "Your account isn't activated, check your e-mail!"]);
|
|
}
|
|
|
|
$this->authenticate($user);
|
|
|
|
$msg = ['error' => null];
|
|
|
|
if (!$user->lastOnline) {
|
|
$msg['go'] = route('info.welcome');
|
|
}
|
|
|
|
return $this->json($msg);
|
|
}
|
|
|
|
/**
|
|
* Do a registration attempt.
|
|
* @throws HttpMethodNotAllowedException
|
|
* @return string
|
|
*/
|
|
public function register(): string
|
|
{
|
|
if (!session_check()) {
|
|
return view('auth/register', compact('registered_username'));
|
|
}
|
|
|
|
// Check if authentication is disallowed
|
|
if (config('user.disable_registration')) {
|
|
return $this->json(['error' => 'Registration is currently disabled.']);
|
|
}
|
|
|
|
$username = $_POST['username'] ?? null;
|
|
$password = $_POST['password'] ?? null;
|
|
$email = $_POST['email'] ?? null;
|
|
|
|
// Attempt to get account data
|
|
$user = User::construct(clean_string($username, true, true));
|
|
|
|
// Check if the username already exists
|
|
if ($user && $user->id !== 0) {
|
|
$message = "{$user->username} is already a member here!"
|
|
. "\r\nIf this is you please use the password reset form instead of making a new account.";
|
|
return $this->json(['error' => $message]);
|
|
}
|
|
|
|
// Username too short
|
|
if (strlen($username) < config('user.name_min')) {
|
|
return $this->json(['error' => 'Your name must be at least 3 characters long.']);
|
|
}
|
|
|
|
// Username too long
|
|
if (strlen($username) > config('user.name_max')) {
|
|
return $this->json(['error' => "Your name can't be longer than 16 characters."]);
|
|
}
|
|
|
|
// Check if the given email address is formatted properly
|
|
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
|
return $this->json(['error' => 'Your e-mail address is formatted incorrectly.']);
|
|
}
|
|
|
|
// Check the MX record of the email
|
|
if (!check_mx_record($email)) {
|
|
return $this->json(['error' => 'No valid MX-Record found on the e-mail address you supplied.']);
|
|
}
|
|
|
|
// Check if the e-mail has already been used
|
|
$emailCheck = DB::table('users')
|
|
->where('email', $email)
|
|
->count();
|
|
if ($emailCheck) {
|
|
return $this->json(['error' => 'Someone already registered using this email!']);
|
|
}
|
|
|
|
// Check password entropy
|
|
if (password_entropy($password) < config('user.pass_min_entropy')) {
|
|
return $this->json([
|
|
'error' => 'Your password is considered too weak, try adding some special characters.'
|
|
]);
|
|
}
|
|
|
|
$activation = boolval(config('user.require_activation'));
|
|
$user = User::create($username, $password, $email, !$activation);
|
|
|
|
// Check if we require e-mail activation
|
|
if ($activation) {
|
|
$message = 'Almost there, only activation is left! Please check your e-mail for the link.';
|
|
$this->sendActivationMail($user);
|
|
} else {
|
|
$this->authenticate($user);
|
|
}
|
|
|
|
return $this->json(['text' => $message ?? null, 'go' => route('main.index')]);
|
|
}
|
|
|
|
/**
|
|
* Do a (re)activation attempt.
|
|
* @return string
|
|
*/
|
|
public function activate(): string
|
|
{
|
|
// activation link handler
|
|
if (isset($_GET['u'], $_GET['k'])) {
|
|
$user = User::construct($_GET['u'] ?? null);
|
|
|
|
if ($user->id === 0
|
|
|| $user->activated
|
|
|| !ActionCode::validate('ACTIVATE', $_GET['k'] ?? null, $user->id)) {
|
|
return view('auth/activate_failed');
|
|
}
|
|
|
|
DB::table('users')
|
|
->where('user_id', $user->id)
|
|
->update(['user_activated' => 1]);
|
|
|
|
$this->authenticate($user);
|
|
|
|
return redirect(route('main.index'));
|
|
}
|
|
|
|
// resend handler
|
|
if (session_check() && isset($_POST['username'], $_POST['email'])) {
|
|
$id = DB::table('users')
|
|
->where('username_clean', clean_string($_POST['username'], true))
|
|
->where('email', clean_string($_POST['email'], true))
|
|
->value('user_id');
|
|
|
|
if (!$id) {
|
|
return $this->json(['error' => "Couldn't find this username/e-mail combination, double check them!"]);
|
|
}
|
|
|
|
$user = User::construct($id);
|
|
|
|
if ($user->activated) {
|
|
return $this->json(['error' => 'Your account is already activated! Why are you here?', 'go' => route('main.index')]);
|
|
}
|
|
|
|
$this->sendActivationMail($user);
|
|
|
|
return $this->json([
|
|
'text' => "The e-mail should be on its way, don't forget to also check your spam folder!",
|
|
'go' => route('main.index')
|
|
]);
|
|
}
|
|
|
|
return view('auth/activate');
|
|
}
|
|
|
|
/**
|
|
* Do a password reset attempt.
|
|
* @return string
|
|
*/
|
|
public function resetPassword(): string
|
|
{
|
|
if (session_check()) {
|
|
$userId = $_POST['user'] ?? 0;
|
|
$key = $_POST['key'] ?? "";
|
|
$password = $_POST['password'] ?? "";
|
|
$userName = clean_string($_POST['username'] ?? "", true);
|
|
$email = clean_string($_POST['email'] ?? "", true);
|
|
$user = User::construct($userId ? $userId : $userName);
|
|
|
|
if ($user->id === 0 || (strlen($email) > 0 ? $email !== $user->email : false)) {
|
|
return $this->json(['error' => "This user does not exist! Contact us if you think this isn't right."]);
|
|
}
|
|
|
|
if (!$user->activated) {
|
|
return $this->json([
|
|
'error' => "Your account isn't activated, go activate it first...",
|
|
'go' => route('auth.activate'),
|
|
]);
|
|
}
|
|
|
|
if ($key && $password) {
|
|
if (password_entropy($password) < config('user.pass_min_entropy')) {
|
|
return $this->json(['error' => "Your password doesn't meet the strength requirements!"]);
|
|
}
|
|
|
|
$action = ActionCode::validate('LOST_PASS', $key, $user->id);
|
|
|
|
if (!$action) {
|
|
return $this->json(['error' => "Invalid verification code! Contact us if you think this isn't right."]);
|
|
}
|
|
|
|
$user->setPassword($password);
|
|
$this->authenticate($user);
|
|
|
|
return $this->json([
|
|
'text' => "Changed your password!",
|
|
'go' => route('main.index'),
|
|
]);
|
|
}
|
|
|
|
$this->sendPasswordMail($user);
|
|
|
|
return $this->json([
|
|
'text' => "The e-mail should be on its way, don't forget to also check your spam folder!",
|
|
'go' => route('main.index'),
|
|
]);
|
|
}
|
|
|
|
return view('auth/resetpassword');
|
|
}
|
|
|
|
/**
|
|
* Send the activation e-mail
|
|
* @param User $user
|
|
*/
|
|
private function sendActivationMail(User $user): void
|
|
{
|
|
$activate = ActionCode::generate('ACTIVATE', $user->id);
|
|
$siteName = config('general.name');
|
|
$baseUrl = "http://{$_SERVER['HTTP_HOST']}";
|
|
$activateLink = route('auth.activate') . "?u={$user->id}&k={$activate}";
|
|
$signature = config('mail.signature');
|
|
|
|
$message = "Hey {$user->username}, welcome to {$siteName}!\r\n\r\n"
|
|
. "Your account is almost ready, the only thing left to do is for you to click the following link:\r\n"
|
|
. "{$baseUrl}{$activateLink}\r\n\r\n"
|
|
. "Hope to see you around,\r\n{$signature}";
|
|
|
|
send_mail([$user->email => $user->username], "Welcome to {$siteName}!", $message);
|
|
}
|
|
|
|
/**
|
|
* Send the activation e-mail
|
|
* @param User $user
|
|
*/
|
|
private function sendPasswordMail(User $user): void
|
|
{
|
|
$verk = ActionCode::generate('LOST_PASS', $user->id);
|
|
$siteName = config('general.name');
|
|
$baseUrl = "http://{$_SERVER['HTTP_HOST']}";
|
|
$pass_confirm = route('auth.resetpassword') . "?u={$user->id}&k={$verk}";
|
|
$signature = config('mail.signature');
|
|
|
|
$message = "Hey {$user->username},\r\n\r\n"
|
|
. "You, or someone pretending to be you, requested a password change for your account!\r\n"
|
|
. "Click the following link to confirm the password change:\r\n"
|
|
. "{$baseUrl}{$pass_confirm}\r\n\r\n"
|
|
. "If this wasn't you please just ignore this e-mail, unless this isn't the first"
|
|
. " time this has happened in which case you should contact a staff member.\r\n\r\n"
|
|
. "--\r\n{$signature}";
|
|
|
|
send_mail([$user->email => $user->username], "{$siteName} password restoration", $message);
|
|
}
|
|
}
|