CasdoorCallback.vue 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <template>
  2. <h1>{{ text }}</h1>
  3. </template>
  4. <script setup lang="ts">
  5. import { ref, onMounted } from 'vue-demi'
  6. import { withBase } from 'vitepress'
  7. import { createDiscreteApi } from 'naive-ui'
  8. import { useCasdoor } from "casdoor-vue-sdk"
  9. import { getOriginalUrl } from '../../plugins/SSE/stateMap'
  10. import { setWalineUserInfoFromToken } from '../../plugins/waline'
  11. const text = ref("Callback")
  12. // const { message } = createDiscreteApi(['message'])
  13. // message.success('Login success')
  14. // message.error(`Login failed: ${err}`)
  15. onMounted(() => {
  16. const url = new URL(window.location.href)
  17. const param = url.searchParams
  18. const code = param.get('code')
  19. const state = param.get('state')
  20. console.log("code: ", code);
  21. console.log("state: ", state);
  22. const sdk = useCasdoor()
  23. if (!sdk) {
  24. return
  25. }
  26. // sdk.signin("https://raspberrypi.dev", withBase("/api/signin")).then((token => {
  27. sdk.signin("", withBase("/api/signin")).then((token => {
  28. // 登录成功
  29. console.log("Login successful.")
  30. console.log(token)
  31. // 尝试提取用户信息
  32. setWalineUserInfoFromToken(token.access_token)
  33. // 尝试跳转登录前页面
  34. const originalUrl = getOriginalUrl(state)
  35. if (originalUrl) {
  36. window.location.href = originalUrl
  37. return
  38. }
  39. // 跳转回主页
  40. window.location.href = withBase("/")
  41. })).catch(err => {
  42. console.log(err)
  43. // 登录失败,需要重新登录,跳转到登录页面
  44. const sdk = useCasdoor()
  45. let signinUrl = "/"
  46. if (sdk) {
  47. signinUrl = sdk.getSigninUrl()
  48. }
  49. window.location.href = signinUrl.replace(/^https?:\/\/[^/]+/, '')
  50. })
  51. })
  52. </script>