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:
parent
516033d0c5
commit
f3a304d613
3 changed files with 367 additions and 172 deletions
216
apps/api/auth-schema.ts
Normal file
216
apps/api/auth-schema.ts
Normal 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],
|
||||||
|
}),
|
||||||
|
}));
|
||||||
Binary file not shown.
|
|
@ -22,7 +22,6 @@ class AppState: ObservableObject {
|
||||||
self.keychainManager = KeychainManager.shared
|
self.keychainManager = KeychainManager.shared
|
||||||
self.cacheManager = CacheManager.shared
|
self.cacheManager = CacheManager.shared
|
||||||
|
|
||||||
// Check if server URL was previously configured
|
|
||||||
if let urlString = UserDefaults.standard.string(forKey: "serverURL"),
|
if let urlString = UserDefaults.standard.string(forKey: "serverURL"),
|
||||||
let url = URL(string: urlString) {
|
let url = URL(string: urlString) {
|
||||||
self.serverURL = url
|
self.serverURL = url
|
||||||
|
|
@ -39,16 +38,11 @@ class AppState: ObservableObject {
|
||||||
// MARK: - Session Management
|
// MARK: - Session Management
|
||||||
|
|
||||||
private func checkExistingSession() async {
|
private func checkExistingSession() async {
|
||||||
// Try to retrieve cached user and token
|
|
||||||
if let token = await keychainManager.retrieveToken(),
|
if let token = await keychainManager.retrieveToken(),
|
||||||
let user = await cacheManager.getCachedUser() {
|
let user = await cacheManager.getCachedUser() {
|
||||||
self.currentUser = user
|
self.currentUser = user
|
||||||
self.isAuthenticated = true
|
self.isAuthenticated = true
|
||||||
|
|
||||||
// Set up API client with token
|
|
||||||
await configureAPIClient(token: token)
|
await configureAPIClient(token: token)
|
||||||
|
|
||||||
// Connect WebSocket
|
|
||||||
if let household = await cacheManager.getCachedHousehold() {
|
if let household = await cacheManager.getCachedHousehold() {
|
||||||
self.currentHousehold = household
|
self.currentHousehold = household
|
||||||
await webSocketManager.connect(
|
await webSocketManager.connect(
|
||||||
|
|
@ -73,7 +67,7 @@ class AppState: ObservableObject {
|
||||||
}
|
}
|
||||||
|
|
||||||
do {
|
do {
|
||||||
let passkeyResult = try await passkeyHelper.signIn()
|
let passkeyResult: PasskeySignInResult = try await passkeyHelper.signIn()
|
||||||
|
|
||||||
let response: APIResponse<AuthResponse> = try await apiClient.post(
|
let response: APIResponse<AuthResponse> = try await apiClient.post(
|
||||||
"auth/sign-in/passkey",
|
"auth/sign-in/passkey",
|
||||||
|
|
@ -120,7 +114,7 @@ class AppState: ObservableObject {
|
||||||
}
|
}
|
||||||
|
|
||||||
do {
|
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(
|
let response: APIResponse<SuccessResponse> = try await apiClient.post(
|
||||||
"auth/passkey/add-passkey",
|
"auth/passkey/add-passkey",
|
||||||
|
|
@ -153,19 +147,13 @@ class AppState: ObservableObject {
|
||||||
throw AuthError.invalidResponse
|
throw AuthError.invalidResponse
|
||||||
}
|
}
|
||||||
|
|
||||||
// Save token
|
|
||||||
try await keychainManager.saveToken(data.session.token)
|
try await keychainManager.saveToken(data.session.token)
|
||||||
|
|
||||||
// Save user and household
|
|
||||||
self.currentUser = data.user
|
self.currentUser = data.user
|
||||||
self.currentHousehold = data.household
|
self.currentHousehold = data.household
|
||||||
|
|
||||||
try await cacheManager.cacheUser(data.user)
|
try await cacheManager.cacheUser(data.user)
|
||||||
try await cacheManager.cacheHousehold(data.household)
|
try await cacheManager.cacheHousehold(data.household)
|
||||||
|
|
||||||
self.isAuthenticated = true
|
self.isAuthenticated = true
|
||||||
|
|
||||||
// Connect WebSocket
|
|
||||||
await webSocketManager.connect(
|
await webSocketManager.connect(
|
||||||
householdId: data.household.id,
|
householdId: data.household.id,
|
||||||
userId: data.user.id,
|
userId: data.user.id,
|
||||||
|
|
@ -194,19 +182,13 @@ class AppState: ObservableObject {
|
||||||
throw AuthError.invalidResponse
|
throw AuthError.invalidResponse
|
||||||
}
|
}
|
||||||
|
|
||||||
// Save token
|
|
||||||
try await keychainManager.saveToken(data.session.token)
|
try await keychainManager.saveToken(data.session.token)
|
||||||
|
|
||||||
// Save user and household
|
|
||||||
self.currentUser = data.user
|
self.currentUser = data.user
|
||||||
self.currentHousehold = data.household
|
self.currentHousehold = data.household
|
||||||
|
|
||||||
try await cacheManager.cacheUser(data.user)
|
try await cacheManager.cacheUser(data.user)
|
||||||
try await cacheManager.cacheHousehold(data.household)
|
try await cacheManager.cacheHousehold(data.household)
|
||||||
|
|
||||||
self.isAuthenticated = true
|
self.isAuthenticated = true
|
||||||
|
|
||||||
// Connect WebSocket
|
|
||||||
await webSocketManager.connect(
|
await webSocketManager.connect(
|
||||||
householdId: data.household.id,
|
householdId: data.household.id,
|
||||||
userId: data.user.id,
|
userId: data.user.id,
|
||||||
|
|
@ -238,7 +220,6 @@ class AppState: ObservableObject {
|
||||||
self.currentHousehold = household
|
self.currentHousehold = household
|
||||||
try await cacheManager.cacheHousehold(household)
|
try await cacheManager.cacheHousehold(household)
|
||||||
|
|
||||||
// Connect WebSocket
|
|
||||||
if let user = currentUser {
|
if let user = currentUser {
|
||||||
await webSocketManager.connect(
|
await webSocketManager.connect(
|
||||||
householdId: household.id,
|
householdId: household.id,
|
||||||
|
|
@ -272,7 +253,6 @@ class AppState: ObservableObject {
|
||||||
self.currentHousehold = household
|
self.currentHousehold = household
|
||||||
try await cacheManager.cacheHousehold(household)
|
try await cacheManager.cacheHousehold(household)
|
||||||
|
|
||||||
// Connect WebSocket
|
|
||||||
if let user = currentUser {
|
if let user = currentUser {
|
||||||
await webSocketManager.connect(
|
await webSocketManager.connect(
|
||||||
householdId: household.id,
|
householdId: household.id,
|
||||||
|
|
@ -290,16 +270,9 @@ class AppState: ObservableObject {
|
||||||
errorMessage = nil
|
errorMessage = nil
|
||||||
defer { isLoading = false }
|
defer { isLoading = false }
|
||||||
|
|
||||||
// Disconnect WebSocket
|
|
||||||
webSocketManager.disconnect()
|
webSocketManager.disconnect()
|
||||||
|
|
||||||
// Clear token
|
|
||||||
try await keychainManager.clearAll()
|
try await keychainManager.clearAll()
|
||||||
|
|
||||||
// Clear cache
|
|
||||||
await cacheManager.clearAll()
|
await cacheManager.clearAll()
|
||||||
|
|
||||||
// Reset state
|
|
||||||
self.currentUser = nil
|
self.currentUser = nil
|
||||||
self.currentHousehold = nil
|
self.currentHousehold = nil
|
||||||
self.isAuthenticated = false
|
self.isAuthenticated = false
|
||||||
|
|
@ -311,8 +284,8 @@ class AppState: ObservableObject {
|
||||||
self.serverURL = url
|
self.serverURL = url
|
||||||
self.serverURLConfigured = true
|
self.serverURLConfigured = true
|
||||||
UserDefaults.standard.set(url.absoluteString, forKey: "serverURL")
|
UserDefaults.standard.set(url.absoluteString, forKey: "serverURL")
|
||||||
// add this:
|
|
||||||
PasskeyHelper.shared.relyingPartyID = url.host ?? "localhost"
|
PasskeyHelper.shared.relyingPartyID = url.host ?? "localhost"
|
||||||
|
PasskeyHelper.shared.serverBaseURL = url.absoluteString.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
|
||||||
Task {
|
Task {
|
||||||
await apiClient.setBaseURL(url)
|
await apiClient.setBaseURL(url)
|
||||||
}
|
}
|
||||||
|
|
@ -373,38 +346,47 @@ enum AuthError: LocalizedError {
|
||||||
return message
|
return message
|
||||||
case .apiError(let error):
|
case .apiError(let error):
|
||||||
return error.errorDescription
|
return error.errorDescription
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Passkey Helper (Stub for now)
|
// MARK: - base64url helpers
|
||||||
|
|
||||||
class PasskeyHelper: NSObject, ObservableObject, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {
|
extension Data {
|
||||||
|
func base64URLEncoded() -> String {
|
||||||
|
base64EncodedString()
|
||||||
|
.replacingOccurrences(of: "+", with: "-")
|
||||||
|
.replacingOccurrences(of: "/", with: "_")
|
||||||
|
.replacingOccurrences(of: "=", with: "")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Passkey Helper
|
||||||
|
|
||||||
|
class PasskeyHelper: NSObject, ObservableObject, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {
|
||||||
static let shared = PasskeyHelper()
|
static let shared = PasskeyHelper()
|
||||||
|
|
||||||
var relyingPartyID: String = "localhost"
|
var relyingPartyID: String = "localhost"
|
||||||
|
var serverBaseURL: String = "http://localhost:3001"
|
||||||
|
|
||||||
var isAvailable: Bool {
|
var isAvailable: Bool {
|
||||||
if #available(iOS 16.0, *) {
|
if #available(iOS 16.0, *) { return true }
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
private var authContinuation: CheckedContinuation<ASAuthorizationPlatformPublicKeyCredentialAssertion, Error>?
|
private var authContinuation: CheckedContinuation<ASAuthorizationPlatformPublicKeyCredentialAssertion, Error>?
|
||||||
private var regContinuation: CheckedContinuation<ASAuthorizationPlatformPublicKeyCredentialRegistration, Error>?
|
private var regContinuation: CheckedContinuation<ASAuthorizationPlatformPublicKeyCredentialRegistration, Error>?
|
||||||
|
|
||||||
// MARK: - Sign In
|
func signIn() async throws -> PasskeySignInResult {
|
||||||
|
|
||||||
func signIn() async throws -> PasskeyResult {
|
|
||||||
guard #available(iOS 16.0, *) else { throw PasskeyError.notAvailable }
|
guard #available(iOS 16.0, *) else { throw PasskeyError.notAvailable }
|
||||||
|
let options = try await fetchOptions(path: "generate-authentication-options")
|
||||||
// fetch challenge from server
|
let challengeData: Data = {
|
||||||
let challenge = try await fetchSignInChallenge()
|
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 provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: relyingPartyID)
|
||||||
let request = provider.createCredentialAssertionRequest(challenge: challenge)
|
let request = provider.createCredentialAssertionRequest(challenge: challengeData)
|
||||||
|
|
||||||
let assertion = try await withCheckedThrowingContinuation { continuation in
|
let assertion = try await withCheckedThrowingContinuation { continuation in
|
||||||
self.authContinuation = continuation
|
self.authContinuation = continuation
|
||||||
let controller = ASAuthorizationController(authorizationRequests: [request])
|
let controller = ASAuthorizationController(authorizationRequests: [request])
|
||||||
|
|
@ -412,29 +394,33 @@ enum AuthError: LocalizedError {
|
||||||
controller.presentationContextProvider = self
|
controller.presentationContextProvider = self
|
||||||
controller.performRequests()
|
controller.performRequests()
|
||||||
}
|
}
|
||||||
|
return PasskeySignInResult(
|
||||||
return PasskeyResult(
|
id: assertion.credentialID.base64URLEncoded(),
|
||||||
credentialId: assertion.credentialID.base64URLEncoded(),
|
rawId: assertion.credentialID.base64URLEncoded(),
|
||||||
authenticatorData: assertion.rawAuthenticatorData.base64URLEncoded(),
|
response: AssertionResponse(
|
||||||
clientDataJSON: assertion.rawClientDataJSON.base64URLEncoded(),
|
clientDataJSON: assertion.rawClientDataJSON.base64URLEncoded(),
|
||||||
signature: assertion.signature.base64URLEncoded()
|
authenticatorData: assertion.rawAuthenticatorData.base64URLEncoded(),
|
||||||
|
signature: assertion.signature.base64URLEncoded(),
|
||||||
|
userHandle: assertion.userID?.base64URLEncoded()
|
||||||
|
),
|
||||||
|
type: "public-key"
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Register
|
func register(userId: String, email: String) async throws -> PasskeyRegistrationResult {
|
||||||
|
|
||||||
func register(userId: String, email: String) async throws -> PasskeyResult {
|
|
||||||
guard #available(iOS 16.0, *) else { throw PasskeyError.notAvailable }
|
guard #available(iOS 16.0, *) else { throw PasskeyError.notAvailable }
|
||||||
|
let options = try await fetchOptions(path: "generate-registration-options")
|
||||||
let challenge = try await fetchRegisterChallenge(userId: userId)
|
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 provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: relyingPartyID)
|
||||||
let request = provider.createCredentialRegistrationRequest(
|
let request = provider.createCredentialRegistrationRequest(
|
||||||
challenge: challenge,
|
challenge: challengeData,
|
||||||
name: email,
|
name: email,
|
||||||
userID: Data(userId.utf8)
|
userID: Data(userId.utf8)
|
||||||
)
|
)
|
||||||
|
|
||||||
let registration = try await withCheckedThrowingContinuation { continuation in
|
let registration = try await withCheckedThrowingContinuation { continuation in
|
||||||
self.regContinuation = continuation
|
self.regContinuation = continuation
|
||||||
let controller = ASAuthorizationController(authorizationRequests: [request])
|
let controller = ASAuthorizationController(authorizationRequests: [request])
|
||||||
|
|
@ -442,16 +428,24 @@ enum AuthError: LocalizedError {
|
||||||
controller.presentationContextProvider = self
|
controller.presentationContextProvider = self
|
||||||
controller.performRequests()
|
controller.performRequests()
|
||||||
}
|
}
|
||||||
|
return PasskeyRegistrationResult(
|
||||||
return PasskeyResult(
|
id: registration.credentialID.base64URLEncoded(),
|
||||||
credentialId: registration.credentialID.base64URLEncoded(),
|
rawId: registration.credentialID.base64URLEncoded(),
|
||||||
authenticatorData: registration.rawAttestationObject?.base64URLEncoded() ?? "",
|
response: AttestationResponse(
|
||||||
clientDataJSON: registration.rawClientDataJSON.base64URLEncoded(),
|
clientDataJSON: registration.rawClientDataJSON.base64URLEncoded(),
|
||||||
signature: ""
|
attestationObject: registration.rawAttestationObject?.base64URLEncoded() ?? ""
|
||||||
|
),
|
||||||
|
type: "public-key"
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - ASAuthorizationControllerDelegate
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
|
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
|
||||||
if #available(iOS 16.0, *) {
|
if #available(iOS 16.0, *) {
|
||||||
|
|
@ -487,54 +481,39 @@ enum AuthError: LocalizedError {
|
||||||
.flatMap { $0.windows }
|
.flatMap { $0.windows }
|
||||||
.first { $0.isKeyWindow } ?? UIWindow()
|
.first { $0.isKeyWindow } ?? UIWindow()
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// MARK: - Challenge fetching
|
// MARK: - Passkey Types
|
||||||
|
|
||||||
private func fetchSignInChallenge() async throws -> Data {
|
struct WebAuthnOptionsResponse: Codable {
|
||||||
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
|
let challenge: String
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - base64url helpers
|
struct PasskeySignInResult: Codable {
|
||||||
|
let id: String
|
||||||
|
let rawId: String
|
||||||
|
let response: AssertionResponse
|
||||||
|
let type: String
|
||||||
|
}
|
||||||
|
|
||||||
extension Data {
|
struct AssertionResponse: Codable {
|
||||||
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 clientDataJSON: String
|
||||||
|
let authenticatorData: String
|
||||||
let signature: String
|
let signature: String
|
||||||
}
|
let userHandle: String?
|
||||||
|
}
|
||||||
|
|
||||||
|
struct PasskeyRegistrationResult: Codable {
|
||||||
|
let id: String
|
||||||
|
let rawId: String
|
||||||
|
let response: AttestationResponse
|
||||||
|
let type: String
|
||||||
|
}
|
||||||
|
|
||||||
|
struct AttestationResponse: Codable {
|
||||||
|
let clientDataJSON: String
|
||||||
|
let attestationObject: String
|
||||||
|
}
|
||||||
|
|
||||||
enum PasskeyError: LocalizedError {
|
enum PasskeyError: LocalizedError {
|
||||||
case invalidCredential, userCancelled, notAvailable
|
case invalidCredential, userCancelled, notAvailable
|
||||||
|
|
@ -542,7 +521,7 @@ enum PasskeyError: LocalizedError {
|
||||||
switch self {
|
switch self {
|
||||||
case .invalidCredential: return "Invalid passkey credential"
|
case .invalidCredential: return "Invalid passkey credential"
|
||||||
case .userCancelled: return "Passkey cancelled"
|
case .userCancelled: return "Passkey cancelled"
|
||||||
case .notAvailable: return "Requires iOS 17+"
|
case .notAvailable: return "Passkeys require iOS 16+"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue