summaryrefslogtreecommitdiff
path: root/account/security.php
blob: 11738dc32377e6bd3003056fed68323c6808cd31 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?php

include_once "{$_SERVER['DOCUMENT_ROOT']}/lib/accounts.php";
include_once "{$_SERVER['DOCUMENT_ROOT']}/lib/alert.php";
include_once "{$_SERVER['DOCUMENT_ROOT']}/lib/config.php";
include_once "{$_SERVER['DOCUMENT_ROOT']}/lib/utils.php";

if ($_SERVER["REQUEST_METHOD"] != "POST" || !authorize_user(true)) {
    header("Location: /account");
    exit;
}

$db = new PDO(CONFIG['database']['url'], CONFIG['database']['user'], CONFIG['database']['pass']);

$stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$_SESSION["user_id"]]);

$user = $stmt->fetch();
$current_password = $_POST["password-current"] ?? "";

if ($user["password"] != null && !password_verify($current_password, $user["password"])) {
    generate_alert("/account", "Password is required to apply changes in 'Security' section");
    exit;
}

if (!empty($_POST["password-new"])) {
    $password = $_POST["password-new"];
    if (CONFIG['account']['minpasswordlength'] > strlen($password)) {
        generate_alert("/account", "Your password must be at least " . CONFIG['account']['minpasswordlength'] . " characters");
        exit;
    }

    $db->prepare("UPDATE users SET password = ? WHERE id = ?")
        ->execute([password_hash($password, PASSWORD_DEFAULT), $user["id"]]);
}

$private_profile = (int) (intval($_POST["make-private"] ?? "0") == 1);

$db->prepare("UPDATE user_preferences SET private_profile = ? WHERE id = ?")
    ->execute([$private_profile, $user["id"]]);

if (intval($_POST["signout-everywhere"] ?? "0") == 1) {
    $db->prepare("UPDATE users SET secret_key = ? WHERE id = ?")
        ->execute([generate_random_string(ACCOUNT_SECRET_KEY_LENGTH), $_SESSION["user_id"]]);

    session_unset();
    session_destroy();

    setcookie("secret_key", "", time() - 1000);
}

generate_alert("/account", "Your changes have been applied!", 200);