summaryrefslogtreecommitdiff
path: root/app/Model/LastLoginModel.php
blob: 168213921774c2faff48e15d8b156096111ac451 (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
<?php

namespace Kanboard\Model;

use Kanboard\Core\Base;

/**
 * LastLogin model
 *
 * @package  Kanboard\Model
 * @author   Frederic Guillot
 */
class LastLoginModel extends Base
{
    /**
     * SQL table name
     *
     * @var string
     */
    const TABLE = 'last_logins';

    /**
     * Number of connections to keep for history
     *
     * @var integer
     */
    const NB_LOGINS = 10;

    /**
     * Create a new record
     *
     * @access public
     * @param  string   $auth_type   Authentication method
     * @param  integer  $user_id     User id
     * @param  string   $ip          IP Address
     * @param  string   $user_agent  User Agent
     * @return boolean
     */
    public function create($auth_type, $user_id, $ip, $user_agent)
    {
        $this->cleanup($user_id);

        return $this->db
            ->table(self::TABLE)
            ->insert(array(
                'auth_type' => $auth_type,
                'user_id' => $user_id,
                'ip' => $ip,
                'user_agent' => substr($user_agent, 0, 255),
                'date_creation' => time(),
            ));
    }

    /**
     * Cleanup login history
     *
     * @access public
     * @param  integer $user_id
     */
    public function cleanup($user_id)
    {
        $connections = $this->db
                            ->table(self::TABLE)
                            ->eq('user_id', $user_id)
                            ->desc('id')
                            ->findAllByColumn('id');

        if (count($connections) >= self::NB_LOGINS) {
            $this->db->table(self::TABLE)
                ->eq('user_id', $user_id)
                ->notin('id', array_slice($connections, 0, self::NB_LOGINS - 1))
                ->remove();
        }
    }

    /**
     * Get the last connections for a given user
     *
     * @access public
     * @param  integer  $user_id  User id
     * @return array
     */
    public function getAll($user_id)
    {
        return $this->db
                    ->table(self::TABLE)
                    ->eq('user_id', $user_id)
                    ->desc('id')
                    ->columns('id', 'auth_type', 'ip', 'user_agent', 'date_creation')
                    ->findAll();
    }
}