This commit is contained in:
Sakurasan
2023-04-12 22:38:03 +08:00
parent 9e8c94006d
commit 8ece9bdf37
2 changed files with 46 additions and 30 deletions

View File

@@ -55,7 +55,7 @@ func main() {
}))
router.GET("/", func(ctx *gin.Context) { ctx.Writer.WriteString("hello world") })
router.GET("/auth/github", githubLoginHandler)
router.GET("/auth/github/callback", githubCallbackHandler)
router.GET("/auth/signin/sso", githubCallbackHandler)
router.Run(":8000")
}

View File

@@ -1,6 +1,6 @@
<template>
<div v-if="!accessToken">
<button @click="loginWithGitHub">Login with GitHub</button>
<button @click="">Login with GitHub</button>
</div>
<div v-else>
<p>Access Token: {{ accessToken }}</p>
@@ -13,48 +13,64 @@ import { reactive } from 'vue';
export default {
setup() {
const state = reactive({
accessToken: null,
const auth = reactive({
type: "github",
redirectUrl: null,
code: null,
state: null,
});
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`;
// Function to handle GitHub login button click
const handleGithubLogin = async () => {
try {
// Send a GET request to /auth/github to get the redirect URL
const response = await axios.get('/auth/github')
auth.redirectUrl = response.data.redirectUrl
auth.state = response.data.state
window.location.href = state.redirectUrl
} catch (error) {
console.error(error)
}
};
const handleCallback = async (code) => {
const handleCallback = async () => {
// const code = this.$route.query.code
// const status = this.$route.query.status
const urlParams = new URLSearchParams(window.location.search)
const code = urlParams.get('code')
const status = urlParams.get('state')
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;
const response = await axios.post('/auth/signin/sso', {
code,
status
})
const jwt = response.data.jwt
localStorage.setItem('jwt', jwt)
} catch (error) {
console.error(error);
if (error.response.status != 200) {
console.log('授权失败')
}
}
};
const logout = () => {
state.accessToken = null;
localStorage.setItem('jwt','');
};
// 监听 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);
// // 监听 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,
};
},
};
</script>