File size: 6,347 Bytes
8d7d15e
 
 
 
 
c16f98d
8d7d15e
c16f98d
 
 
 
 
8d7d15e
 
 
 
c16f98d
8d7d15e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c16f98d
 
8d7d15e
 
 
 
 
 
 
 
 
c16f98d
8d7d15e
 
 
 
c16f98d
8d7d15e
c16f98d
8d7d15e
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
// static/js/admin/users.js
const { createApp } = Vue;

import { authData, authMethods, authMounted } from '../auth.js';
import { appData, appMethods, appMounted } from '../store.js';
import AdminNavbar from '../components/AdminNavbar.js'; // Import the new component

const UserManagementApp = {
    components: {
        AdminNavbar // Register the component
    },
    // template: document.querySelector('#app template').innerHTML, // Removed template option
    data() {
        return {
            ...authData(),
            ...appData(),
            currentPath: window.location.pathname, // Add currentPath to data
            
            // 用户管理相关数据
            users: [],
            userSearchQuery: '',
            currentPage: 1,
            pageSize: 10,
            totalUsers: 0,
            totalPages: 0,
            userMessage: '',
            editingUser: {
                id: null,
                email: '',
                password: '',
                email_verified: false,
                is_admin: false,
                disabled: false
            },
            isSavingUser: false,
            editUserModal: null // Bootstrap Modal instance
        };
    },
    methods: {
        ...authMethods(this),
        ...appMethods(this),
        async fetchUsers() {
            this.userMessage = '加载用户中...';
            try {
                const token = localStorage.getItem('access_token');
                let url = `/api/admin/users?page=${this.currentPage}&page_size=${this.pageSize}`;
                if (this.userSearchQuery) {
                    url += `&search=${encodeURIComponent(this.userSearchQuery)}`;
                }
                const response = await fetch(url, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                const responseData = await response.json();

                if (response.ok) {
                    this.users = responseData.users;
                    this.totalUsers = responseData.total_count;
                    this.totalPages = Math.ceil(this.totalUsers / this.pageSize);
                    this.userMessage = '';
                    console.log('Fetched users successfully. totalUsers:', this.totalUsers, 'totalPages:', this.totalPages);
                } else {
                    this.userMessage = responseData.detail || '获取用户失败。';
                }
            } catch (error) {
                this.userMessage = '网络错误或服务器无响应。';
                console.error('获取用户错误:', error);
            }
        },
        changePage(pageNumber) {
            if (pageNumber > 0 && pageNumber <= this.totalPages) {
                this.currentPage = pageNumber;
                this.fetchUsers();
            }
        },
        editUser(user) {
            this.editingUser = { ...user, password: '' }; // Clear password field for security
            this.editUserModal.show();
        },
        async saveUserChanges() {
            this.isSavingUser = true;
            this.userMessage = '';
            try {
                const token = localStorage.getItem('access_token');
                const updatePayload = {
                    email: this.editingUser.email,
                    email_verified: this.editingUser.email_verified,
                    is_admin: this.editingUser.is_admin,
                    disabled: this.editingUser.disabled
                };
                if (this.editingUser.password) {
                    updatePayload.password = this.editingUser.password;
                }

                const response = await fetch(`/api/admin/users/${this.editingUser.id}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(updatePayload)
                });
                const data = await response.json();

                if (response.ok) {
                    this.userMessage = '用户更新成功!';
                    this.fetchUsers(); // Refresh user list
                    this.editUserModal.hide();
                } else {
                    this.userMessage = data.detail || '用户更新失败。';
                }
            } catch (error) {
                this.userMessage = '网络错误或服务器无响应。';
                console.error('更新用户错误:', error);
            } finally {
                this.isSavingUser = false;
            }
        },
        async deleteUser(userId) {
            if (!confirm('确定要删除此用户吗?此操作不可逆!')) {
                return;
            }
            this.userMessage = '删除用户中...';
            try {
                const token = localStorage.getItem('access_token');
                const response = await fetch(`/api/admin/users/${userId}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (response.ok) {
                    this.userMessage = '用户删除成功!';
                    this.fetchUsers(); // Refresh user list
                } else {
                    const data = await response.json();
                    this.userMessage = data.detail || '用户删除失败。';
                }
            } catch (error) {
                this.userMessage = '网络错误或服务器无响应。';
                console.error('删除用户错误:', error);
            }
        },
        handleShowChangePasswordModal() {
            this.showChangePasswordModal = true;
        }
    },
    mounted() {
        authMounted(this);
        appMounted(this);
        console.log('User management app mounted!');

        this.editUserModal = new bootstrap.Modal(document.getElementById('editUserModal'));
        this.fetchUsers(); // Fetch users on page load

    },
    watch: {
        // No specific watchers needed for this standalone page yet
    }
};

createApp(UserManagementApp).mount('#app');
console.log('User management Vue app successfully mounted to #app element.');