chengkun
2025-09-09 1ff9e27b020822168a95edd83be567e7153837f3
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
<?php
 
namespace app\admin\util;
 
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Config;
use think\facade\Db;
use think\facade\Session;
use think\facade\Cookie;
 
 
class Opadmin {
    
    public string  $user_name;      //用户名
    private string $password;       //密码
    private mixed  $session_prefix; //SESSION前缀
    
    private string $kinfo     = 'admininfo';
    public mixed   $info;
    public string  $commfield = 'id,user_name,real_name,ban_access,initialize,start_time,end_time';
    
    /**
     * +----------------------------------------------------------
     * 构造函数,对象初始化
     * +----------------------------------------------------------
     * @param string $username 用户名
     * @param string $password 密码
     *                         +----------------------------------------------------------
     */
    public function __construct(string $username = '', string $password = '') {
        $this->session_prefix = Config::get('app.session_admin_prefix');
        //给保存SESSION的成员变量名称加上前缀
        $this->kinfo = $this->session_prefix . $this->kinfo;
        //用于登陆的时候初始化变量
        $this->user_name = $username;
        $this->password  = joinmd5($password);
        //判断session是否存在,存在就赋值
        if (session('?' . $this->kinfo)) {
            $this->info = session($this->kinfo);
        } elseif ($tempcookie = cookie($this->kinfo)) {
            $this->info = json_decode(html_entity_decode($tempcookie), TRUE); ////json转成数组保存到session
            session($this->kinfo, $this->info);
        }
    }
    
    /**
     * 用户登陆
     * @return bool|array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function login(): bool|array {
        $subwhere['user_name'] = $this->user_name;
//        $subwhere['password'] = $this->password;
        $tempinfo = Db::name('administrators')->field('id,password,ban_access,login_lock_time,login_try_num')->where($subwhere)->find();
        if (!$tempinfo) {
            $d['code']    = 400;
            $d['message'] = '账号或密码错误、请重试';
            return $d;
        }
        
        if ($tempinfo['login_lock_time'] != '' && time() - $tempinfo['login_lock_time'] < 600) {
            $d['code']    = 400;
            $d['message'] = '该账号已被锁定、请10分钟后重试';
            return $d;
        }
        $upd_where['id'] = $tempinfo['id'];
        if ($this->password != $tempinfo['password']) {
            // 次数 小于等于 1 -> 锁定登录操作
            if ($tempinfo['login_try_num'] <= 1) {
                $upd_data['login_lock_time'] = time();
                $upd_data['login_try_num']   = 5;
                Db::name('administrators')->where($upd_where)->save($upd_data);
                $d['code']    = 400;
                $d['message'] = '该账号已被锁定、请10分钟后重试';
            } else {
                // 次数 小于2 次数-1 -> 账号密码错误
                Db::name('administrators')->where($upd_where)->dec('login_try_num')->update();
                $d['code']    = 400;
                $d['message'] = '账号或密码错误、剩余' . ($tempinfo['login_try_num'] - 1) . '次';
            }
            return $d;
        }
        /////以下密码正确,成功登陆///////////
        Db::name('administrators')->where($upd_where)->save(['login_try_num' => 5]);
        if ($tempinfo['ban_access'] == 0) {
            $msg['code']    = 400;
            $msg['message'] = '该账号已被禁止登录';
            return $msg;
        }
        return $this->getlogininfo($tempinfo['id']);
    }
    
    /**
     * 获取用户登录信息
     * @param $id
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getlogininfo($id = ''): array {
        $subwhere['id'] = $id;
        $info           = Db::name('administrators')->field($this->commfield)->where($subwhere)->find();
        if ($info) {
            if ($info['initialize'] == 0 && ($info['start_time'] > time() || $info['end_time'] < time())) {
                $this->loginout();
                $msg['code']    = 400;
                $msg['message'] = '账号已过期,请联系管理员!';
                return $msg;
            }
            ///////登陆成功赋值////
            $this->info = $info;
            $this->saveSession();
            $this->writelogs();
            //更新登陆信息
            if ($this->updateInfo()) {
                $msg['code']    = 200;
                $msg['message'] = '登录成功';
            } else {
                $msg['code']    = 400;
                $msg['message'] = '登录失败';
            }
        } else {
            $msg['code']    = 400;
            $msg['message'] = '用户名或密码不正确';
        }
        return $msg;
    }
    
    /**
     * 更新用户信息
     * @return bool
     */
    private function updateInfo(): bool {
        $temp['login_time'] = time();
        $temp['login_ip']   = getIP();
        $where['id']        = $this->info['id'];
        $count              = Db::name('administrators')->where($where)->save($temp);
        if ($count > 0)
            return TRUE;
        else
            return FALSE;
    }
    
    /**
     * 写入登陆日志
     * @return void
     */
    private function writelogs(): void {
        //////登陆记录//////////
        $d['login_ip']   = getIP();
        $d['login_time'] = time();
        $d['admin_id']   = $this->info['id'];
        Db::name('admin_login_logs')->insert($d);
    }
    
    /**
     * 保存session
     * @return void
     */
    public function saveSession(): void {
        session($this->kinfo, $this->info);
        cookie($this->kinfo, json_encode($this->info, JSON_UNESCAPED_SLASHES), 3600 * 24 * 30);
    }
    
    /**
     * 判断用户是否登陆
     * @return bool
     */
    public function islogin(): bool {
        if (isset($this->info['id']) && $this->info['id'] != '')
            return TRUE;
        else
            return FALSE;
    }
    
    /**
     * 用户退出
     * @return bool
     */
    public function loginout(): bool {
        $this->info = "";
        cookie($this->kinfo, NULL);
        session($this->kinfo, NULL);
        session(NULL);
        unset($_COOKIE);
        return TRUE;
    }
    
    /**
     * 获取菜单
     * @return array
     */
    public function menu(): array {
        $condition['show_menu'] = 1;
        $order                  = 'order_id asc,id asc';
        $list                   = Db::name('admin_menu')
            ->field("id,title,menu_index,menu_icon,show_menu,menu_url,father_id")
            ->cache(60)
            ->where($condition)
            ->order($order)
            ->withAttr('menu_index', function ($value) {
                return strtolower($value);
            })
            ->select()
            ->toArray();
        return $this->getMenuList($list, 'father_id');
    }
    
    /**
     * 获取菜单列表
     * @param        $result
     * @param string $one_field
     * @return array
     */
    private function getMenuList($result, string $one_field = ''): array {
        if (!empty($result) && is_array($result)) {
            $result_arr = [];
            foreach ($result as $value) {
                $result_arr[$value[$one_field]][] = $value;
            }
            return $result_arr;
        } else {
            return [];
        }
    }
    
}