Is this safe and secure?
function loginout_LogInType($type) {
global $DB;
if( $type = "user" ) {
// Fetch User from DB - by User
$fetchUser = $DB->prepare("
SELECT
u_id, u_user, u_email, u_password, u_login_attempts, u_locked
FROM
{$DB->CONFIG['sql_tbl_prefix']}users
WHERE
u_user=:username
");
$fetchUser->execute( [
':username' => $_POST['username'],
] );
}
else {
global $USER;
// Fetch User from DB - by UserId
$fetchUser = $DB->prepare("
SELECT
u_id, u_password, u_login_attempts, u_locked
FROM
{$DB->CONFIG['sql_tbl_prefix']}users
WHERE
u_id=:uid
");
$fetchUser->execute( [
':uid' => $USER['u_id'],
] );
}
return $fetchUser->fetch();
}
function loginout_LogIn() {
global $CONFIG, $DB;
$errors = [];
$maxLogInAttempts = 3;
// Fetch the User Details:
$dbUser = loginout_LogInType('user');
// +------------------------------------------------------------------------------------------------------------------------------------------------
if ( false !== $dbUser ) {
// Is the account locked:
if( $dbUser['u_locked'] != 1 ) {
if( ! password_verify($_POST['password'], $dbUser['u_password'] ) ) {
$errors[] = "invalid_login_2_credentials";
if( $dbUser['u_login_attempts'] >= 0 && $dbUser['u_login_attempts'] < $maxLogInAttempts ) {
// Update FAILED login attempts:
$userLogInAttempts = $DB->prepare("
UPDATE
{$DB->CONFIG['sql_tbl_prefix']}users
SET
u_login_attempts = Coalesce(u_login_attempts, 0)+1, u_last_login_attempt = NOW()
WHERE
u_id=:uid
");
$userLogInAttempts->execute( [
':uid' => $dbUser['u_id'],
] );
}
else {
// Incorrect PASSWORD:
// Update FAILED login attempts:
$userLogInAttempts = $DB->prepare("
UPDATE
{$DB->CONFIG['sql_tbl_prefix']}users
SET
u_login_attempts = Coalesce(u_login_attempts, 0)+1, u_last_login_attempt = NOW(), u_locked=1
WHERE
u_id=:uid
");
$userLogInAttempts->execute( [
':uid' => $dbUser['u_id'],
] );
// ADD EMAIL TO QUEUE
$lockedEmail = $DB->prepare("
INSERT INTO
{$DB->CONFIG['sql_tbl_prefix']}email_queue (
eq_id, eq_to, eq_from, eq_subject, eq_message, eq_added
)
VALUES (
:id, :to, :from, :subject, :message, NOW()
)
");
$lockedEmail->execute( [
':id' => uniqid(),
':to' => $dbUser['u_email'],
':from' => $CONFIG['email_from'],
':subject' => "Account Locked",
':message' =>"Your account has now been locked for security reasons. <p>Sorry!</p>Test Message!"
] );
}
}
else {
// Login Successful:
// Update Last Login:
$userLastLogIn = $DB->prepare("
UPDATE
{$DB->CONFIG['sql_tbl_prefix']}users
SET
u_last_login = NOW()
WHERE
u_id=:uid
");
$userLastLogIn->execute( [
':uid' => $dbUser['u_id'],
] );
$_SESSION['user_id'] = $dbUser['u_id'];
// Return nothing, if we are a valid user...
}
}
else {
$errors[] = 'invalid_login_3_credentials';
}
}
else {
// Invalid DB User
$errors[] = "invalid_login_1_credentials";
}
// Return Errors - if any?
return $errors;
}
I've moved it into a function as the admin/user panels will also use this function to validate the user before changing things like email address and password changes?