Skip to content

Commit

Permalink
add supabase auth test
Browse files Browse the repository at this point in the history
  • Loading branch information
jaredpereira committed Mar 24, 2023
1 parent c7212cd commit 6bd3b89
Show file tree
Hide file tree
Showing 4 changed files with 2,005 additions and 103 deletions.
1 change: 1 addition & 0 deletions backend/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ let router = makeRouter(Routes);
export type Bindings = {
APP_EVENT_ANALYTICS: AnalyticsEngineDataset;
FAUNA_KEY: string;
SUPABASE_API_TOKEN: string;
SPACES: DurableObjectNamespace;
USER_UPLOADS: R2Bucket;
};
Expand Down
41 changes: 35 additions & 6 deletions backend/routes/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import bcrypt from "bcryptjs";
import { ExtractResponse, makeRoute } from "backend/lib/api";
import { createSession } from "backend/fauna/resources/functions/create_new_session";
import { getIdentityByUsername } from "backend/fauna/resources/functions/get_identity_by_username";
import { createClient } from "@supabase/supabase-js";

const Errors = {
noUser: "noUser",
Expand All @@ -24,6 +25,11 @@ export const LoginRoute = makeRoute({
secret: env.FAUNA_KEY,
domain: "db.us.fauna.com",
});
const supabase = createClient(
"https://epzrqdtswyqvjtketjhe.supabase.co",
env.SUPABASE_API_TOKEN
);

let existingUser = await getIdentityByUsername(fauna, {
username: msg.username.toLowerCase(),
});
Expand All @@ -36,10 +42,26 @@ export const LoginRoute = makeRoute({
data: { success: false, error: Errors.incorrectPassword },
} as const;
let newToken = crypto.randomUUID?.();
if (!newToken)
return {
data: { success: false, error: Errors.insecureContext },
} as const;

let supabaseLogin = await supabase.auth.signInWithPassword({
email: existingUser.email,
password: msg.password,
});
if (supabaseLogin.error) {
await supabase.auth.admin.createUser({
email: existingUser.email,
password: msg.password,
email_confirm: true,
user_metadata: {
username: existingUser.username,
studio: existingUser.studio,
},
});
supabaseLogin = await supabase.auth.signInWithPassword({
email: existingUser.email,
password: msg.password,
});
}

let session = await createSession(fauna, {
username: existingUser.username,
Expand All @@ -49,10 +71,17 @@ export const LoginRoute = makeRoute({
id: newToken,
});
if (!session.success)
return { data: { success: false, error: session.error } } as const;
return {
data: { success: false, error: session.error, supabaseLogin },
} as const;

return {
data: { success: true, token: newToken, session: session.data },
data: {
success: true,
token: newToken,
session: session.data,
supabaseLogin,
},
} as const;
},
});
Loading

0 comments on commit 6bd3b89

Please sign in to comment.