Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

1.7 KB
Raw Blame
import { AuthProvider } from '@refinedev/core'

import { supabaseClient } from './utility'

const authProvider: AuthProvider = {
  login: async ({ email }) => {
    try {
      const { error } = await supabaseClient.auth.signInWithOtp({ email })

      if (!error) {
        alert('Check your email for the login link!')
        return {
          success: true,
        }
      }

      throw error
    } catch (e: any) {
      alert(e.message)
      return {
        success: false,
        e,
      }
    }
  },
  logout: async () => {
    const { error } = await supabaseClient.auth.signOut()

    if (error) {
      return {
        success: false,
        error,
      }
    }

    return {
      success: true,
      redirectTo: '/',
    }
  },
  onError: async (error) => {
    console.error(error)
    return { error }
  },
  check: async () => {
    try {
      const { data, error } = await supabaseClient.auth.getClaims()

      if (error || !data) {
        return {
          authenticated: false,
          error: {
            message: 'Check failed',
            name: 'Session not found',
          },
          logout: true,
          redirectTo: '/login',
        }
      }
    } catch (error: any) {
      return {
        authenticated: false,
        error: error || {
          message: 'Check failed',
          name: 'Not authenticated',
        },
        logout: true,
        redirectTo: '/login',
      }
    }

    return {
      authenticated: true,
    }
  },
  getIdentity: async () => {
    const { data } = await supabaseClient.auth.getUser()

    if (data?.user) {
      return {
        ...data.user,
        name: data.user.email,
      }
    }

    return null
  },
}

export default authProvider