feat: add token validation api and auth module

This commit is contained in:
Tim
2025-07-05 13:34:47 +08:00
parent 3568e54984
commit 6bdc32ff05
4 changed files with 42 additions and 1 deletions

View File

@@ -5,6 +5,7 @@ import './assets/global.css'
import Toast, { POSITION } from 'vue-toastification'
import 'vue-toastification/dist/index.css'
import { useToast } from 'vue-toastification'
import { checkToken, clearToken } from './utils/auth'
// Configurable API domain and port
export const API_DOMAIN = 'http://127.0.0.1'
@@ -16,3 +17,9 @@ const app = createApp(App)
app.use(router)
app.use(Toast, { position: POSITION.TOP_RIGHT })
app.mount('#app')
checkToken().then(valid => {
if (!valid) {
clearToken()
}
})

View File

@@ -0,0 +1,28 @@
import { API_BASE_URL } from '../main'
const TOKEN_KEY = 'token'
export function getToken() {
return localStorage.getItem(TOKEN_KEY)
}
export function setToken(token) {
localStorage.setItem(TOKEN_KEY, token)
}
export function clearToken() {
localStorage.removeItem(TOKEN_KEY)
}
export async function checkToken() {
const token = getToken()
if (!token) return false
try {
const res = await fetch(`${API_BASE_URL}/api/auth/check`, {
headers: { Authorization: `Bearer ${token}` }
})
return res.ok
} catch (e) {
return false
}
}

View File

@@ -56,6 +56,7 @@
<script>
import { API_BASE_URL, toast } from '../main'
import { setToken } from '../utils/auth'
export default {
name: 'LoginPageView',
data() {
@@ -77,7 +78,7 @@ export default {
this.isWaitingForLogin = false
const data = await res.json()
if (res.ok && data.token) {
localStorage.setItem('token', data.token)
setToken(data.token)
toast.success('登录成功')
this.$router.push('/')
} else {

View File

@@ -63,6 +63,11 @@ public class AuthController {
}
}
@GetMapping("/check")
public ResponseEntity<?> checkToken() {
return ResponseEntity.ok(Map.of("valid", true));
}
@Data
private static class RegisterRequest {
private String username;