userCenter.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. /**
  2. * 用户中心管理模块
  3. */
  4. // 获取用户信息
  5. async function getUserInfo() {
  6. try {
  7. // 先检查是否已登录
  8. const sessionResponse = await fetch('/api/check-session');
  9. const sessionData = await sessionResponse.json();
  10. if (!sessionData.authenticated) {
  11. // 用户未登录,不显示错误,静默返回
  12. // console.log('用户未登录或会话无效,跳过获取用户信息');
  13. return;
  14. }
  15. // 用户已登录,获取用户信息
  16. // console.log('会话有效,尝试获取用户信息...');
  17. const response = await fetch('/api/user-info');
  18. if (!response.ok) {
  19. // 检查是否是认证问题
  20. if (response.status === 401) {
  21. // console.log('会话已过期,需要重新登录');
  22. return;
  23. }
  24. throw new Error('获取用户信息失败');
  25. }
  26. const data = await response.json();
  27. // console.log('获取到用户信息:', data);
  28. // 更新顶部导航栏的用户名
  29. const currentUsername = document.getElementById('currentUsername');
  30. if (currentUsername) {
  31. currentUsername.textContent = data.username || '未知用户';
  32. }
  33. // 更新统计卡片数据
  34. const loginCountElement = document.getElementById('loginCount');
  35. if (loginCountElement) {
  36. loginCountElement.textContent = data.loginCount || '0';
  37. }
  38. const accountAgeElement = document.getElementById('accountAge');
  39. if (accountAgeElement) {
  40. accountAgeElement.textContent = data.accountAge ? `${data.accountAge}天` : '0天';
  41. }
  42. const lastLoginElement = document.getElementById('lastLogin');
  43. if (lastLoginElement) {
  44. let lastLogin = data.lastLogin || '未知';
  45. // 检查是否包含 "今天" 字样,添加样式
  46. if (lastLogin.includes('今天')) {
  47. lastLoginElement.innerHTML = `<span class="today-login">${lastLogin}</span>`;
  48. } else {
  49. lastLoginElement.textContent = lastLogin;
  50. }
  51. }
  52. } catch (error) {
  53. // console.error('获取用户信息失败:', error);
  54. // 不显示错误通知,只在控制台记录错误
  55. }
  56. }
  57. // 修改密码
  58. async function changePassword(event) {
  59. if (event) {
  60. event.preventDefault();
  61. }
  62. const form = document.getElementById('changePasswordForm');
  63. const currentPassword = form.querySelector('#ucCurrentPassword').value;
  64. const newPassword = form.querySelector('#ucNewPassword').value;
  65. const confirmPassword = form.querySelector('#ucConfirmPassword').value;
  66. // 验证表单
  67. if (!currentPassword || !newPassword || !confirmPassword) {
  68. return core.showAlert('所有字段都不能为空', 'error');
  69. }
  70. if (newPassword !== confirmPassword) {
  71. return core.showAlert('两次输入的新密码不一致', 'error');
  72. }
  73. // 密码复杂度检查
  74. if (!isPasswordComplex(newPassword)) {
  75. return core.showAlert('密码必须包含至少1个字母、1个数字和1个特殊字符,长度在8-16位之间', 'error');
  76. }
  77. // 显示加载状态
  78. const submitButton = form.querySelector('button[type="submit"]');
  79. const originalButtonText = submitButton.innerHTML;
  80. submitButton.disabled = true;
  81. submitButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 提交中...';
  82. try {
  83. const response = await fetch('/api/change-password', {
  84. method: 'POST',
  85. headers: {
  86. 'Content-Type': 'application/json'
  87. },
  88. body: JSON.stringify({
  89. currentPassword,
  90. newPassword
  91. })
  92. });
  93. // 无论成功与否,去除加载状态
  94. submitButton.disabled = false;
  95. submitButton.innerHTML = originalButtonText;
  96. if (!response.ok) {
  97. const errorData = await response.json();
  98. throw new Error(errorData.error || '修改密码失败');
  99. }
  100. // 清空表单
  101. form.reset();
  102. // 设置倒计时并显示
  103. let countDown = 5;
  104. Swal.fire({
  105. title: '密码修改成功',
  106. html: `您的密码已成功修改,系统将在 <b>${countDown}</b> 秒后自动退出,请使用新密码重新登录。`,
  107. icon: 'success',
  108. timer: countDown * 1000,
  109. timerProgressBar: true,
  110. didOpen: () => {
  111. const content = Swal.getHtmlContainer();
  112. const timerInterval = setInterval(() => {
  113. countDown--;
  114. if (content) {
  115. const b = content.querySelector('b');
  116. if (b) {
  117. b.textContent = countDown > 0 ? countDown : 0;
  118. }
  119. }
  120. if (countDown <= 0) clearInterval(timerInterval);
  121. }, 1000);
  122. },
  123. allowOutsideClick: false, // 禁止外部点击关闭
  124. showConfirmButton: true, // 重新显示确认按钮
  125. confirmButtonText: '确定' // 设置按钮文本
  126. }).then((result) => {
  127. // 当计时器结束或弹窗被关闭时 (包括点击确定按钮)
  128. if (result.dismiss === Swal.DismissReason.timer || result.isConfirmed) {
  129. // console.log('计时器结束或手动确认,执行登出');
  130. auth.logout();
  131. }
  132. });
  133. } catch (error) {
  134. // console.error('修改密码失败:', error);
  135. core.showAlert('修改密码失败: ' + error.message, 'error');
  136. }
  137. }
  138. // 验证密码复杂度
  139. function isPasswordComplex(password) {
  140. // 至少包含1个字母、1个数字和1个特殊字符,长度在8-16位之间
  141. const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[.,\-_+=()[\]{}|\\;:'"<>?/@$!%*#?&])[A-Za-z\d.,\-_+=()[\]{}|\\;:'"<>?/@$!%*#?&]{8,16}$/;
  142. return passwordRegex.test(password);
  143. }
  144. // 检查密码强度
  145. function checkUcPasswordStrength() {
  146. const password = document.getElementById('ucNewPassword').value;
  147. const strengthSpan = document.getElementById('ucPasswordStrength');
  148. const strengthBar = document.getElementById('strengthBar');
  149. if (!password) {
  150. strengthSpan.textContent = '';
  151. if (strengthBar) strengthBar.style.width = '0%';
  152. return;
  153. }
  154. let strength = 0;
  155. let strengthText = '';
  156. let strengthColor = '';
  157. let strengthWidth = '0%';
  158. // 长度检查
  159. if (password.length >= 8) strength++;
  160. if (password.length >= 12) strength++;
  161. // 包含字母
  162. if (/[A-Za-z]/.test(password)) strength++;
  163. // 包含数字
  164. if (/\d/.test(password)) strength++;
  165. // 包含特殊字符
  166. if (/[.,\-_+=()[\]{}|\\;:'"<>?/@$!%*#?&]/.test(password)) strength++;
  167. // 根据强度设置文本和颜色
  168. switch(strength) {
  169. case 0:
  170. case 1:
  171. strengthText = '密码强度:非常弱';
  172. strengthColor = '#FF4136';
  173. strengthWidth = '20%';
  174. break;
  175. case 2:
  176. strengthText = '密码强度:弱';
  177. strengthColor = '#FF851B';
  178. strengthWidth = '40%';
  179. break;
  180. case 3:
  181. strengthText = '密码强度:中';
  182. strengthColor = '#FFDC00';
  183. strengthWidth = '60%';
  184. break;
  185. case 4:
  186. strengthText = '密码强度:强';
  187. strengthColor = '#2ECC40';
  188. strengthWidth = '80%';
  189. break;
  190. case 5:
  191. strengthText = '密码强度:非常强';
  192. strengthColor = '#3D9970';
  193. strengthWidth = '100%';
  194. break;
  195. }
  196. // 用span元素包裹文本,并设置为不换行
  197. strengthSpan.innerHTML = `<span style="white-space: nowrap;">${strengthText}</span>`;
  198. strengthSpan.style.color = strengthColor;
  199. if (strengthBar) {
  200. strengthBar.style.width = strengthWidth;
  201. strengthBar.style.backgroundColor = strengthColor;
  202. }
  203. }
  204. // 切换密码可见性
  205. function togglePasswordVisibility(inputId) {
  206. const passwordInput = document.getElementById(inputId);
  207. const toggleBtn = passwordInput.nextElementSibling.querySelector('i');
  208. if (passwordInput.type === 'password') {
  209. passwordInput.type = 'text';
  210. toggleBtn.classList.remove('fa-eye');
  211. toggleBtn.classList.add('fa-eye-slash');
  212. } else {
  213. passwordInput.type = 'password';
  214. toggleBtn.classList.remove('fa-eye-slash');
  215. toggleBtn.classList.add('fa-eye');
  216. }
  217. }
  218. // 刷新用户信息
  219. function refreshUserInfo() {
  220. // 显示刷新动画
  221. Swal.fire({
  222. title: '刷新中...',
  223. html: '<i class="fas fa-sync-alt fa-spin"></i> 正在刷新用户信息',
  224. showConfirmButton: false,
  225. allowOutsideClick: false,
  226. timer: 1500
  227. });
  228. // 调用获取用户信息
  229. getUserInfo().then(() => {
  230. // 更新页面上的用户名称
  231. const usernameElement = document.getElementById('profileUsername');
  232. const currentUsername = document.getElementById('currentUsername');
  233. if (usernameElement && currentUsername) {
  234. usernameElement.textContent = currentUsername.textContent || '管理员';
  235. }
  236. // 显示成功消息
  237. Swal.fire({
  238. title: '刷新成功',
  239. icon: 'success',
  240. timer: 1500,
  241. showConfirmButton: false
  242. });
  243. }).catch(error => {
  244. Swal.fire({
  245. title: '刷新失败',
  246. text: error.message || '无法获取最新用户信息',
  247. icon: 'error',
  248. timer: 2000,
  249. showConfirmButton: false
  250. });
  251. });
  252. }
  253. // 初始化用户中心
  254. function initUserCenter() {
  255. // console.log('初始化用户中心');
  256. // 获取用户信息
  257. getUserInfo();
  258. // 为用户中心按钮添加事件
  259. const userCenterBtn = document.getElementById('userCenterBtn');
  260. if (userCenterBtn) {
  261. userCenterBtn.addEventListener('click', () => {
  262. core.showSection('user-center');
  263. });
  264. }
  265. }
  266. // 加载用户统计信息
  267. function loadUserStats() {
  268. getUserInfo();
  269. }
  270. // 导出模块
  271. const userCenter = {
  272. init: function() {
  273. // console.log('初始化用户中心模块...');
  274. // 可以在这里调用初始化逻辑,也可以延迟到需要时调用
  275. return Promise.resolve(); // 返回一个已解决的 Promise,保持与其他模块一致
  276. },
  277. getUserInfo,
  278. changePassword,
  279. checkUcPasswordStrength,
  280. initUserCenter,
  281. loadUserStats,
  282. isPasswordComplex,
  283. togglePasswordVisibility,
  284. refreshUserInfo
  285. };
  286. // 页面加载完成后初始化
  287. document.addEventListener('DOMContentLoaded', initUserCenter);
  288. // 全局公开用户中心模块
  289. window.userCenter = userCenter;