feat: Add better-auth Drizzle schema

This commit introduces the Drizzle ORM schema for the `better-auth`
library. This includes tables for users, sessions, accounts,
verification, organizations, members, invitations, and passkeys, along
with their respective relations.

This schema provides the foundational database structure for user
authentication and authorization within the application, enabling
features like passkey sign-in, organization management, and invitation
handling.
This commit is contained in:
bananabas 2026-04-13 18:28:47 +01:00
parent 516033d0c5
commit f3a304d613
3 changed files with 367 additions and 172 deletions

216
apps/api/auth-schema.ts Normal file
View file

@ -0,0 +1,216 @@
import { relations } from "drizzle-orm";
import {
pgTable,
text,
timestamp,
boolean,
integer,
index,
uniqueIndex,
} from "drizzle-orm/pg-core";
export const user = pgTable("user", {
id: text("id").primaryKey(),
name: text("name").notNull(),
email: text("email").notNull().unique(),
emailVerified: boolean("email_verified").default(false).notNull(),
image: text("image"),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at")
.defaultNow()
.$onUpdate(() => /* @__PURE__ */ new Date())
.notNull(),
});
export const session = pgTable(
"session",
{
id: text("id").primaryKey(),
expiresAt: timestamp("expires_at").notNull(),
token: text("token").notNull().unique(),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at")
.$onUpdate(() => /* @__PURE__ */ new Date())
.notNull(),
ipAddress: text("ip_address"),
userAgent: text("user_agent"),
userId: text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
activeOrganizationId: text("active_organization_id"),
},
(table) => [index("session_userId_idx").on(table.userId)],
);
export const account = pgTable(
"account",
{
id: text("id").primaryKey(),
accountId: text("account_id").notNull(),
providerId: text("provider_id").notNull(),
userId: text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
accessToken: text("access_token"),
refreshToken: text("refresh_token"),
idToken: text("id_token"),
accessTokenExpiresAt: timestamp("access_token_expires_at"),
refreshTokenExpiresAt: timestamp("refresh_token_expires_at"),
scope: text("scope"),
password: text("password"),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at")
.$onUpdate(() => /* @__PURE__ */ new Date())
.notNull(),
},
(table) => [index("account_userId_idx").on(table.userId)],
);
export const verification = pgTable(
"verification",
{
id: text("id").primaryKey(),
identifier: text("identifier").notNull(),
value: text("value").notNull(),
expiresAt: timestamp("expires_at").notNull(),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at")
.defaultNow()
.$onUpdate(() => /* @__PURE__ */ new Date())
.notNull(),
},
(table) => [index("verification_identifier_idx").on(table.identifier)],
);
export const organization = pgTable(
"organization",
{
id: text("id").primaryKey(),
name: text("name").notNull(),
slug: text("slug").notNull().unique(),
logo: text("logo"),
createdAt: timestamp("created_at").notNull(),
metadata: text("metadata"),
},
(table) => [uniqueIndex("organization_slug_uidx").on(table.slug)],
);
export const member = pgTable(
"member",
{
id: text("id").primaryKey(),
organizationId: text("organization_id")
.notNull()
.references(() => organization.id, { onDelete: "cascade" }),
userId: text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
role: text("role").default("member").notNull(),
createdAt: timestamp("created_at").notNull(),
},
(table) => [
index("member_organizationId_idx").on(table.organizationId),
index("member_userId_idx").on(table.userId),
],
);
export const invitation = pgTable(
"invitation",
{
id: text("id").primaryKey(),
organizationId: text("organization_id")
.notNull()
.references(() => organization.id, { onDelete: "cascade" }),
email: text("email").notNull(),
role: text("role"),
status: text("status").default("pending").notNull(),
expiresAt: timestamp("expires_at").notNull(),
createdAt: timestamp("created_at").defaultNow().notNull(),
inviterId: text("inviter_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
},
(table) => [
index("invitation_organizationId_idx").on(table.organizationId),
index("invitation_email_idx").on(table.email),
],
);
export const passkey = pgTable(
"passkey",
{
id: text("id").primaryKey(),
name: text("name"),
publicKey: text("public_key").notNull(),
userId: text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
credentialID: text("credential_id").notNull(),
counter: integer("counter").notNull(),
deviceType: text("device_type").notNull(),
backedUp: boolean("backed_up").notNull(),
transports: text("transports"),
createdAt: timestamp("created_at"),
aaguid: text("aaguid"),
},
(table) => [
index("passkey_userId_idx").on(table.userId),
index("passkey_credentialID_idx").on(table.credentialID),
],
);
export const userRelations = relations(user, ({ many }) => ({
sessions: many(session),
accounts: many(account),
members: many(member),
invitations: many(invitation),
passkeys: many(passkey),
}));
export const sessionRelations = relations(session, ({ one }) => ({
user: one(user, {
fields: [session.userId],
references: [user.id],
}),
}));
export const accountRelations = relations(account, ({ one }) => ({
user: one(user, {
fields: [account.userId],
references: [user.id],
}),
}));
export const organizationRelations = relations(organization, ({ many }) => ({
members: many(member),
invitations: many(invitation),
}));
export const memberRelations = relations(member, ({ one }) => ({
organization: one(organization, {
fields: [member.organizationId],
references: [organization.id],
}),
user: one(user, {
fields: [member.userId],
references: [user.id],
}),
}));
export const invitationRelations = relations(invitation, ({ one }) => ({
organization: one(organization, {
fields: [invitation.organizationId],
references: [organization.id],
}),
user: one(user, {
fields: [invitation.inviterId],
references: [user.id],
}),
}));
export const passkeyRelations = relations(passkey, ({ one }) => ({
user: one(user, {
fields: [passkey.userId],
references: [user.id],
}),
}));

View file

@ -22,7 +22,6 @@ class AppState: ObservableObject {
self.keychainManager = KeychainManager.shared
self.cacheManager = CacheManager.shared
// Check if server URL was previously configured
if let urlString = UserDefaults.standard.string(forKey: "serverURL"),
let url = URL(string: urlString) {
self.serverURL = url
@ -39,16 +38,11 @@ class AppState: ObservableObject {
// MARK: - Session Management
private func checkExistingSession() async {
// Try to retrieve cached user and token
if let token = await keychainManager.retrieveToken(),
let user = await cacheManager.getCachedUser() {
self.currentUser = user
self.isAuthenticated = true
// Set up API client with token
await configureAPIClient(token: token)
// Connect WebSocket
if let household = await cacheManager.getCachedHousehold() {
self.currentHousehold = household
await webSocketManager.connect(
@ -73,7 +67,7 @@ class AppState: ObservableObject {
}
do {
let passkeyResult = try await passkeyHelper.signIn()
let passkeyResult: PasskeySignInResult = try await passkeyHelper.signIn()
let response: APIResponse<AuthResponse> = try await apiClient.post(
"auth/sign-in/passkey",
@ -120,7 +114,7 @@ class AppState: ObservableObject {
}
do {
let passkeyResult = try await passkeyHelper.register(userId: user.id, email: user.email)
let passkeyResult: PasskeyRegistrationResult = try await passkeyHelper.register(userId: user.id, email: user.email)
let response: APIResponse<SuccessResponse> = try await apiClient.post(
"auth/passkey/add-passkey",
@ -153,19 +147,13 @@ class AppState: ObservableObject {
throw AuthError.invalidResponse
}
// Save token
try await keychainManager.saveToken(data.session.token)
// Save user and household
self.currentUser = data.user
self.currentHousehold = data.household
try await cacheManager.cacheUser(data.user)
try await cacheManager.cacheHousehold(data.household)
self.isAuthenticated = true
// Connect WebSocket
await webSocketManager.connect(
householdId: data.household.id,
userId: data.user.id,
@ -194,19 +182,13 @@ class AppState: ObservableObject {
throw AuthError.invalidResponse
}
// Save token
try await keychainManager.saveToken(data.session.token)
// Save user and household
self.currentUser = data.user
self.currentHousehold = data.household
try await cacheManager.cacheUser(data.user)
try await cacheManager.cacheHousehold(data.household)
self.isAuthenticated = true
// Connect WebSocket
await webSocketManager.connect(
householdId: data.household.id,
userId: data.user.id,
@ -238,7 +220,6 @@ class AppState: ObservableObject {
self.currentHousehold = household
try await cacheManager.cacheHousehold(household)
// Connect WebSocket
if let user = currentUser {
await webSocketManager.connect(
householdId: household.id,
@ -272,7 +253,6 @@ class AppState: ObservableObject {
self.currentHousehold = household
try await cacheManager.cacheHousehold(household)
// Connect WebSocket
if let user = currentUser {
await webSocketManager.connect(
householdId: household.id,
@ -290,16 +270,9 @@ class AppState: ObservableObject {
errorMessage = nil
defer { isLoading = false }
// Disconnect WebSocket
webSocketManager.disconnect()
// Clear token
try await keychainManager.clearAll()
// Clear cache
await cacheManager.clearAll()
// Reset state
self.currentUser = nil
self.currentHousehold = nil
self.isAuthenticated = false
@ -311,8 +284,8 @@ class AppState: ObservableObject {
self.serverURL = url
self.serverURLConfigured = true
UserDefaults.standard.set(url.absoluteString, forKey: "serverURL")
// add this:
PasskeyHelper.shared.relyingPartyID = url.host ?? "localhost"
PasskeyHelper.shared.serverBaseURL = url.absoluteString.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
Task {
await apiClient.setBaseURL(url)
}
@ -373,168 +346,174 @@ enum AuthError: LocalizedError {
return message
case .apiError(let error):
return error.errorDescription
}
}
}
}
// MARK: - Passkey Helper (Stub for now)
// MARK: - base64url helpers
class PasskeyHelper: NSObject, ObservableObject, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {
static let shared = PasskeyHelper()
extension Data {
func base64URLEncoded() -> String {
base64EncodedString()
.replacingOccurrences(of: "+", with: "-")
.replacingOccurrences(of: "/", with: "_")
.replacingOccurrences(of: "=", with: "")
}
}
var relyingPartyID: String = "localhost"
// MARK: - Passkey Helper
var isAvailable: Bool {
if #available(iOS 16.0, *) {
return true
}
return false
}
class PasskeyHelper: NSObject, ObservableObject, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {
static let shared = PasskeyHelper()
private var authContinuation: CheckedContinuation<ASAuthorizationPlatformPublicKeyCredentialAssertion, Error>?
private var regContinuation: CheckedContinuation<ASAuthorizationPlatformPublicKeyCredentialRegistration, Error>?
var relyingPartyID: String = "localhost"
var serverBaseURL: String = "http://localhost:3001"
// MARK: - Sign In
var isAvailable: Bool {
if #available(iOS 16.0, *) { return true }
return false
}
func signIn() async throws -> PasskeyResult {
guard #available(iOS 16.0, *) else { throw PasskeyError.notAvailable }
private var authContinuation: CheckedContinuation<ASAuthorizationPlatformPublicKeyCredentialAssertion, Error>?
private var regContinuation: CheckedContinuation<ASAuthorizationPlatformPublicKeyCredentialRegistration, Error>?
// fetch challenge from server
let challenge = try await fetchSignInChallenge()
func signIn() async throws -> PasskeySignInResult {
guard #available(iOS 16.0, *) else { throw PasskeyError.notAvailable }
let options = try await fetchOptions(path: "generate-authentication-options")
let challengeData: Data = {
var b64 = options.challenge.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
let rem = b64.count % 4; if rem != 0 { b64 += String(repeating: "=", count: 4 - rem) }
return Data(base64Encoded: b64) ?? Data()
}()
let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: relyingPartyID)
let request = provider.createCredentialAssertionRequest(challenge: challengeData)
let assertion = try await withCheckedThrowingContinuation { continuation in
self.authContinuation = continuation
let controller = ASAuthorizationController(authorizationRequests: [request])
controller.delegate = self
controller.presentationContextProvider = self
controller.performRequests()
}
return PasskeySignInResult(
id: assertion.credentialID.base64URLEncoded(),
rawId: assertion.credentialID.base64URLEncoded(),
response: AssertionResponse(
clientDataJSON: assertion.rawClientDataJSON.base64URLEncoded(),
authenticatorData: assertion.rawAuthenticatorData.base64URLEncoded(),
signature: assertion.signature.base64URLEncoded(),
userHandle: assertion.userID?.base64URLEncoded()
),
type: "public-key"
)
}
let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: relyingPartyID)
let request = provider.createCredentialAssertionRequest(challenge: challenge)
func register(userId: String, email: String) async throws -> PasskeyRegistrationResult {
guard #available(iOS 16.0, *) else { throw PasskeyError.notAvailable }
let options = try await fetchOptions(path: "generate-registration-options")
let challengeData: Data = {
var b64 = options.challenge.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
let rem = b64.count % 4; if rem != 0 { b64 += String(repeating: "=", count: 4 - rem) }
return Data(base64Encoded: b64) ?? Data()
}()
let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: relyingPartyID)
let request = provider.createCredentialRegistrationRequest(
challenge: challengeData,
name: email,
userID: Data(userId.utf8)
)
let registration = try await withCheckedThrowingContinuation { continuation in
self.regContinuation = continuation
let controller = ASAuthorizationController(authorizationRequests: [request])
controller.delegate = self
controller.presentationContextProvider = self
controller.performRequests()
}
return PasskeyRegistrationResult(
id: registration.credentialID.base64URLEncoded(),
rawId: registration.credentialID.base64URLEncoded(),
response: AttestationResponse(
clientDataJSON: registration.rawClientDataJSON.base64URLEncoded(),
attestationObject: registration.rawAttestationObject?.base64URLEncoded() ?? ""
),
type: "public-key"
)
}
let assertion = try await withCheckedThrowingContinuation { continuation in
self.authContinuation = continuation
let controller = ASAuthorizationController(authorizationRequests: [request])
controller.delegate = self
controller.presentationContextProvider = self
controller.performRequests()
}
private func fetchOptions(path: String) async throws -> WebAuthnOptionsResponse {
let url = URL(string: "\(serverBaseURL)/api/auth/passkey/\(path)")!
var req = URLRequest(url: url)
req.httpMethod = "GET"
let (data, _) = try await URLSession.shared.data(for: req)
return try JSONDecoder().decode(WebAuthnOptionsResponse.self, from: data)
}
return PasskeyResult(
credentialId: assertion.credentialID.base64URLEncoded(),
authenticatorData: assertion.rawAuthenticatorData.base64URLEncoded(),
clientDataJSON: assertion.rawClientDataJSON.base64URLEncoded(),
signature: assertion.signature.base64URLEncoded()
)
}
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
if #available(iOS 16.0, *) {
if let assertion = authorization.credential as? ASAuthorizationPlatformPublicKeyCredentialAssertion {
authContinuation?.resume(returning: assertion)
authContinuation = nil
} else if let registration = authorization.credential as? ASAuthorizationPlatformPublicKeyCredentialRegistration {
regContinuation?.resume(returning: registration)
regContinuation = nil
}
}
}
// MARK: - Register
func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
let passkeyError: PasskeyError
if let authError = error as? ASAuthorizationError {
switch authError.code {
case .canceled: passkeyError = .userCancelled
default: passkeyError = .invalidCredential
}
} else {
passkeyError = .invalidCredential
}
authContinuation?.resume(throwing: passkeyError)
authContinuation = nil
regContinuation?.resume(throwing: passkeyError)
regContinuation = nil
}
func register(userId: String, email: String) async throws -> PasskeyResult {
guard #available(iOS 16.0, *) else { throw PasskeyError.notAvailable }
func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
UIApplication.shared.connectedScenes
.compactMap { $0 as? UIWindowScene }
.flatMap { $0.windows }
.first { $0.isKeyWindow } ?? UIWindow()
}
}
let challenge = try await fetchRegisterChallenge(userId: userId)
// MARK: - Passkey Types
let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: relyingPartyID)
let request = provider.createCredentialRegistrationRequest(
challenge: challenge,
name: email,
userID: Data(userId.utf8)
)
struct WebAuthnOptionsResponse: Codable {
let challenge: String
}
let registration = try await withCheckedThrowingContinuation { continuation in
self.regContinuation = continuation
let controller = ASAuthorizationController(authorizationRequests: [request])
controller.delegate = self
controller.presentationContextProvider = self
controller.performRequests()
}
struct PasskeySignInResult: Codable {
let id: String
let rawId: String
let response: AssertionResponse
let type: String
}
return PasskeyResult(
credentialId: registration.credentialID.base64URLEncoded(),
authenticatorData: registration.rawAttestationObject?.base64URLEncoded() ?? "",
clientDataJSON: registration.rawClientDataJSON.base64URLEncoded(),
signature: ""
)
}
struct AssertionResponse: Codable {
let clientDataJSON: String
let authenticatorData: String
let signature: String
let userHandle: String?
}
// MARK: - ASAuthorizationControllerDelegate
struct PasskeyRegistrationResult: Codable {
let id: String
let rawId: String
let response: AttestationResponse
let type: String
}
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
if #available(iOS 16.0, *) {
if let assertion = authorization.credential as? ASAuthorizationPlatformPublicKeyCredentialAssertion {
authContinuation?.resume(returning: assertion)
authContinuation = nil
} else if let registration = authorization.credential as? ASAuthorizationPlatformPublicKeyCredentialRegistration {
regContinuation?.resume(returning: registration)
regContinuation = nil
}
}
}
func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
let passkeyError: PasskeyError
if let authError = error as? ASAuthorizationError {
switch authError.code {
case .canceled: passkeyError = .userCancelled
default: passkeyError = .invalidCredential
}
} else {
passkeyError = .invalidCredential
}
authContinuation?.resume(throwing: passkeyError)
authContinuation = nil
regContinuation?.resume(throwing: passkeyError)
regContinuation = nil
}
func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
UIApplication.shared.connectedScenes
.compactMap { $0 as? UIWindowScene }
.flatMap { $0.windows }
.first { $0.isKeyWindow } ?? UIWindow()
}
// MARK: - Challenge fetching
private func fetchSignInChallenge() async throws -> Data {
let url = URL(string: "https://\(relyingPartyID)/api/auth/passkey/challenge")!
let (data, _) = try await URLSession.shared.data(from: url)
let json = try JSONDecoder().decode(ChallengeResponse.self, from: data)
return Data(base64URLEncoded: json.challenge) ?? Data()
}
private func fetchRegisterChallenge(userId: String) async throws -> Data {
let url = URL(string: "https://\(relyingPartyID)/api/auth/passkey/register-challenge")!
let (data, _) = try await URLSession.shared.data(from: url)
let json = try JSONDecoder().decode(ChallengeResponse.self, from: data)
return Data(base64URLEncoded: json.challenge) ?? Data()
}
}
struct ChallengeResponse: Codable {
let challenge: String
}
// MARK: - base64url helpers
extension Data {
func base64URLEncoded() -> String {
base64EncodedString()
.replacingOccurrences(of: "+", with: "-")
.replacingOccurrences(of: "/", with: "_")
.replacingOccurrences(of: "=", with: "")
}
init?(base64URLEncoded string: String) {
var base64 = string
.replacingOccurrences(of: "-", with: "+")
.replacingOccurrences(of: "_", with: "/")
let remainder = base64.count % 4
if remainder != 0 { base64 += String(repeating: "=", count: 4 - remainder) }
self.init(base64Encoded: base64)
}
}
struct PasskeyResult: Codable {
let credentialId: String
let authenticatorData: String
let clientDataJSON: String
let signature: String
}
struct AttestationResponse: Codable {
let clientDataJSON: String
let attestationObject: String
}
enum PasskeyError: LocalizedError {
case invalidCredential, userCancelled, notAvailable
@ -542,7 +521,7 @@ enum PasskeyError: LocalizedError {
switch self {
case .invalidCredential: return "Invalid passkey credential"
case .userCancelled: return "Passkey cancelled"
case .notAvailable: return "Requires iOS 17+"
case .notAvailable: return "Passkeys require iOS 16+"
}
}
}