supabase-node-kit
Version:
A backend utility package for Supabase authentication and database functionality.
339 lines (335 loc) • 11.3 kB
JavaScript
;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// src/index.ts
var index_exports = {};
__export(index_exports, {
authAdminService: () => authAdminService,
authService: () => authService,
dbService: () => dbService,
supabaseAdmin: () => supabaseAdmin,
supabaseClient: () => supabaseClient
});
module.exports = __toCommonJS(index_exports);
// src/config/supabaseClient.ts
var import_supabase_js = require("@supabase/supabase-js");
var SUPABASE_URL = process.env.NEXT_PUBLIC_SUPABASE_URL || process.env.SUPABASE_URL || "";
var SUPABASE_ANON_KEY = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || process.env.SUPABASE_ANON_KEY || "";
var SUPABASE_SERVICE_ROLE_KEY = process.env.SUPABASE_SERVICE_ROLE_KEY || "";
var isServerSide = typeof window === "undefined";
if (!SUPABASE_URL) {
throw new Error("Supabase URL is missing");
}
var supabaseClient = (0, import_supabase_js.createClient)(SUPABASE_URL, SUPABASE_ANON_KEY, {
auth: { persistSession: true }
});
var supabaseAdmin = isServerSide ? (0, import_supabase_js.createClient)(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY, {
auth: { persistSession: false }
}) : null;
// src/auth/authService.ts
var authService = {
/**
* Authenticates a user with email and password
* @param email - User's email address
* @param password - User's password
* @returns Promise containing the sign in response
* @example
* const { data, error } = await authService.signIn('user@example.com', 'password123')
*/
signIn(email, password) {
return __async(this, null, function* () {
return yield supabaseClient.auth.signInWithPassword({ email, password });
});
},
/**
* Signs out the currently authenticated user
* @returns Promise containing the sign out response
* @example
* await authService.signOutCurrentUser()
*/
signOutCurrentUser() {
return __async(this, null, function* () {
return yield supabaseClient.auth.signOut();
});
},
/**
* Retrieves the currently authenticated user's details
* @returns Promise containing the current user data
* @example
* const { data: { user }, error } = await authService.getCurrentUser()
*/
getCurrentUser() {
return __async(this, null, function* () {
return yield supabaseClient.auth.getUser();
});
},
signUp(email, password) {
return __async(this, null, function* () {
const { data: existingUser } = yield supabaseClient.from("users").select().eq("email", email).single();
if (existingUser) {
throw new Error("User with this email already exists");
}
return yield supabaseClient.auth.signUp({
email,
password,
options: {
emailRedirectTo: `${window.location.origin}/auth/callback`
}
});
});
},
/**
* Signs in with a third-party provider
* @param provider - The authentication provider (google, github, etc.)
* @returns Promise containing the sign in response
* @example
* await authService.signInWithProvider('google')
*/
signInWithProvider(provider) {
return __async(this, null, function* () {
return yield supabaseClient.auth.signInWithOAuth({
provider,
options: {
redirectTo: `${window.location.origin}/auth/callback`,
scopes: "email profile"
}
});
});
},
/**
* Sends a password reset email
* @param email - User's email address
* @returns Promise containing the reset response
* @example
* const { data, error } = await authService.resetPassword('user@example.com')
*/
resetPassword(email) {
return __async(this, null, function* () {
return yield supabaseClient.auth.resetPasswordForEmail(email, {
redirectTo: `${window.location.origin}/auth/reset-password`
});
});
},
/**
* Updates user's password
* @param newPassword - New password
* @returns Promise containing the update response
* @example
* const { data, error } = await authService.updatePassword('newPassword123')
*/
updatePassword(newPassword) {
return __async(this, null, function* () {
return yield supabaseClient.auth.updateUser({
password: newPassword
});
});
}
};
var authAdminService = {
/**
* Creates a new user account (Server-side only)
* @param email - New user's email address
* @param password - New user's password
* @returns Promise containing the created user data
* @throws Error if called from client-side
* @example
* // Only in API routes or server-side code
* const { data, error } = await authAdminService.createUser('newuser@example.com', 'password123')
*/
createUser(email, password) {
return __async(this, null, function* () {
if (!supabaseAdmin) {
throw new Error("Admin operations can only be performed server-side");
}
return yield supabaseAdmin.auth.admin.createUser({
email,
password,
email_confirm: true
});
});
},
/**
* Deletes a user account by ID (Server-side only)
* @param userId - The UUID of the user to delete
* @returns Promise containing the deletion response
* @throws Error if called from client-side
* @example
* // Only in API routes or server-side code
* await authAdminService.deleteUser('user-uuid-here')
*/
deleteUser(userId) {
return __async(this, null, function* () {
if (!supabaseAdmin) {
throw new Error("Admin operations can only be performed server-side");
}
return yield supabaseAdmin.auth.admin.deleteUser(userId);
});
},
/**
* Retrieves user details by ID (Server-side only)
* @param userId - The UUID of the user to fetch
* @returns Promise containing the user data
* @throws Error if called from client-side
* @example
* // Only in API routes or server-side code
* const { data: { user }, error } = await authAdminService.getUserById('user-uuid-here')
*/
getUserById(userId) {
return __async(this, null, function* () {
if (!supabaseAdmin) {
throw new Error("Admin operations can only be performed server-side");
}
return yield supabaseAdmin.auth.admin.getUserById(userId);
});
},
/**
* Forces sign out for a specific user (Server-side only)
* @param userId - The UUID of the user to sign out
* @returns Promise containing the sign out response
* @throws Error if called from client-side
* @example
* // Only in API routes or server-side code
* await authAdminService.signOutUser('user-uuid-here')
*/
signOutUser(userId) {
return __async(this, null, function* () {
if (!supabaseAdmin) {
throw new Error("Admin operations can only be performed server-side");
}
return yield supabaseAdmin.auth.admin.signOut(userId);
});
},
checkUserExists(email) {
return __async(this, null, function* () {
if (!supabaseAdmin) {
throw new Error("Admin operations can only be performed server-side");
}
const { data, error } = yield supabaseAdmin.from("users").select("id").eq("email", email).single();
return { exists: !!data, error };
});
},
/**
* Updates user's email verification status (Server-side only)
* @param userId - The UUID of the user
* @param verified - Boolean indicating verification status
* @throws Error if called from client-side
* @example
* await authAdminService.updateEmailVerification('user-uuid', true)
*/
updateEmailVerification(userId, verified) {
return __async(this, null, function* () {
if (!supabaseAdmin) {
throw new Error("Admin operations can only be performed server-side");
}
return yield supabaseAdmin.auth.admin.updateUserById(userId, {
email_confirm: verified
});
});
},
/**
* Initialize auth session from existing session data
* @returns Promise containing the session data
* @example
* const { data: { session }, error } = await authService.initializeSession()
*/
initializeSession() {
return __async(this, null, function* () {
return yield supabaseClient.auth.getSession();
});
},
/**
* Set up an auth state change listener
* @param callback - Function to handle auth state changes
* @returns Cleanup function to remove the listener
* @example
* const unsubscribe = authService.onAuthStateChange((event, session) => {
* console.log('Auth event:', event, session)
* })
*/
onAuthStateChange(callback) {
return supabaseClient.auth.onAuthStateChange(callback);
}
};
// src/db/dbservice.ts
var getClient = (useAdmin = false) => {
if (useAdmin && !supabaseAdmin) {
throw new Error("Admin operations can only be performed server-side");
}
return useAdmin ? supabaseAdmin : supabaseClient;
};
var dbService = {
getAll(table, useAdmin = false) {
return __async(this, null, function* () {
const client = getClient(useAdmin);
return yield client.from(table).select("*");
});
},
getById(table, id, useAdmin = false) {
return __async(this, null, function* () {
const client = getClient(useAdmin);
return yield client.from(table).select("*").eq("id", id).single();
});
},
insert(table, values, useAdmin = false) {
return __async(this, null, function* () {
const client = getClient(useAdmin);
return yield client.from(table).insert(values);
});
},
update(table, id, values, useAdmin = false) {
return __async(this, null, function* () {
const client = getClient(useAdmin);
return yield client.from(table).update(values).eq("id", id);
});
},
remove(table, id, useAdmin = false) {
return __async(this, null, function* () {
const client = getClient(useAdmin);
return yield client.from(table).delete().eq("id", id);
});
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
authAdminService,
authService,
dbService,
supabaseAdmin,
supabaseClient
});
//# sourceMappingURL=index.js.map