summaryrefslogtreecommitdiff
path: root/app/Model/PasswordReset.php
blob: c2d7dde9b22c6ce989f3d1747580dcb204ab17e5 (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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php

namespace Kanboard\Model;

/**
 * Password Reset Model
 *
 * @package  model
 * @author   Frederic Guillot
 */
class PasswordReset extends Base
{
    /**
     * SQL table name
     *
     * @var string
     */
    const TABLE = 'password_reset';

    /**
     * Token duration (30 minutes)
     *
     * @var string
     */
    const DURATION = 1800;

    /**
     * Get all tokens
     *
     * @access public
     * @param  integer $user_id
     * @return array
     */
    public function getAll($user_id)
    {
        return $this->db->table(self::TABLE)->eq('user_id', $user_id)->desc('date_creation')->limit(100)->findAll();
    }

    /**
     * Generate a new reset token for a user
     *
     * @access public
     * @param  string  $username
     * @param  integer $expiration
     * @return boolean|string
     */
    public function create($username, $expiration = 0)
    {
        $user_id = $this->db->table(User::TABLE)->eq('username', $username)->neq('email', '')->notNull('email')->findOneColumn('id');

        if (! $user_id) {
            return false;
        }

        $token = $this->token->getToken();

        $result = $this->db->table(self::TABLE)->insert(array(
            'token' => $token,
            'user_id' => $user_id,
            'date_expiration' => $expiration ?: time() + self::DURATION,
            'date_creation' => time(),
            'ip' => $this->request->getIpAddress(),
            'user_agent' => $this->request->getUserAgent(),
            'is_active' => 1,
        ));

        return $result ? $token : false;
    }

    /**
     * Get user id from the token
     *
     * @access public
     * @param  string $token
     * @return integer
     */
    public function getUserIdByToken($token)
    {
        return $this->db->table(self::TABLE)->eq('token', $token)->eq('is_active', 1)->gte('date_expiration', time())->findOneColumn('user_id');
    }

    /**
     * Disable all tokens for a user
     *
     * @access public
     * @param  integer $user_id
     * @return boolean
     */
    public function disable($user_id)
    {
        return $this->db->table(self::TABLE)->eq('user_id', $user_id)->update(array('is_active' => 0));
    }
}