The key bonus from those anonymous sign-ins is that you can mark user as authenticated without creating a real user. So you can utilize all strenghts of RLS’s and then, only after, ask for the email to create a real account.
Anonymous Sign-Ins | Supabase Docs
So I want to create an anonymous account, and then I want WeWeb to raise “Authenticated” state in WeWeb.
So we actually need three new actions:
- Anonymous sign-in
const { data, error } = await supabase.auth.signInAnonymously()
- Set email to anonymous account
const { data: updateEmailData, error: updateEmailError } = await supabase.auth.updateUser({
email: 'valid.email@supabase.io',
})
// verify the user's email by clicking on the email change link
// or entering the 6-digit OTP sent to the email address
// once the user has been verified, update the password
const { data: updatePasswordData, error: updatePasswordError } = await supabase.auth.updateUser({
password: 'password',
})
- Link anonymous account to existing
// 1. Sign in anonymously (assuming the user is already signed in anonymously)
const { data: anonData, error: anonError } = await supabase.auth.getSession()
// 2. Attempt to update the user with the existing email
const { data: updateData, error: updateError } = await supabase.auth.updateUser({
email: 'valid.email@supabase.io',
})
// 3. Handle the error (since the email belongs to an existing user)
if (updateError) {
console.log('This email belongs to an existing user. Please sign in to that account.')
// 4. Sign in to the existing account
const {
data: { user: existingUser },
error: signInError,
} = await supabase.auth.signInWithPassword({
email: 'valid.email@supabase.io',
password: 'user_password',
})
if (existingUser) {
// 5. Reassign entities tied to the anonymous user
// This step will vary based on your specific use case and data model
const { data: reassignData, error: reassignError } = await supabase
.from('your_table')
.update({ user_id: existingUser.id })
.eq('user_id', anonData.session.user.id)
// 6. Implement your chosen conflict resolution strategy
// This could involve merging data, overwriting, or other custom logic
await resolveDataConflicts(anonData.session.user.id, existingUser.id)
}
}
// Helper function to resolve data conflicts (implement based on your strategy)
async function resolveDataConflicts(anonymousUserId, existingUserId) {
// Implement your conflict resolution logic here
// This could involve ignoring the anonymous user's metadata, overwriting the existing user's metadata, or merging the data of both the anonymous and existing user.
}
And then I can implement some purge function in Supabase to clean those anonymous data.