up
This commit is contained in:
@@ -1,29 +1,60 @@
|
|||||||
html
|
|
||||||
<template>
|
<template>
|
||||||
<div>
|
<div v-if="!accessToken">
|
||||||
<h1>Login with GitHub</h1>
|
<button @click="loginWithGitHub">Login with GitHub</button>
|
||||||
<button @click="login">Login with GitHub</button>
|
</div>
|
||||||
|
<div v-else>
|
||||||
|
<p>Access Token: {{ accessToken }}</p>
|
||||||
|
<button @click="logout">Logout</button>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup>
|
<script>
|
||||||
import { ref } from 'vue';
|
import { reactive } from 'vue';
|
||||||
|
|
||||||
const login = async () => {
|
export default {
|
||||||
const client_id = '9f75836d51c1cb447fa5';//process.env.VUE_APP_GITHUB_CLIENT_ID;
|
setup() {
|
||||||
const redirect_uri = "http://localhost:5173/login/callback";
|
const state = reactive({
|
||||||
const scope = "read:user";
|
accessToken: null,
|
||||||
const url = `https://github.com/login/oauth/authorize?client_id=${client_id}&redirect_uri=${redirect_uri}&scope=${scope}`;
|
});
|
||||||
console.log(url);
|
|
||||||
window.location.href = url;
|
const loginWithGitHub = () => {
|
||||||
|
// 基于 OAuth2 的认证流程,首先跳转到 GitHub 授权页面进行授权
|
||||||
|
window.location.href = `https://github.com/login/oauth/authorize?client_id=${import.meta.env.VUE_APP_GITHUB_CLIENT_ID}&scope=user`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCallback = async (code) => {
|
||||||
|
try {
|
||||||
|
// 请求后端接口获取 access token
|
||||||
|
const response = await fetch(`${process.env.VUE_APP_API_BASE_URL}/auth/signin/sso?code=${code}`);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(response.statusText);
|
||||||
|
}
|
||||||
|
const { accessToken } = await response.json();
|
||||||
|
state.accessToken = accessToken;
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const logout = () => {
|
||||||
|
state.accessToken = null;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 监听 URL 变化,处理从 GitHub 授权页面回调回来的 code 参数
|
||||||
|
const handleUrlChange = () => {
|
||||||
|
const urlParams = new URLSearchParams(window.location.search);
|
||||||
|
const code = urlParams.get('code');
|
||||||
|
if (code) {
|
||||||
|
handleCallback(code);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
window.addEventListener('load', handleUrlChange);
|
||||||
|
|
||||||
|
return {
|
||||||
|
accessToken: state.accessToken,
|
||||||
|
loginWithGitHub,
|
||||||
|
logout,
|
||||||
|
};
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
// export default {
|
|
||||||
// name: 'Login',
|
|
||||||
// setup() {
|
|
||||||
// return {
|
|
||||||
// login,
|
|
||||||
// };
|
|
||||||
// },
|
|
||||||
// };
|
|
||||||
</script>
|
</script>
|
||||||
Reference in New Issue
Block a user