0.0.15 • Published 1 year ago

onebapp-vue-dev v0.0.15

Weekly downloads
-
License
MIT
Repository
-
Last release
1 year ago

Example Vue src/main.ts

import { createApp } from 'vue'
import { createPinia } from 'pinia'

import App from './App.vue'
import router from './router'
import toast from 'vue-toastification'
import './assets/main.css'

import { init } from '@/app.ts'

const app = createApp(App)

app.use(createPinia())
app.use(toast, { showCloseButtonOnHover: true })
app.use(router)
app.mount('#app')

init()

Example App Setup src/app.ts:

import { getState } from './backend/api/state'
import { useRouter } from 'vue-router'
import { isString } from './utils/string/isString'
import { session } from '@/base/auth/auth.session'
import { setAuthorization, setErrorHandler } from '@/base/backend'
import { useAuthStore } from '@/base/auth/auth.store'
import { computed, ref } from 'vue'
import { request, setAfterResponseHook } from '@/base/backend/request'
import { fetchTokenByCode, fetchTokenByRefresh, getUserLogin } from '@/base/backend/api/login'
import { provideApolloClient } from '@/base/backend/apollo'
import { getBotLogin, authBotByCode } from '@/base/backend/api/bot'
import { useNotify } from '@/base/notify/useNotify'
import { ValidationError } from '@/base/backend/errors/ValidationError'

const HISTORY_BASE_URL = import.meta.env.BASE_URL
const EXCLUDE_FIRST_PARTS: string[] = []
const locationPathParts = window.location.pathname.split('/').filter((part) => part.trim() !== '')

export const AUTH_USER_REDIRECT_URI = `${window.location.origin}/login`
export const AUTH_BOT_REDIRECT_URI = `${window.location.origin}/bot`

const isDefaultUrl = [
  window.location.href.indexOf(AUTH_USER_REDIRECT_URI),
  window.location.href.indexOf(AUTH_BOT_REDIRECT_URI),
  ...EXCLUDE_FIRST_PARTS.map((part) => `${window.location.origin}/${part}`)
].every((i) => i === -1)

const hasTenantAliasInUrl = locationPathParts.length > 0 && isDefaultUrl

export const TENANT_ALIAS = hasTenantAliasInUrl ? locationPathParts[0] : undefined
export const ROUTER_WEB_HISTORY_BASE = `${HISTORY_BASE_URL}${TENANT_ALIAS ?? ''}`

export const init = () => {
  session.init()

  const last = session.getLast()

  if (isDefaultUrl && isString(TENANT_ALIAS)) {
    session.setCurrentByAlias(TENANT_ALIAS)
  }

  if (isDefaultUrl && !isString(TENANT_ALIAS) && last) {
    window.location.href = `/${last.tenant_alias}`
    return
  }

  provideApolloClient()

  const current = session.getCurrent()

  if (current == undefined) {
    useAuthStore().load()
    return
  }

  setAuthorization(current)

  setAfterResponseHook(401, (input, options) => {
    if (input.method.toLowerCase() === 'post' && input.url.includes('/token')) {
      return
    }

    const user = session.getCurrent()

    if (user == null) {
      return
    }

    return fetchTokenByRefresh(user.refresh_token)
      .then((newToken) => {
        setAuthorization(newToken)
        session.addUser(newToken)
        input.headers.set('Authorization', `Bearer ${newToken.access_token}`)

        return request(input, options)
      })
      .catch(() => {
        setAuthorization(null)
        session.removeUser(user.subject)
        window.location.href = '/'
      })
  })

  setErrorHandler((error) => {
    if (!(error instanceof ValidationError)) {
      useNotify().error(error)
    }
  })

  getState().then((state) => {
    if (state.user != null) {
      useAuthStore().login(state.user)
    } else if (current != null) {
      setAuthorization(null)
      session.setCurrentId(null)
      session.removeUser(current.subject)
    }

    useAuthStore().load()
  })
}

export const useBotLoginHandler = () => {
  const router = useRouter()
  const notify = useNotify()

  const isLoading = ref(false)
  const code = router.currentRoute.value.query.code
  const error = computed(() => router.currentRoute.value.query.error)
  const errorDesc = computed(() => router.currentRoute.value.query.error_description)

  const redirect = () => {
    isLoading.value = true
    getBotLogin(TENANT_ALIAS, AUTH_BOT_REDIRECT_URI)
      .then(({ url }) => {
        window.location.href = url
      })
      .catch((error) => {
        notify.error(error)
        isLoading.value = false
      })
  }

  if (isString(code)) {
    isLoading.value = true
    authBotByCode(code, AUTH_BOT_REDIRECT_URI)
      .then((bot) => {
        window.location.href = `/${bot.tenant_alias}`
      })
      .catch((error) => {
        notify.error(error)
        isLoading.value = false
      })
  } else if (error.value == null) {
    redirect()
  }

  return {
    isLoading,
    error,
    errorDesc
  }
}

export const useUserLoginHandler = () => {
  const router = useRouter()
  const notify = useNotify()

  const isLoading = ref(false)
  const code = router.currentRoute.value.query.code
  const error = computed(() => router.currentRoute.value.query.error)
  const errorDesc = computed(() => router.currentRoute.value.query.error_description)

  const redirect = () => {
    isLoading.value = true
    getUserLogin(TENANT_ALIAS, AUTH_USER_REDIRECT_URI)
      .then(({ url }) => {
        window.location.href = url
      })
      .catch((error) => {
        notify.error(error)
        isLoading.value = false
      })
  }

  if (isString(code)) {
    isLoading.value = true
    fetchTokenByCode(code, AUTH_USER_REDIRECT_URI)
      .then((user) => {
        session.addUser(user)
        window.location.href = `${HISTORY_BASE_URL}${user.tenant_alias}`
      })
      .catch((error) => {
        notify.error(error)
        isLoading.value = false
      })
  } else if (error.value == null) {
    redirect()
  }

  return {
    isLoading,
    error,
    errorDesc
  }
}
0.0.15

1 year ago

0.0.14

1 year ago

0.0.13

1 year ago

0.0.12

1 year ago

0.0.11

1 year ago

0.0.10

1 year ago

0.0.9

1 year ago

0.0.8

1 year ago

0.0.6

1 year ago

0.0.5

1 year ago

0.0.4

1 year ago

0.0.3

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago