feat: 登录改用 JWT(access token + refresh token),不再用 cookie
Deploy / deploy (build, debian, 22) (push) Canceled after 0s
Deploy / deploy (build, debian, 22) (push) Canceled after 0s
- 登录返回 15 分钟的 access token(HS256,密钥 JWT_SECRET,未配置则每次启动随机) 和 14 天的 refresh token;请求带 Authorization: Bearer,WebSocket 用 ?token= - refresh token 只存 sha256,放在新表 auth_refresh_token(删除旧的 auth_session); POST /account/refresh 换新的 access token,退出、改密码、封号时作废 - 带了无效或过期的 token 一律 401,前端据此刷新:快过期时提前刷新、并发请求只刷新一次, 401 时刷新后重试一次,refresh token 也失效才退出登录 - 不再用 cookie,去掉 CORS credentials 和写请求的 Origin 校验 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
dde976cacb
commit
26827e31d5
21 files changed
+281
-141
No files matched your search
+2
-11
@@ -2,10 +2,9 @@
|
||||
import { dateZhCN, zhCN } from "naive-ui"
|
||||
import type { GlobalThemeOverrides } from "naive-ui"
|
||||
import Login from "./components/Login.vue"
|
||||
import { onMounted, watch } from "vue"
|
||||
import { onMounted } from "vue"
|
||||
import { Account } from "./api"
|
||||
import { authed, user } from "./store/user"
|
||||
import { STORAGE_KEY } from "./utils/const"
|
||||
import { user } from "./store/user"
|
||||
import hljs from "highlight.js/lib/core"
|
||||
|
||||
const themeOverrides: GlobalThemeOverrides = {
|
||||
@@ -28,14 +27,6 @@ onMounted(async () => {
|
||||
user.loaded = true
|
||||
}
|
||||
})
|
||||
|
||||
watch(authed, (v) => {
|
||||
if (v) {
|
||||
localStorage.setItem(STORAGE_KEY.LOGIN, "true")
|
||||
} else {
|
||||
localStorage.removeItem(STORAGE_KEY.LOGIN)
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
+32
-8
@@ -25,24 +25,46 @@ import type {
|
||||
CreationDetail,
|
||||
CreationIn,
|
||||
} from "./utils/type"
|
||||
import { BASE_URL, STORAGE_KEY } from "./utils/const"
|
||||
import { BASE_URL } from "./utils/const"
|
||||
import {
|
||||
clearTokens,
|
||||
getAccessToken,
|
||||
getRefreshToken,
|
||||
hasLogin,
|
||||
refreshAccessToken,
|
||||
setTokens,
|
||||
} from "./token"
|
||||
import { user } from "./store/user"
|
||||
|
||||
const http = axios.create({
|
||||
baseURL: BASE_URL,
|
||||
xsrfCookieName: "xsrfCookieName",
|
||||
xsrfHeaderName: "X-CSRFTOKEN",
|
||||
withCredentials: true,
|
||||
})
|
||||
|
||||
http.interceptors.request.use(async (config) => {
|
||||
const token = await getAccessToken()
|
||||
if (token) config.headers.Authorization = `Bearer ${token}`
|
||||
return config
|
||||
})
|
||||
|
||||
http.interceptors.response.use(
|
||||
(res) => {
|
||||
return res
|
||||
},
|
||||
(err) => {
|
||||
async (err) => {
|
||||
if (err.response) {
|
||||
// access token 失效(如服务端重启换了密钥):刷新一次后重试
|
||||
if (
|
||||
err.response.status === 401 &&
|
||||
hasLogin() &&
|
||||
!err.config._retried
|
||||
) {
|
||||
err.config._retried = true
|
||||
if (await refreshAccessToken()) return http(err.config)
|
||||
}
|
||||
switch (err.response.status) {
|
||||
case 401: // 未授权
|
||||
localStorage.removeItem(STORAGE_KEY.LOGIN)
|
||||
clearTokens()
|
||||
user.username = ""
|
||||
router.push("/")
|
||||
break
|
||||
case 403: // 禁止访问
|
||||
@@ -62,12 +84,14 @@ http.interceptors.response.use(
|
||||
export const Account = {
|
||||
async login(username: string, password: string) {
|
||||
const res = await http.post("/account/login", { username, password })
|
||||
setTokens(res.data)
|
||||
return res.data
|
||||
},
|
||||
|
||||
async logout() {
|
||||
const res = await http.post("/account/logout")
|
||||
return res.data
|
||||
const refresh_token = getRefreshToken()
|
||||
clearTokens()
|
||||
await http.post("/account/logout", { refresh_token })
|
||||
},
|
||||
|
||||
async getMyProfile() {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { createWebHistory, createRouter } from "vue-router"
|
||||
import { loginModal } from "./store/modal"
|
||||
|
||||
import Workspace from "./pages/Workspace.vue"
|
||||
import { STORAGE_KEY } from "./utils/const"
|
||||
import { hasLogin } from "./token"
|
||||
import { authed } from "./store/user"
|
||||
|
||||
const routes = [
|
||||
@@ -103,8 +103,7 @@ export const router = createRouter({
|
||||
})
|
||||
|
||||
router.beforeEach((to) => {
|
||||
const isLoggedIn =
|
||||
authed.value || localStorage.getItem(STORAGE_KEY.LOGIN) === "true"
|
||||
const isLoggedIn = authed.value || hasLogin()
|
||||
if (to.meta.auth && !isLoggedIn) {
|
||||
loginModal.value = true
|
||||
return false
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ref } from "vue"
|
||||
import { WS_BASE_URL } from "../utils/const"
|
||||
import { wsUrl } from "../token"
|
||||
|
||||
export interface GuidanceMessage {
|
||||
role: "user" | "assistant"
|
||||
@@ -17,6 +17,18 @@ export const initialPrompt = ref("")
|
||||
|
||||
let ws: WebSocket | null = null
|
||||
let _taskId = 0
|
||||
// 取 token 要等一下,期间又重连或关闭时作废这次连接
|
||||
let connectSeq = 0
|
||||
|
||||
async function connect(taskId: number) {
|
||||
if (ws) ws.close()
|
||||
ws = null
|
||||
const seq = ++connectSeq
|
||||
const url = await wsUrl(`/ws/guidance/${taskId}/`)
|
||||
if (seq !== connectSeq) return
|
||||
ws = new WebSocket(url)
|
||||
setupHandlers(ws)
|
||||
}
|
||||
|
||||
function setupHandlers(socket: WebSocket) {
|
||||
socket.onopen = () => {
|
||||
@@ -69,9 +81,7 @@ export function openGuidance(taskId: number, prompt: string) {
|
||||
streamingContent.value = ""
|
||||
isOpen.value = true
|
||||
|
||||
if (ws) ws.close()
|
||||
ws = new WebSocket(`${WS_BASE_URL}/ws/guidance/${taskId}/`)
|
||||
setupHandlers(ws)
|
||||
connect(taskId)
|
||||
}
|
||||
|
||||
export function sendGuidance(content: string) {
|
||||
@@ -88,14 +98,13 @@ export function stopGuidance() {
|
||||
streaming.value = false
|
||||
streamingContent.value = ""
|
||||
if (_taskId) {
|
||||
if (ws) ws.close()
|
||||
ws = new WebSocket(`${WS_BASE_URL}/ws/guidance/${_taskId}/`)
|
||||
initialPrompt.value = ""
|
||||
setupHandlers(ws)
|
||||
connect(_taskId)
|
||||
}
|
||||
}
|
||||
|
||||
export function closeGuidance() {
|
||||
connectSeq++
|
||||
if (ws) {
|
||||
ws.close()
|
||||
ws = null
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ref } from "vue"
|
||||
import { WS_BASE_URL } from "../utils/const"
|
||||
import { wsUrl } from "../token"
|
||||
import { html, css, js } from "./editors"
|
||||
|
||||
export interface PromptMessage {
|
||||
@@ -29,12 +29,18 @@ export function setOnCodeComplete(fn: typeof _onCodeComplete) {
|
||||
}
|
||||
|
||||
let ws: WebSocket | null = null
|
||||
// 取 token 要等一下,期间又连了别的题或断开时作废这次连接
|
||||
let connectSeq = 0
|
||||
|
||||
export function connectPrompt(taskId: number) {
|
||||
export async function connectPrompt(taskId: number) {
|
||||
currentTaskId.value = taskId
|
||||
if (ws) ws.close()
|
||||
ws = null
|
||||
|
||||
ws = new WebSocket(`${WS_BASE_URL}/ws/prompt/${taskId}/`)
|
||||
const seq = ++connectSeq
|
||||
const url = await wsUrl(`/ws/prompt/${taskId}/`)
|
||||
if (seq !== connectSeq) return
|
||||
ws = new WebSocket(url)
|
||||
|
||||
ws.onopen = () => {
|
||||
connected.value = true
|
||||
@@ -92,6 +98,7 @@ export function connectPrompt(taskId: number) {
|
||||
}
|
||||
|
||||
export function disconnectPrompt() {
|
||||
connectSeq++
|
||||
if (ws) {
|
||||
ws.close()
|
||||
ws = null
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import axios from "axios"
|
||||
import { BASE_URL, STORAGE_KEY, WS_BASE_URL } from "./utils/const"
|
||||
|
||||
// access token 有效期很短,快过期时提前换新的
|
||||
const REFRESH_AHEAD_MS = 30_000
|
||||
|
||||
export function setTokens(tokens: {
|
||||
access_token: string
|
||||
refresh_token?: string
|
||||
}) {
|
||||
localStorage.setItem(STORAGE_KEY.ACCESS_TOKEN, tokens.access_token)
|
||||
if (tokens.refresh_token) {
|
||||
localStorage.setItem(STORAGE_KEY.REFRESH_TOKEN, tokens.refresh_token)
|
||||
}
|
||||
}
|
||||
|
||||
export function clearTokens() {
|
||||
localStorage.removeItem(STORAGE_KEY.ACCESS_TOKEN)
|
||||
localStorage.removeItem(STORAGE_KEY.REFRESH_TOKEN)
|
||||
}
|
||||
|
||||
export const getRefreshToken = () =>
|
||||
localStorage.getItem(STORAGE_KEY.REFRESH_TOKEN)
|
||||
|
||||
export const hasLogin = () => !!getRefreshToken()
|
||||
|
||||
function expiresSoon(token: string) {
|
||||
try {
|
||||
const payload = token.split(".")[1]!.replace(/-/g, "+").replace(/_/g, "/")
|
||||
const { exp } = JSON.parse(atob(payload))
|
||||
return exp * 1000 - Date.now() < REFRESH_AHEAD_MS
|
||||
} catch {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
let refreshing: Promise<string | null> | null = null
|
||||
|
||||
// 同时有多个请求要刷新时只发一次
|
||||
export function refreshAccessToken(): Promise<string | null> {
|
||||
const refreshToken = getRefreshToken()
|
||||
if (!refreshToken) return Promise.resolve(null)
|
||||
refreshing ??= axios
|
||||
.post(`${BASE_URL}/account/refresh`, { refresh_token: refreshToken })
|
||||
.then((res) => {
|
||||
setTokens(res.data)
|
||||
return res.data.access_token as string
|
||||
})
|
||||
.catch((err) => {
|
||||
// refresh token 失效(过期、改密码、封号)才清掉;网络错误下次再试
|
||||
if (err.response?.status === 401) clearTokens()
|
||||
return null
|
||||
})
|
||||
.finally(() => {
|
||||
refreshing = null
|
||||
})
|
||||
return refreshing
|
||||
}
|
||||
|
||||
export async function getAccessToken() {
|
||||
const token = localStorage.getItem(STORAGE_KEY.ACCESS_TOKEN)
|
||||
if (token && !expiresSoon(token)) return token
|
||||
return refreshAccessToken()
|
||||
}
|
||||
|
||||
// 浏览器建 WebSocket 时不能加请求头,token 放在查询参数里
|
||||
export async function wsUrl(path: string) {
|
||||
const token = await getAccessToken()
|
||||
return `${WS_BASE_URL}${path}?token=${encodeURIComponent(token ?? "")}`
|
||||
}
|
||||
@@ -27,7 +27,8 @@ export const alertVariants = [
|
||||
]
|
||||
|
||||
export const STORAGE_KEY = {
|
||||
LOGIN: "web-isloggedin",
|
||||
ACCESS_TOKEN: "web-access-token",
|
||||
REFRESH_TOKEN: "web-refresh-token",
|
||||
HTML: "web-html",
|
||||
CSS: "web-css",
|
||||
JS: "web-js",
|
||||
|
||||
Reference in new issue
Block a user