he wei
2025-04-03 c6a2d2debf161b987ff91c6ac9560d10fc98c54b
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
<template>
  <!-- 人脸登陆弹窗 -->
  <div>
    <video ref="video" width="480" height="320" style="display: none"></video>
    <canvas ref="canvas" width="480" height="320"></canvas>
    <p class="text">{{ faceDetect }}</p>
  </div>
</template>
<script>
    import faceManager from "./faceManager.js";
    import { uKeyLogin } from "@/api/user";
    import store from '@/store';
    import { mapState } from 'pinia';
    import useElement from '@/hooks/useElement.js';
    import { getToken, removeToken, setToken, getUname, setUname, removeUname, getUrole, setUrole, removeUrole } from '@/utils/auth';
 
    const { $loading, $confirm, $message } = useElement();
    // import const_num from "@/assets/js/const/const_num";
    // import RSA from "@/assets/js/tools/RSA";
    export default {
        props: {
            faceShow: {
                type: Boolean,
                default: false,
            },
        },
        data() {
            return {
                status: true,
                faceDetect: "请将正脸对准摄像头",
                imageBase64: "",
                newstream: "",
                intTime: null,
                postTime: null,
                setTime: null,
        redirect: undefined,
                otherQuery: {}
            };
        },
        watch: {
            $route: {
                handler: function (route) {
                    const query = route.query;
                    if (query) {
                        this.redirect = query.redirect;
                        this.otherQuery = this.getOtherQuery(query);
                    }
                },
                immediate: true
            }
        },
        computed: {
            ...mapState(store.ukey, ['isIn', 'connect', 'id']),
        },
        mounted() {
            this.faceChange();
        },
        beforeUnmount() {
            // console.log('beforeUnmount ', '=============');
 
            this.status = false;
            this.clearVideo();
        },
        methods: {
      getOtherQuery(query) {
                return Object.keys(query).reduce((acc, cur) => {
                    if (cur !== 'redirect') {
                        acc[cur] = query[cur];
                    }
                    return acc;
                }, {});
            },
            // 关闭摄像头
            clearVideo: function () {
                // 关闭定时器
                clearInterval(this.intTime);
                clearInterval(this.postTime);
                clearTimeout(this.setTime);
                // 关闭摄像头
                for (let track of this.newstream.getTracks()) {
                    track.stop();
                }
            },
            // 获取图片
            getImg: function () {
                let vm = this;
                let video = vm.$refs.video;
                let canvas = vm.$refs.canvas;
                let context = canvas.getContext("2d");
                context.drawImage(video, 0, 0, 480, 320);
                // 获取图片base64链接
                vm.imageBase64 = canvas.toDataURL("image/png");
            },
            // 人脸检测
            faceChange: function () {
                let vm = this;
                // 恢复提示语
                vm.faceDetect = "请将正脸对准摄像头";
                // vm.faceShow = true;
                if (
                    navigator.mediaDevices.getUserMedia ||
                    navigator.getUserMedia ||
                    navigator.webkitGetUserMedia ||
                    navigator.mozGetUserMedia
                ) {
                    //调用用户媒体设备, 访问摄像头
                    this.getUserMedia(
                        { video: { width: 480, height: 320 } },
                        this.success,
                        this.error
                    );
                } else {
                    alert("不支持访问用户媒体");
                }
            },
            //访问用户媒体设备的兼容方法
            getUserMedia: function (constraints, success, error) {
                if (navigator.mediaDevices.getUserMedia) {
                    //最新的标准API
                    navigator.mediaDevices
                        .getUserMedia(constraints)
                        .then(success)
                        .catch(error);
                } else if (navigator.webkitGetUserMedia) {
                    //webkit核心浏览器
                    navigator.webkitGetUserMedia(constraints, success, error);
                } else if (navigator.mozGetUserMedia) {
                    //firfox浏览器
                    navigator.mozGetUserMedia(constraints, success, error);
                } else if (navigator.getUserMedia) {
                    //旧版API
                    navigator.getUserMedia(constraints, success, error);
                }
            },
            // 成功回调
            success: function (stream) {
                let vm = this;
                //兼容webkit核心浏览器
                let CompatibleURL = window.URL || window.webkitURL;
                //将视频流设置为video元素的源
                // console.log(stream);
                // stream = stream;
                this.newstream = stream;
                //video.src = CompatibleURL.createObjectURL(stream);
                let video = this.$refs.video;
                video.srcObject = stream;
                video.play();
                this.intTime = setInterval(() => {
                    vm.getImg();
                }, 0);
                setTimeout(function () {
                    vm.facePost();
                }, 0);
            },
            error: function (error) {
                console.log(error);
                console.log(`访问用户媒体设备失败${error.name}, ${error.message}`);
            },
            // 请求后台验证人脸
            facePost: function () {
                if (!this.isIn) {
                    this.faceDetect = "请先插入ukey";
                    this.setTime = setTimeout(() => {
                        this.facePost();
                    }, 500);
                } else if (!this.imageBase64) {
                    this.faceDetect = "人脸识别中...";
                    this.setTime = setTimeout(() => {
                        this.facePost();
                    }, 500);
                } else {
                    let vm = this;
                    faceManager
                        .faceVerify('"' + vm.imageBase64 + '"', this.id)
                        .then((result) => {
                            let res = result;
                            console.log(res);
                            if (res.code === 1 && res.data) {
                                vm.faceDetect = "匹配成功";
                let user = res.data2[0];
                                setTimeout(() => {
                                    // vm.onLogin();
                                    // $message.success("登录成功");
                                    setUname(user.uname);
                                    setToken('admin');
                                    setUrole(user.urole);
                  this.$router.push({ path: this.redirect || '/', query: this.otherQuery });
                                    // this.$router.push("/home");
                                    // // // 设置用户的权限
                                    // // this.$store.dispatch("user/getPermits");
                                }, 1000);
                            } else {
                                vm.faceDetect = res.msg;
                                if (vm.status == true) {
                                    this.setTime = setTimeout(() => {
                                        this.facePost();
                                    }, 3000);
                                }
                            }
                        })
                        .catch((err) => {
                            vm.faceDetect = "网络链接失败";
                            if (vm.status == true) {
                                this.setTime = setTimeout(() => {
                                    this.facePost();
                                }, 3000);
                            }
                        });
                }
            },
            // 登陆设置sessionStorage
            onLogin: function () {
                faceManager
                    .getUserName()
                    .then((res) => {
                        let { code, data } = res;
                        if (code == 1) {
                            this.uKeyLogin(data.uname, data.usnid);
                        }
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            },
            uKeyLogin(username, password) {
                // ukey登录
                uKeyLogin(username, password, this.id, true)
                    .then((res) => {
                        console.log('res', res, '=============');
 
                        // 对结果进行处理
                        this.handleLogin(res, username);
                    })
                    .catch((error) => {
                        // 关闭等待
                        this.loading = false;
                        this.faceDetect = "网络异常";
                        this.facePost();
                    });
            },
            handleLogin(res, username) {
                let rs = res.data;
                if (rs.code == 1) {
                    this.$message.success("登录成功");
                    sessionStorage.setItem("username", username);
                    sessionStorage.setItem("userId", rs.data);
                    this.$router.push("/home");
                    // 设置用户的权限
                    this.$store.dispatch("user/getPermits");
                } else {
                    this.faceDetect = rs.msg;
                    this.facePost();
                }
            },
        },
    };
</script>
<style lang="scss" scoped>
.text {
  text-align: center;
  padding: 10px 0;
}
</style>