Skip to content

Commit

Permalink
feat(user):认证改为使用 token
Browse files Browse the repository at this point in the history
  • Loading branch information
li1553770945 committed Nov 9, 2024
1 parent ccd890a commit 0bbfa01
Show file tree
Hide file tree
Showing 9 changed files with 76 additions and 53 deletions.
4 changes: 2 additions & 2 deletions .env.development
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
VITE_WS_BASE_URL=ws://127.0.0.1:8000/socket
VITE_API_BASE_URL=http://127.0.0.1:8000/api
VITE_WS_BASE_URL=/socket
VITE_API_BASE_URL=/api
13 changes: 13 additions & 0 deletions components.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,31 @@ declare module '@vue/runtime-core' {
ElCard: typeof import('element-plus/es')['ElCard']
ElCol: typeof import('element-plus/es')['ElCol']
ElContainer: typeof import('element-plus/es')['ElContainer']
ElDatePicker: typeof import('element-plus/es')['ElDatePicker']
ElDialog: typeof import('element-plus/es')['ElDialog']
ElDivider: typeof import('element-plus/es')['ElDivider']
ElFooter: typeof import('element-plus/es')['ElFooter']
ElForm: typeof import('element-plus/es')['ElForm']
ElFormItem: typeof import('element-plus/es')['ElFormItem']
ElIcon: typeof import('element-plus/es')['ElIcon']
ElInput: typeof import('element-plus/es')['ElInput']
ElMain: typeof import('element-plus/es')['ElMain']
ElMenu: typeof import('element-plus/es')['ElMenu']
ElMenuItem: typeof import('element-plus/es')['ElMenuItem']
ElOption: typeof import('element-plus/es')['ElOption']
ElPagination: typeof import('element-plus/es')['ElPagination']
ElRadioButton: typeof import('element-plus/es')['ElRadioButton']
ElRadioGroup: typeof import('element-plus/es')['ElRadioGroup']
ElRate: typeof import('element-plus/es')['ElRate']
ElRow: typeof import('element-plus/es')['ElRow']
ElScrollbar: typeof import('element-plus/es')['ElScrollbar']
ElSelect: typeof import('element-plus/es')['ElSelect']
ElSkeleton: typeof import('element-plus/es')['ElSkeleton']
ElSkeletonItem: typeof import('element-plus/es')['ElSkeletonItem']
ElSubMenu: typeof import('element-plus/es')['ElSubMenu']
ElTable: typeof import('element-plus/es')['ElTable']
ElTableColumn: typeof import('element-plus/es')['ElTableColumn']
ElTag: typeof import('element-plus/es')['ElTag']
ElTimeline: typeof import('element-plus/es')['ElTimeline']
ElTimelineItem: typeof import('element-plus/es')['ElTimelineItem']
Menu: typeof import('./src/components/menu.vue')['default']
Expand Down
74 changes: 45 additions & 29 deletions src/components/menu.vue
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@
</el-container>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { ref, watch } from "vue";
import { Notebook, TopRight, User, Setting, Message, House, Star, MilkTea, Sugar, InfoFilled } from "@element-plus/icons-vue";
import { useUser } from "../store/user"
import { storeToRefs } from 'pinia'
Expand All @@ -115,7 +115,7 @@ import { ElNotification } from 'element-plus'
import { onMounted } from 'vue'
import { Github } from '@icon-park/vue-next';
const userStore = useUser()
const { isLogined, username, nickname, role } = storeToRefs(userStore)
const { token,isLogined, username, nickname, role } = storeToRefs(userStore)
const isCollapse = ref(false);
let menuWidth = ref("64");
const handleOpen = (key: string, keyPath: string[]) => {
Expand Down Expand Up @@ -147,10 +147,12 @@ const logout = () => {
message: "已成功登出",
type: 'success',
})
localStorage.removeItem("token");
isLogined.value = false;
username.value = "";
nickname.value = "";
role.value = ""
token.value = "";
}
}
Expand All @@ -165,35 +167,49 @@ const logout = () => {
)
}
onMounted(() => {
userInfoAPI().then(
(res) => {
let data = res.data;
if (data.code != 0) {
console.log("用户未登录");
} else {
data = data.data
ElNotification({
title: '用户状态恢复成功',
message: "欢迎回来," + data.nickname,
type: 'success',
})
isLogined.value = true;
username.value = data.username;
nickname.value = data.nickname;
role.value = data.role;
const fetchUserInfo = () => {
userInfoAPI().then(
(res) => {
let data = res.data;
if (data.code != 0) {
console.log("用户未登录");
} else {
data = data.data
ElNotification({
title: '获取用户信息成功',
message: "欢迎回来, " + data.nickname,
type: 'success',
})
isLogined.value = true;
username.value = data.username;
nickname.value = data.nickname;
role.value = data.role;
}
}
).catch(
err => {
ElNotification({
title: '获取用户信息请求失败',
message: err.message,
type: 'error',
})
}
)
}
}
// 在 token 改变时重新请求用户信息
watch(token, (newToken, oldToken) => {
if (newToken && newToken !== oldToken) {
fetchUserInfo();
}
).catch(
err => {
ElNotification({
title: '获取用户信息请求失败',
message: err.message,
type: 'error',
})
}
)
})
// 组件挂载时恢复用户状态
onMounted(() => {
const tokenStoreValue = localStorage.getItem("token");
if (tokenStoreValue) {
token.value = tokenStoreValue;
}
})
const openMail = () => {
Expand Down
13 changes: 4 additions & 9 deletions src/pages/login.vue
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,15 @@

<script lang="ts" setup>
import { reactive } from 'vue'
import { loginAPI } from "../request/api"
import { loginAPI,userInfoAPI } from "../request/api"
import { ElNotification } from 'element-plus'
import { useUser } from "../store/user"
import { storeToRefs } from 'pinia'
import { useRouter} from 'vue-router'
const userStore = useUser()
const router = useRouter();
const { isLogined, username, nickname,role } = storeToRefs(userStore)
const { token,isLogined, username, nickname,role } = storeToRefs(userStore)
const loginForm = reactive({
Expand All @@ -45,17 +45,12 @@ const onSubmit = () => {
})
} else {
data = data.data
token.value = data.token;
localStorage.setItem("token", data.token);
ElNotification({
title: '登录成功',
message: "欢迎回来,"+data.nickname,
type: 'success',
})
isLogined.value = true;
username.value = data.username;
nickname.value = data.nickname;
role.value = data.role;
router.back();
}
}
).catch(
Expand Down
8 changes: 4 additions & 4 deletions src/pages/projects.vue
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ class ProjectsPage {
if (data.code != 0) {
ElNotification({
title: '添加项目失败',
message: data.msg,
message: data.message,
type: 'error',
})
} else {
Expand Down Expand Up @@ -219,7 +219,7 @@ class ProjectsPage {
if (data.code != 0) {
ElNotification({
title: '获取项目数量失败',
message: data.msg,
message: data.message,
type: 'error',
})
} else {
Expand Down Expand Up @@ -251,7 +251,7 @@ class ProjectsPage {
if (data.code != 0) {
ElNotification({
title: '获取项目列表失败',
message: data.msg,
message: data.message,
type: 'error',
})
} else {
Expand Down Expand Up @@ -286,7 +286,7 @@ class ProjectsPage {
if (data.code != 0) {
ElNotification({
title: '删除失败',
message: data.msg,
message: data.message,
type: 'error',
});
} else {
Expand Down
2 changes: 1 addition & 1 deletion src/request/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export const logoutAPI = () => instance.get("/users/logout");

// post请求,有参数
export const loginAPI = (data: any) =>
instance.post("/users/login", data);
instance.post("/auth/login", data);

export const registerAPI = (data: any) =>
instance.post("/users/register", data);
Expand Down
10 changes: 4 additions & 6 deletions src/request/request.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import axios from 'axios'
const baseURL = import.meta.env.VITE_API_BASE_URL;

console.log("baseurl"+baseURL)
// 创建axios实例
const request = axios.create({
baseURL: baseURL,// 所有的请求地址前缀部分(没有后端请求不用写)
Expand All @@ -18,11 +17,10 @@ const request = axios.create({
// request拦截器
request.interceptors.request.use(
config => {
// 如果你要去localStor获取token
// let token = localStorage.getItem("x-auth-token");
// if (token) {
// config.headers = {"x-auth-token": token}
// }
let token = localStorage.getItem("token");
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config
},
error => {
Expand Down
1 change: 1 addition & 0 deletions src/store/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export const useUser = defineStore('user', {
state: () => {
return {
isLogined: false,
token:"",
username: "",
nickname: "",
role:"",
Expand Down
4 changes: 2 additions & 2 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,12 @@ export default defineConfig({
server: {
proxy: {
'/api': { // 匹配请求路径,
target: 'http://localhost:8000/', // 代理的目标地址
target: 'http://localhost:9100/', // 代理的目标地址
changeOrigin: true,
},
'/socket': { // 匹配请求路径,
ws: true,
target: 'ws://localhost:8000/', // 代理的目标地址
target: 'ws://localhost:9100/', // 代理的目标地址
changeOrigin: true,
}
}
Expand Down

0 comments on commit 0bbfa01

Please sign in to comment.