Skip to content

Commit f356a4a

Browse files
authored
Fix login logic (#4)
1 parent 20e9264 commit f356a4a

13 files changed

Lines changed: 84 additions & 63 deletions

File tree

src/App.vue

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
<div id="app">
33
<router-view v-slot="{ Component }">
44
<!-- keep alive源自于vue-router的缓存 -->
5-
<!-- keep alive comes from cach function from vue-router -->
5+
<!-- keep alive comes from cach function from vue-router -->
66
<keep-alive>
77
<component
88
:is="Component"

src/components/friends/list.vue

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
<infiniteScroll
33
:initial-items="items"
44
:has-more="!noMore"
5-
:margin-top="-200"
5+
:margin-top="-200"
66
@load="handleLoad"
77
>
88
<template #default="{ items }">

src/components/messages/MessageList.vue

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,13 @@
1919
</template>
2020

2121
<script setup lang="ts">
22-
import { ref, watch, nextTick, onMounted } from "vue";
22+
import { ref, watch, nextTick } from "vue";
2323
import MessageItem from "./MessageItem.vue";
2424
import { getData } from "@services/api/getData.ts";
2525
import type { PropType } from "vue";
2626
import { showMessage } from "@popup/naiveui";
2727
import InfiniteScroll from "../utils/infiniteScroll.vue";
2828
import { useI18n } from "vue-i18n";
29-
import storageManager from "@storage/index.ts";
3029
import { checkLogin } from "@services/utils.ts";
3130
import { NDivider } from "naive-ui";
3231
@@ -97,7 +96,8 @@ function handleMsgClick(message: PMessageItem) {
9796
9897
const handleLoad = async () => {
9998
if (
100-
storageManager.getObj("userInfo")?.value?.loginStatus === false &&
99+
// CheckLogin without popup for the sake of avoiding API Handling errors
100+
checkLogin(false) === false &&
101101
Category === "User"
102102
) {
103103
return;
@@ -137,7 +137,10 @@ const handleLoad = async () => {
137137
await nextTick();
138138
};
139139
140+
if (Category === "User") checkLogin();
141+
// CheckLogin with popup for the sake of leading user
140142
handleLoad();
143+
141144
watch(
142145
() => upDate,
143146
() => {
@@ -153,10 +156,6 @@ window.$Logger.logPageView({
153156
pageLink: `/${Category}/${ID}/Comments/`,
154157
timeStamp: Date.now(),
155158
});
156-
157-
onMounted(() => {
158-
if (Category === "User") checkLogin();
159-
});
160159
</script>
161160

162161
<style scoped>

src/components/utils/Header.vue

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,18 @@
33
<slot></slot>
44
<!-- @see https://icomoon.io/app/ -->
55
<div class="buttons">
6+
<div class="logout" @click="logout">
7+
<svg
8+
width="25"
9+
height="25"
10+
viewBox="0 0 32 32"
11+
xmlns="http://www.w3.org/2000/svg"
12+
>
13+
<path
14+
d="M24 20v-4h-10v-4h10v-4l6 6zM22 18v8h-10v6l-12-6v-26h22v10h-2v-8h-16l8 4v18h8v-6z"
15+
></path>
16+
</svg>
17+
</div>
618
<div v-show="!isFullScreen" class="fullScreen" @click="toggleFullScreen">
719
<svg
820
width="22"
@@ -34,10 +46,11 @@
3446
</template>
3547

3648
<script setup lang="ts">
49+
import router from "../../router/index";
3750
import { ref } from "vue";
3851
let isFullScreen = ref(false);
3952
40-
const toggleFullScreen = () => {
53+
function toggleFullScreen() {
4154
if (!document.fullscreenElement) {
4255
document.documentElement.requestFullscreen();
4356
isFullScreen.value = true;
@@ -47,19 +60,20 @@ const toggleFullScreen = () => {
4760
isFullScreen.value = false;
4861
}
4962
}
50-
};
63+
}
5164
5265
/**
5366
* 强制刷新,但是日后需要修改本地存储清理逻辑
5467
* Force refresh, but the local storage clearing logic needs to be modified in the future
5568
* @deprecated
5669
*/
57-
// function logout() {
58-
// sm.remove("userInfo");
59-
// Emitter.emit("info", "您已退出登录!", 1);
60-
// window.location.href = getPath("/@root");
61-
// window.location.reload();
62-
// }
70+
function logout() {
71+
localStorage.clear();
72+
// This is not merely to clear the storage, mabye an error happened in our storage system so the user try to logout
73+
router.push({ name: "Home" }).then(() => {
74+
window.location.reload();
75+
});
76+
}
6377
</script>
6478

6579
<style scoped>
@@ -80,7 +94,7 @@ const toggleFullScreen = () => {
8094
display: flex;
8195
align-items: center;
8296
cursor: pointer;
83-
padding-right: 8vw;
97+
padding-right: 20px;
8498
gap: 10px;
8599
}
86100

src/config/user.config.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import i18n from "@i18n/index";
2-
import Emitter from "../services/eventEmitter";
32
import storageManager from "../services/storage";
4-
import { showDialog } from "@popup/naiveui";
3+
import { showDialog, showNotification } from "@popup/naiveui";
54

65
export const settingsConfig = [
76
{
@@ -30,7 +29,10 @@ export const settingsConfig = [
3029
label: "newValue",
3130
timestamp: Date.now(),
3231
});
33-
Emitter.emit("loginRequired");
32+
showNotification({
33+
type: "info",
34+
title: i18n.global.t("login.reLoginContent"),
35+
});
3436
},
3537
});
3638
},

src/services/api/getData.ts

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import Emitter from "../eventEmitter.ts";
21
import { beforeRequest, afterRequest } from "./Interceptor.ts";
32
import sm from "@storage/index.ts";
43
import i18n from "@i18n/index.ts";
@@ -22,12 +21,11 @@ import { getPath } from "../utils.ts";
2221
// eslint-disable-next-line max-lines-per-function
2322
export async function getData(path: string, body: unknown) {
2423
const userInfo = sm.getObj("userAuthInfo");
25-
if (userInfo.status === "empty" || userInfo.status === "expired") {
26-
Emitter.emit("loginRequired");
27-
return;
28-
}
29-
const token = userInfo.value.token;
30-
const authCode = userInfo.value.authCode;
24+
const token = userInfo.value?.token;
25+
const authCode = userInfo.value?.authCode;
26+
// If token || authcode is null, it means a there's a problem with our code logic
27+
// Mabe the anonymous token storage or local storage or authentication (CheckLogin) has a problem
28+
// 可能是匿名Token的存储或者本地存储或者鉴权(CheckLogin)出了问题
3129
const beforeRes = beforeRequest(path);
3230
if (beforeRes.continue === false) {
3331
return beforeRes.data;
@@ -79,13 +77,8 @@ export async function getData(path: string, body: unknown) {
7977
/**
8078
* 在首页进行登录操作。 Login operation on the Home.vue
8179
* 注意,不进行本操作无法访问其他任何API接口(除非有本地缓存),所以在处理任何其他API时都要处理是否登录的错误(不等同于没有“类似管理行为”的权限)
82-
* 可以使用EventEmitter来发布LoginRequired事件
83-
* 订阅laoding、error、success事件,并管理用户登录状态存储。使用`window.$message`显示消息。
84-
*
8580
* Note that without performing this operation, you cannot access any other API interfaces (unless there is local cache).
8681
* Therefore, when handling any other API, you should handle the error of whether the user is
87-
* Emits loading, error, and success events via `Emitter` and manages user login status in storage. Displays messages using `window.$message`.
88-
*
8982
* @param arg1 - 用户名或者API令牌,取决于IsToken。’The username or API token, depending on `is_token`.
9083
* @param arg2 - 密码或者API认证码,取决于IsToken。The password or API auth code, depending on `is_token`.
9184
* @returns 成功时返回服务器响应数据,失败时发出错误事件。A promise that resolves to the server response data if successful, or emits an error event on failure.
@@ -140,7 +133,8 @@ export async function login(
140133
});
141134
}
142135
return response.json().then((data) => {
143-
if (data.Token != null && data.AuthCode != null)
136+
// Exclude(排除) user who has authenticated successfully but still does an null-null login to get homepage data
137+
if (sm.getObj("userAuthInfo").value?.token == null) {
144138
sm.setObj(
145139
"userAuthInfo",
146140
{
@@ -149,6 +143,7 @@ export async function login(
149143
},
150144
30 * 24 * 60 * 60 * 1000,
151145
);
146+
}
152147
messageRef.destroy();
153148
return data;
154149
});

src/services/api/logWriter.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
// see repository CIVITAS-John/Quantum-Intermediates ( ask @CIVITAS-John for access )
22
// Up till now, nobody kowns whether it works, as the log-uploading API well repond with 200 nomatter what.
33

4-
54
export type LogSession = {
65
type: 0;
76
region: string;

src/services/popup/loginModel.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ export default async function showLoginModel() {
99
inset: "0",
1010
width: "100%",
1111
height: "100%",
12-
zIndex: "8000",
13-
// make sure it's on top.
12+
zIndex: "8000",
13+
// make sure it's on top.
1414
// I donnot know why it need to be as big as 8000, but it works.
1515
pointerEvents: "auto",
1616
background: "transparent",

src/services/storage/readme.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@ Storage manager(alias: sm?) uses localStorage to store small data, and indexDB t
44

55
In the future, for example, when opening messages board, we need to wait for fetching data before rendering. Instead, query in the local database and render it immediately, then compare with server response amd update.Offline pages may also be served through this middleware layer.
66

7+
Tips: when user logput, we'll use `localStorage.clear()` derectly
78

89
storageManager(被奇怪的缩写为sm)使用localStorage存小数据,(计划)indexDB缓存API,日后可能依据用户配置启用settionstoragre。
910

1011
未来 比如打开留言板,不毕等待及时数据,先从本地存储的数据库里面查询后渲染,再校验并由Vue自动最小化更新渲染(因为这些数据一般是不会变的!)这还可以支持离线页面。
12+
13+
注意:用户登出时会直接使用`localStorage.clear()`清除数据

src/services/utils.ts

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@ import {
66
differenceInHours,
77
} from "date-fns";
88
import i18n from "@i18n/index";
9-
import Emitter from "./eventEmitter";
109
import storageManager from "./storage";
1110
import { showDialog } from "@popup/naiveui";
11+
import router from "../router/index";
1212

1313
type PUser = {
1414
ID: string;
@@ -56,7 +56,7 @@ export function getUserUrl(user: PUser): string {
5656
? "/@base/assets/user/default-avatar.png"
5757
: `/@static/users/avatars/${user.ID.slice(0, 4)}/${user.ID.slice(4, 6)}/${user.ID.slice(
5858
6,
59-
8
59+
8,
6060
)}/${user.ID.slice(8, 24)}/${user.Avatar}.jpg`;
6161

6262
return getPath(url);
@@ -65,7 +65,7 @@ export function getUserUrl(user: PUser): string {
6565
export function getCoverUrl(data: PProjects): string {
6666
const url = `/@static/experiments/images/${data.ID.slice(0, 4)}/${data.ID.slice(
6767
4,
68-
6
68+
6,
6969
)}/${data.ID.slice(6, 8)}/${data.ID.slice(8, 24)}/${data.Image || 0}.jpg`;
7070
return getPath(url);
7171
}
@@ -143,7 +143,7 @@ export function decodeHrefToQueryObj(base64Input: string) {
143143
}
144144
const latin1String = atob(base64Input.replace(/DEVIDER/g, "/"));
145145
const utf8Bytes = new Uint8Array(
146-
[...latin1String].map((char) => char.charCodeAt(0))
146+
[...latin1String].map((char) => char.charCodeAt(0)),
147147
);
148148
const jsonString = new TextDecoder().decode(utf8Bytes);
149149
const result = JSON.parse(jsonString);
@@ -170,7 +170,7 @@ export function decodeHrefToQueryObj(base64Input: string) {
170170
export function formatDate(
171171
id: string,
172172
showRelative?: boolean,
173-
type?: string
173+
type?: string,
174174
): string {
175175
// 1. 提取并转换16进制时间戳
176176
// 1. Extract and convert 16-bit timestamp
@@ -205,7 +205,7 @@ export function formatDate(
205205
else if (diffDays === 1) {
206206
return `${i18n.global.t("date.yesterday") as string} ${i18n.global.d(
207207
date,
208-
"time"
208+
"time",
209209
)}`;
210210
}
211211
// 前天
@@ -261,7 +261,7 @@ export function removeToken(obj: any) {
261261
/**
262262
* Can user have access to login-restricted features
263263
* @param showLoginLeader Pupup a dialog to lead user to login
264-
* @returns
264+
* @returns
265265
*/
266266
export function checkLogin(showLoginLeader = true): boolean {
267267
if (storageManager.getObj("userInfo").value?.Nickname == null) {
@@ -271,7 +271,7 @@ export function checkLogin(showLoginLeader = true): boolean {
271271
content: i18n.global.t("login.loginContent"),
272272
positiveText: i18n.global.t("login.confirm"),
273273
onPositiveClick: async () => {
274-
Emitter.emit("loginRequired");
274+
router.push({ name: "Home" });
275275
},
276276
});
277277
return false;

0 commit comments

Comments
 (0)