This repository has been archived on 2024-06-26. You can view files and clone it, but cannot push or open issues or pull requests.
sakura/app/Controllers/AuthController.php

457 lines
16 KiB
PHP
Raw Normal View History

2016-02-27 16:46:16 +00:00
<?php
/**
* Holds the auth controllers.
* @package Sakura
*/
namespace Sakura\Controllers;
2016-03-17 19:09:00 +00:00
use Sakura\ActionCode;
2016-02-27 16:46:16 +00:00
use Sakura\Config;
2016-08-07 14:10:27 +00:00
use Sakura\CurrentSession;
2016-02-27 16:46:16 +00:00
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
{
2016-03-27 21:18:57 +00:00
/**
* Touch the login rate limit.
2016-12-04 16:33:52 +00:00
* @param int $user The ID of the user that attempted to log in.
* @param bool $success Whether the login attempt was successful.
2016-03-27 21:18:57 +00:00
*/
2016-12-04 16:33:52 +00:00
protected function touchRateLimit(int $user, bool $success = false): void
2016-02-27 16:46:16 +00:00
{
DB::table('login_attempts')
->insert([
2016-03-27 21:18:57 +00:00
'attempt_success' => $success ? 1 : 0,
2016-02-27 16:46:16 +00:00
'attempt_timestamp' => time(),
2016-03-27 21:18:57 +00:00
'attempt_ip' => Net::pton(Net::ip()),
2016-02-27 16:46:16 +00:00
'user_id' => $user,
]);
}
2016-03-27 21:18:57 +00:00
/**
* End the current session.
* @return string
*/
2016-12-04 16:33:52 +00:00
public function logout(): string
2016-02-27 16:46:16 +00:00
{
2016-09-13 14:41:42 +00:00
if (!session_check()) {
2016-12-08 23:19:18 +00:00
return $this->json(['error' => 'Logout failed.']);
2016-02-27 16:46:16 +00:00
}
// Destroy the active session
2016-08-07 14:10:27 +00:00
CurrentSession::stop();
2016-02-27 16:46:16 +00:00
2016-12-08 18:45:20 +00:00
return $this->json(['error' => null]);
2016-02-27 16:46:16 +00:00
}
2016-03-27 21:18:57 +00:00
/**
* Login page.
2016-03-27 21:18:57 +00:00
* @return string
*/
2016-12-04 16:33:52 +00:00
public function login(): string
2016-02-27 16:46:16 +00:00
{
if (!session_check()) {
2016-12-08 18:04:27 +00:00
return $this->json(['error' => 'Your session expired! Please refresh and try again.']);
}
2016-02-27 16:46:16 +00:00
// Get request variables
2016-12-07 23:34:59 +00:00
$username = $_POST['username'] ?? null;
$password = $_POST['password'] ?? null;
2016-02-27 16:46:16 +00:00
// Check if we haven't hit the rate limit
$rates = DB::table('login_attempts')
2016-03-27 21:18:57 +00:00
->where('attempt_ip', Net::pton(Net::ip()))
2016-02-27 16:46:16 +00:00
->where('attempt_timestamp', '>', time() - 1800)
->where('attempt_success', '0')
->count();
if ($rates > 4) {
2016-12-07 23:34:59 +00:00
return $this->json(['error' => 'Your have hit the login rate limit, try again later.']);
2016-02-27 16:46:16 +00:00
}
2016-04-01 21:44:31 +00:00
$user = User::construct(clean_string($username, true, true));
2016-02-27 16:46:16 +00:00
// Check if the user that's trying to log in actually exists
if ($user->id === 0) {
$this->touchRateLimit($user->id);
2016-12-07 23:34:59 +00:00
return $this->json(['error' => 'The user you tried to log into does not exist.']);
2016-02-27 16:46:16 +00:00
}
2016-08-01 21:09:27 +00:00
if ($user->passwordExpired()) {
2016-12-07 23:34:59 +00:00
return $this->json(['error' => 'Your password expired.']);
}
2016-02-27 16:46:16 +00:00
2016-08-01 21:09:27 +00:00
if (!$user->verifyPassword($password)) {
$this->touchRateLimit($user->id);
2016-12-07 23:34:59 +00:00
return $this->json(['error' => 'The password you entered was invalid.']);
2016-02-27 16:46:16 +00:00
}
// Check if the user has the required privs to log in
if (!$user->activated) {
2016-02-27 16:46:16 +00:00
$this->touchRateLimit($user->id);
2016-12-07 23:34:59 +00:00
return $this->json(['error' => "Your account isn't activated, check your e-mail!"]);
2016-02-27 16:46:16 +00:00
}
// Generate a session key
2016-08-07 14:10:27 +00:00
$session = CurrentSession::create(
$user->id,
Net::ip(),
get_country_code(),
2016-12-07 23:34:59 +00:00
clean_string($_SERVER['HTTP_USER_AGENT'] ?? '')
2016-08-07 14:10:27 +00:00
);
2016-02-27 16:46:16 +00:00
2016-07-26 17:29:53 +00:00
$cookiePrefix = config('cookie.prefix');
2016-12-07 23:34:59 +00:00
setcookie("{$cookiePrefix}id", $user->id, time() + 604800);
setcookie("{$cookiePrefix}session", $session->key, time() + 604800);
2016-02-27 16:46:16 +00:00
2016-03-27 21:18:57 +00:00
$this->touchRateLimit($user->id, true);
2016-02-27 16:46:16 +00:00
2016-12-07 23:34:59 +00:00
$msg = ['error' => null];
2016-03-17 19:09:00 +00:00
2016-12-07 23:34:59 +00:00
if (!$user->lastOnline) {
$msg['go'] = route('info.welcome');
}
2016-02-27 16:46:16 +00:00
2016-12-07 23:34:59 +00:00
return $this->json($msg);
2016-02-28 17:45:25 +00:00
}
2016-03-27 21:18:57 +00:00
/**
* Do a registration attempt.
* @return string
*/
2016-12-04 16:33:52 +00:00
public function register(): string
2016-02-28 17:45:25 +00:00
{
2016-03-17 19:09:00 +00:00
// Preliminarily set registration to failed
$redirect = route('auth.register');
2016-02-28 17:45:25 +00:00
// Check if authentication is disallowed
2016-07-26 17:29:53 +00:00
if (config('user.disable_registration')) {
2016-02-28 17:45:25 +00:00
$message = 'Registration is disabled for security checkups! Try again later.';
return view('global/information', compact('message', 'redirect'));
2016-02-28 17:45:25 +00:00
}
2016-08-07 14:10:27 +00:00
if (!session_check()) {
// Attempt to check if a user has already registered from the current IP
$getUserIP = DB::table('users')
->where('register_ip', Net::pton(Net::ip()))
->orWhere('last_ip', Net::pton(Net::ip()))
->get();
$vars = [];
if ($getUserIP) {
$vars = [
'haltRegistration' => count($getUserIP) > 1,
'haltName' => $getUserIP[array_rand($getUserIP)]->username,
];
}
2016-02-28 17:45:25 +00:00
return view('auth/register', $vars);
2016-02-28 17:45:25 +00:00
}
// Grab forms
$username = $_POST['username'] ?? null;
$password = $_POST['password'] ?? null;
$email = $_POST['email'] ?? null;
2016-02-28 17:45:25 +00:00
// Append username and email to the redirection url
$redirect .= "?username={$username}&email={$email}";
// Attempt to get account data
2016-04-01 21:44:31 +00:00
$user = User::construct(clean_string($username, true, true));
2016-02-28 17:45:25 +00:00
// Check if the username already exists
if ($user && $user->id !== 0) {
2016-04-01 21:44:31 +00:00
$message = "{$user->username} is already a member here!"
. " If this is you please use the password reset form instead of making a new account.";
return view('global/information', compact('message', 'redirect'));
2016-02-28 17:45:25 +00:00
}
// Username too short
2016-07-26 17:29:53 +00:00
if (strlen($username) < config('user.name_min')) {
2016-02-28 17:45:25 +00:00
$message = 'Your name must be at least 3 characters long.';
return view('global/information', compact('message', 'redirect'));
2016-02-28 17:45:25 +00:00
}
// Username too long
2016-07-26 17:29:53 +00:00
if (strlen($username) > config('user.name_max')) {
2016-02-28 17:45:25 +00:00
$message = 'Your name can\'t be longer than 16 characters.';
return view('global/information', compact('message', 'redirect'));
2016-02-28 17:45:25 +00:00
}
// Check if the given email address is formatted properly
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$message = 'Your e-mail address is formatted incorrectly.';
return view('global/information', compact('message', 'redirect'));
2016-02-28 17:45:25 +00:00
}
// Check the MX record of the email
2016-04-01 21:44:31 +00:00
if (!check_mx_record($email)) {
2016-02-28 17:45:25 +00:00
$message = 'No valid MX-Record found on the e-mail address you supplied.';
return view('global/information', compact('message', 'redirect'));
2016-02-28 17:45:25 +00:00
}
// Check if the e-mail has already been used
$emailCheck = DB::table('users')
->where('email', $email)
->count();
if ($emailCheck) {
$message = 'Someone already registered using this email!';
return view('global/information', compact('message', 'redirect'));
2016-02-28 17:45:25 +00:00
}
// Check password entropy
2016-07-26 17:29:53 +00:00
if (password_entropy($password) < config('user.pass_min_entropy')) {
2016-02-28 17:45:25 +00:00
$message = 'Your password is too weak, try adding some special characters.';
return view('global/information', compact('message', 'redirect'));
2016-02-28 17:45:25 +00:00
}
2016-12-07 15:33:26 +00:00
$requireActive = boolval(config('user.require_activation'));
$user = User::create($username, $password, $email, !$requireActive);
2016-02-28 17:45:25 +00:00
// Check if we require e-mail activation
if ($requireActive) {
2016-04-01 21:44:31 +00:00
$this->sendActivationMail($user);
2016-02-28 17:45:25 +00:00
}
// Return true with a specific message if needed
2016-12-07 23:34:59 +00:00
$redirect = route('main.index');
2016-12-07 15:33:26 +00:00
$message = 'Your registration went through!';
$message .= $requireActive ? ' An activation e-mail has been sent.' : ' Welcome to ' . config('general.name') . '!';
2016-02-28 17:45:25 +00:00
return view('global/information', compact('message', 'redirect'));
2016-02-28 17:45:25 +00:00
}
2016-03-17 19:09:00 +00:00
2016-03-27 21:18:57 +00:00
/**
* Do a activation attempt.
* @return string
*/
2016-12-04 16:33:52 +00:00
public function activate(): string
2016-03-17 19:09:00 +00:00
{
// Preliminarily set activation to failed
$redirect = route('main.index');
2016-03-17 19:09:00 +00:00
// Attempt to get the required GET parameters
$userId = $_GET['u'] ?? 0;
$key = $_GET['k'] ?? "";
2016-03-17 19:09:00 +00:00
// Attempt to create a user object
$user = User::construct($userId);
// Quit if the user ID is 0
if ($user->id === 0) {
$message = "This user does not exist! Contact us if you think this isn't right.";
return view('global/information', compact('message', 'redirect'));
2016-03-17 19:09:00 +00:00
}
// Check if the user is already active
2016-11-04 17:51:11 +00:00
if ($user->activated) {
2016-03-17 19:09:00 +00:00
$message = "Your account is already activated! Why are you here?";
return view('global/information', compact('message', 'redirect'));
2016-03-17 19:09:00 +00:00
}
// Validate the activation key
$action = ActionCode::validate('ACTIVATE', $key, $user->id);
if (!$action) {
$message = "Invalid activation code! Contact us if you think this isn't right.";
return view('global/information', compact('message', 'redirect'));
2016-03-17 19:09:00 +00:00
}
2016-12-07 15:33:26 +00:00
DB::table('users')
->where('user_id', $userId)
->update(['user_activated' => 1]);
2016-03-17 19:09:00 +00:00
2016-12-07 23:34:59 +00:00
$redirect = route('main.index');
2016-07-26 17:29:53 +00:00
$message = "Your account is activated, welcome to " . config('general.name') . "!";
return view('global/information', compact('message', 'redirect'));
2016-03-17 19:09:00 +00:00
}
2016-03-19 15:29:47 +00:00
2016-03-27 21:18:57 +00:00
/**
* Do a reactivation preparation attempt.
* @return string
*/
2016-12-04 16:33:52 +00:00
public function reactivate(): string
2016-03-19 15:29:47 +00:00
{
// Validate session
2016-08-07 14:10:27 +00:00
if (!session_check()) {
return view('auth/reactivate');
2016-03-19 15:29:47 +00:00
}
// Preliminarily set registration to failed
$redirect = route('auth.reactivate');
2016-03-19 15:29:47 +00:00
// Grab forms
2016-04-01 21:44:31 +00:00
$username = isset($_POST['username']) ? clean_string($_POST['username'], true) : null;
$email = isset($_POST['email']) ? clean_string($_POST['email'], true) : null;
2016-03-19 15:29:47 +00:00
// Do database request
$getUser = DB::table('users')
->where('username_clean', $username)
->where('email', $email)
->get(['user_id']);
// Check if user exists
if (!$getUser) {
$message = "User not found! Double check your username and e-mail address!";
return view('global/information', compact('message', 'redirect'));
2016-03-19 15:29:47 +00:00
}
// Create user object
$user = User::construct($getUser[0]->user_id);
// Check if a user is activated
2016-11-04 17:51:11 +00:00
if ($user->activated) {
2016-03-19 15:29:47 +00:00
$message = "Your account is already activated! Why are you here?";
return view('global/information', compact('message', 'redirect'));
2016-03-19 15:29:47 +00:00
}
// Send activation e-mail to user
2016-04-01 21:44:31 +00:00
$this->sendActivationMail($user);
2016-03-19 15:29:47 +00:00
2016-12-07 23:34:59 +00:00
$redirect = route('main.index');
2016-03-19 15:29:47 +00:00
$message = "Sent the e-mail! Make sure to check your spam folder as well!";
return view('global/information', compact('message', 'redirect'));
2016-03-19 15:29:47 +00:00
}
2016-03-27 21:18:57 +00:00
/**
* Do a password reset attempt.
* @return string
*/
2016-12-04 16:33:52 +00:00
public function resetPassword(): string
2016-03-19 15:29:47 +00:00
{
// Validate session
2016-08-07 14:10:27 +00:00
if (!session_check()) {
return view('auth/resetpassword');
2016-03-19 15:29:47 +00:00
}
// Preliminarily set action to failed
$redirect = route('main.index');
2016-03-19 15:29:47 +00:00
// Attempt to get the various required GET parameters
$userId = $_POST['user'] ?? 0;
$key = $_POST['key'] ?? "";
$password = $_POST['password'] ?? "";
$userName = clean_string($_POST['username'] ?? "", true);
$email = clean_string($_POST['email'] ?? "", true);
2016-03-19 15:29:47 +00:00
// Create user object
$user = User::construct($userId ? $userId : $userName);
// Quit if the user ID is 0
if ($user->id === 0 || ($email !== null ? $email !== $user->email : false)) {
$message = "This user does not exist! Contact us if you think this isn't right.";
return view('global/information', compact('message', 'redirect'));
2016-03-19 15:29:47 +00:00
}
// Check if the user is active
if (!$user->activated) {
2016-03-19 15:29:47 +00:00
$message = "Your account is deactivated, go activate it first...";
return view('global/information', compact('message', 'redirect'));
2016-03-19 15:29:47 +00:00
}
if ($key && $password) {
// Check password entropy
2016-07-26 17:29:53 +00:00
if (password_entropy($password) < config('user.pass_min_entropy')) {
2016-03-19 15:29:47 +00:00
$message = "Your password doesn't meet the strength requirements!";
return view('global/information', compact('message', 'redirect'));
2016-03-19 15:29:47 +00:00
}
// Validate the activation key
$action = ActionCode::validate('LOST_PASS', $key, $user->id);
if (!$action) {
$message = "Invalid verification code! Contact us if you think this isn't right.";
return view('global/information', compact('message', 'redirect'));
2016-03-19 15:29:47 +00:00
}
2016-08-01 21:09:27 +00:00
$user->setPassword($password);
2016-03-19 15:29:47 +00:00
$message = "Changed your password! You may now log in.";
2016-12-07 23:34:59 +00:00
$redirect = route('main.index');
2016-03-19 15:29:47 +00:00
} else {
2016-04-01 21:44:31 +00:00
// Send the e-mail
$this->sendPasswordMail($user);
2016-03-19 15:29:47 +00:00
$message = "Sent the e-mail, keep an eye on your spam folder as well!";
$redirect = route('main.index');
2016-03-19 15:29:47 +00:00
}
return view('global/information', compact('message', 'redirect'));
2016-03-19 15:29:47 +00:00
}
2016-04-01 21:44:31 +00:00
/**
* Send the activation e-mail
* @param User $user
*/
2016-12-04 16:33:52 +00:00
private function sendActivationMail(User $user): void
2016-04-01 21:44:31 +00:00
{
// Generate activation key
$activate = ActionCode::generate('ACTIVATE', $user->id);
2016-07-26 17:29:53 +00:00
$siteName = config('general.name');
$baseUrl = "http://{$_SERVER['HTTP_HOST']}";
$activateLink = route('auth.activate') . "?u={$user->id}&k={$activate}";
$profileLink = route('user.profile', $user->id);
2016-07-26 17:29:53 +00:00
$signature = config('mail.signature');
2016-04-01 21:44:31 +00:00
// Build the e-mail
$message = "Welcome to {$siteName}!\r\n\r\n"
. "Please keep this e-mail for your records. Your account intormation is as follows:\r\n\r\n"
. "----------------------------\r\n\r\n"
. "Username: {$user->username}\r\n\r\n"
. "Your profile: {$baseUrl}{$profileLink}\r\n\r\n"
. "----------------------------\r\n\r\n"
. "Please visit the following link in order to activate your account:\r\n\r\n"
. "{$baseUrl}{$activateLink}\r\n\r\n"
. "Your password has been securely stored in our database and cannot be retrieved. "
. "In the event that it is forgotten,"
. " you will be able to reset it using the email address associated with your account.\r\n\r\n"
. "Thank you for registering.\r\n\r\n"
. "--\r\n\r\nThanks\r\n\r\n{$signature}";
// Send the message
send_mail([$user->email => $user->username], "{$siteName} activation mail", $message);
}
/**
* Send the activation e-mail
* @param User $user
*/
2016-12-04 16:33:52 +00:00
private function sendPasswordMail(User $user): void
2016-04-01 21:44:31 +00:00
{
// Generate the verification key
$verk = ActionCode::generate('LOST_PASS', $user->id);
2016-07-26 17:29:53 +00:00
$siteName = config('general.name');
$baseUrl = "http://{$_SERVER['HTTP_HOST']}";
$reactivateLink = route('auth.resetpassword') . "?u={$user->id}&k={$verk}";
2016-07-26 17:29:53 +00:00
$signature = config('mail.signature');
2016-04-01 21:44:31 +00:00
// Build the e-mail
$message = "Hello {$user->username},\r\n\r\n"
. "You are receiving this notification because you have (or someone pretending to be you has)"
. " requested a password reset link to be sent for your account on \"{$siteName}\"."
. " If you did not request this notification then please ignore it,"
. " if you keep receiving it please contact the site administrator.\r\n\r\n"
. "To use this password reset key you need to go to a special page."
. " To do this click the link provided below.\r\n\r\n"
. "{$baseUrl}{$reactivateLink}\r\n\r\n"
. "If successful you should be able to change your password here.\r\n\r\n"
. "You can of course change this password yourself via the settings page."
. " If you have any difficulties please contact the site administrator.\r\n\r\n"
. "--\r\n\r\nThanks\r\n\r\n{$signature}";
// Send the message
send_mail([$user->email => $user->username], "{$siteName} password restoration", $message);
}
2016-02-27 16:46:16 +00:00
}