🐛 Refresh token won't implement

This commit is contained in:
LittleSheep 2024-08-13 01:08:32 +08:00
parent 14f2bc0ee6
commit 542f81d9c2
5 changed files with 60 additions and 28 deletions

View File

@ -87,6 +87,8 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { solarFetch } from "~/utils/request"
const config = useRuntimeConfig() const config = useRuntimeConfig()
const error = ref<string | null>(null) const error = ref<string | null>(null)
@ -123,15 +125,12 @@ async function readTickets({ page, itemsPerPage }: { page?: number; itemsPerPage
if (page) pagination.tickets.page = page if (page) pagination.tickets.page = page
reverting.sessions = true reverting.sessions = true
const res = await fetch( const res = await solarFetch(
`${config.public.solarNetworkApi}/cgi/auth/users/me/tickets?` + "/cgi/auth/users/me/tickets?" +
new URLSearchParams({ new URLSearchParams({
take: pagination.tickets.pageSize.toString(), take: pagination.tickets.pageSize.toString(),
offset: ((pagination.tickets.page - 1) * pagination.tickets.pageSize).toString(), offset: ((pagination.tickets.page - 1) * pagination.tickets.pageSize).toString(),
}), }),
{
headers: { Authorization: `Bearer ${useAtk().value}` },
},
) )
if (res.status !== 200) { if (res.status !== 200) {
error.value = await res.text() error.value = await res.text()
@ -148,15 +147,12 @@ async function readEvents({ page, itemsPerPage }: { page?: number; itemsPerPage?
if (page) pagination.events.page = page if (page) pagination.events.page = page
reverting.events = true reverting.events = true
const res = await fetch( const res = await solarFetch(
`${config.public.solarNetworkApi}/cgi/auth/users/me/events?` + "/cgi/auth/users/me/events?" +
new URLSearchParams({ new URLSearchParams({
take: pagination.events.pageSize.toString(), take: pagination.events.pageSize.toString(),
offset: ((pagination.events.page - 1) * pagination.events.pageSize).toString(), offset: ((pagination.events.page - 1) * pagination.events.pageSize).toString(),
}), }),
{
headers: { Authorization: `Bearer ${useAtk().value}` },
},
) )
if (res.status !== 200) { if (res.status !== 200) {
error.value = await res.text() error.value = await res.text()
@ -172,9 +168,8 @@ Promise.all([readTickets({}), readEvents({})])
async function killTicket(item: any) { async function killTicket(item: any) {
reverting.sessions = true reverting.sessions = true
const res = await fetch(`${config.public.solarNetworkApi}/cgi/auth/users/me/tickets/${item.id}`, { const res = await solarFetch(`/cgi/auth/users/me/tickets/${item.id}`, {
method: "DELETE", method: "DELETE",
headers: { Authorization: `Bearer ${useAtk().value}` },
}) })
if (res.status !== 200) { if (res.status !== 200) {
error.value = await res.text() error.value = await res.text()

View File

@ -16,7 +16,6 @@
<script setup lang="ts"> <script setup lang="ts">
import { onMounted, ref } from "vue" import { onMounted, ref } from "vue"
import { useRoute, useRouter } from "vue-router" import { useRoute, useRouter } from "vue-router"
import { setTokenSet } from "~/stores/userinfo"
const config = useRuntimeConfig() const config = useRuntimeConfig()
@ -53,7 +52,7 @@ async function getToken(tk: string) {
throw new Error(err) throw new Error(err)
} else { } else {
const out = await res.json() const out = await res.json()
setTokenSet(out["access_token"], out["refresh_token"]) auth.setTokenSet(out["access_token"], out["refresh_token"])
error.value = null error.value = null
} }
} }

View File

@ -69,6 +69,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref } from "vue" import { ref } from "vue"
import { solarFetch } from "~/utils/request"
definePageMeta({ definePageMeta({
middleware: ["auth"], middleware: ["auth"],
@ -86,9 +87,7 @@ const metadata = ref<any>(null)
const panel = ref("confirm") const panel = ref("confirm")
async function tryAuthorize() { async function tryAuthorize() {
const res = await fetch(`${config.public.solarNetworkApi}/cgi/auth/auth/o/authorize` + window.location.search, { const res = await solarFetch(`/cgi/auth/auth/o/authorize${window.location.search}`)
headers: { Authorization: `Bearer ${useAtk().value}` },
})
if (res.status !== 200) { if (res.status !== 200) {
error.value = await res.text() error.value = await res.text()
@ -117,9 +116,8 @@ function decline() {
async function approve() { async function approve() {
loading.value = true loading.value = true
const res = await fetch(`${config.public.solarNetworkApi}/cgi/auth/auth/o/authorize` + window.location.search, { const res = await solarFetch(`/cgi/auth/auth/o/authorize${window.location.search}`, {
method: "POST", method: "POST",
headers: { Authorization: `Bearer ${useAtk().value}` },
}) })
if (res.status !== 200) { if (res.status !== 200) {

View File

@ -1,5 +1,6 @@
import { defineStore } from "pinia" import { defineStore } from "pinia"
import { ref } from "vue" import { ref } from "vue"
import { solarFetch } from "~/utils/request"
export interface Userinfo { export interface Userinfo {
isLoggedIn: boolean isLoggedIn: boolean
@ -21,11 +22,6 @@ export function useRtk() {
return useCookie("__hydrogen_rtk", { watch: "shallow" }) return useCookie("__hydrogen_rtk", { watch: "shallow" })
} }
export function setTokenSet(atk: string, rtk: string) {
useAtk().value = atk
useRtk().value = rtk
}
export function useLoggedInState() { export function useLoggedInState() {
return computed(() => useAtk().value != null) return computed(() => useAtk().value != null)
} }
@ -34,6 +30,40 @@ export const useUserinfo = defineStore("userinfo", () => {
const userinfo = ref(defaultUserinfo) const userinfo = ref(defaultUserinfo)
const isReady = ref(false) const isReady = ref(false)
const lastRefreshedAt = ref<Date | null>(null)
function setTokenSet(atk: string, rtk: string) {
lastRefreshedAt.value = new Date()
useAtk().value = atk
useRtk().value = rtk
}
async function getAtk() {
if (lastRefreshedAt.value != null && Math.floor(Math.abs(Date.now() - lastRefreshedAt.value.getTime()) / 60000) < 3) {
return useAtk().value
}
const config = useRuntimeConfig()
const res = await fetch(`${config.public.solarNetworkApi}/cgi/auth/auth/token`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
refresh_token: useRtk().value,
grant_type: "refresh_token",
}),
})
if (res.status !== 200) {
const err = await res.text()
throw new Error(err)
} else {
const out = await res.json()
console.log("[PASSPORT] Access token has been refreshed now.")
setTokenSet(out["access_token"], out["refresh_token"])
return out["access_token"]
}
}
async function readProfiles() { async function readProfiles() {
if (!useLoggedInState().value) { if (!useLoggedInState().value) {
isReady.value = true isReady.value = true
@ -41,9 +71,7 @@ export const useUserinfo = defineStore("userinfo", () => {
const config = useRuntimeConfig() const config = useRuntimeConfig()
const res = await fetch(`${config.public.solarNetworkApi}/cgi/auth/users/me`, { const res = await solarFetch("/cgi/auth/users/me")
headers: { Authorization: `Bearer ${useAtk().value}` },
})
if (res.status !== 200) { if (res.status !== 200) {
return return
@ -59,5 +87,5 @@ export const useUserinfo = defineStore("userinfo", () => {
} }
} }
return { userinfo, isReady, readProfiles } return { userinfo, lastRefreshedAt, isReady, setTokenSet, getAtk, readProfiles }
}) })

12
utils/request.ts Normal file
View File

@ -0,0 +1,12 @@
export async function solarFetch(input: string | URL | globalThis.Request, init?: RequestInit) {
const auth = useUserinfo()
const config = useRuntimeConfig()
return await fetch(`${config.public.solarNetworkApi}${input}`, {
...init,
headers: {
...init?.headers,
"Authorization": `Bearer ${await auth.getAtk()}`,
},
})
}