Fix: Improve better-auth integration and passkey flow

Adjusted the `BETTER_AUTH_URL` in `.env.example` to emphasize its
importance for proper functioning, especially for local development.

Updated the catch-all handler in
`apps/api/app/api/auth/[...all]/route.ts` to directly use the
`auth.handler` from `better-auth`, simplifying the configuration.

Corrected the file path for the TypeScript route definitions in
`apps/api/next-env.d.ts`.

In the iOS app, updated the API endpoints called for passkey sign-in and
registration in `AppState.swift` to include the `/api` prefix, ensuring
they match the backend routes.

Refactored `SignInView.swift` to provide a cleaner and more intuitive
user experience:
- Introduced a toggle (`usePasskey`) to switch between passkey and
  email/password authentication.
- Redesigned the UI with distinct sections for each authentication
  method.
- Enhanced the email and password form with better styling and
  validation feedback.
- Added a "Continue" button for email/password sign-in and "Continue
  with Passkey" for passkey authentication.
- Modified the `authenticate` and `authenticateWithPasskey` functions to
  correctly invoke the `AppState` methods.

Updated `SignUpView.swift` to use the `authenticate` method for
consistency, which handles both sign-up and sign-in flows.
This commit is contained in:
bananabas 2026-04-13 19:10:33 +01:00
parent a59c092172
commit 67f24f4cd7
7 changed files with 196 additions and 205 deletions

View file

@ -2,6 +2,9 @@
DATABASE_URL=postgresql://user:password@localhost:5432/shop DATABASE_URL=postgresql://user:password@localhost:5432/shop
# Better Auth # Better Auth
# IMPORTANT: BETTER_AUTH_URL must match the actual server URL or auth will return 404
# For VPS: use the actual domain (e.g., https://api.bagsy.frg.network)
# For local: use http://localhost:3001
BETTER_AUTH_SECRET=your-secret-key-here-at-least-32-characters BETTER_AUTH_SECRET=your-secret-key-here-at-least-32-characters
BETTER_AUTH_URL=http://localhost:3001 BETTER_AUTH_URL=http://localhost:3001

View file

@ -1,16 +1,9 @@
import { auth } from '@/lib/auth'; import { auth } from '@/lib/auth';
import { toNextJsHandler } from 'better-auth/next-js';
/** const handler = auth.handler;
* Better Auth catch-all handler for all authentication routes
* Handles: /api/auth/sign-up, /api/auth/sign-in, /api/auth/passkey/*, etc.
*
* Note: auth object is callable as a function and handles all HTTP methods
*/
const handlers = toNextJsHandler(auth);
export const GET = handlers.GET; export const GET = handler;
export const POST = handlers.POST; export const POST = handler;
export const PATCH = handlers.PATCH; export const PATCH = handler;
export const PUT = handlers.PUT; export const PUT = handler;
export const DELETE = handlers.DELETE; export const DELETE = handler;

View file

@ -1,6 +1,6 @@
/// <reference types="next" /> /// <reference types="next" />
/// <reference types="next/image-types/global" /> /// <reference types="next/image-types/global" />
import "./.next/dev/types/routes.d.ts"; import "./.next/types/routes.d.ts";
// NOTE: This file should not be edited // NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information. // see https://nextjs.org/docs/app/api-reference/config/typescript for more information.

View file

@ -70,7 +70,7 @@ class AppState: ObservableObject {
let passkeyResult: PasskeySignInResult = 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", "api/auth/sign-in/passkey",
body: passkeyResult body: passkeyResult
) )
@ -117,7 +117,7 @@ class AppState: ObservableObject {
let passkeyResult: PasskeyRegistrationResult = 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", "api/auth/passkey/add-passkey",
body: passkeyResult body: passkeyResult
) )
@ -129,74 +129,57 @@ class AppState: ObservableObject {
} }
} }
func signUp(email: String, password: String) async throws { func authenticate(email: String, password: String) async throws {
isLoading = true isLoading = true
errorMessage = nil errorMessage = nil
defer { isLoading = false } defer { isLoading = false }
let payload = SignUpPayload(email: email, password: password)
do { do {
let response: APIResponse<AuthResponse> = try await apiClient.post("auth/sign-up", body: payload) // Try sign in first
let signInPayload = SignInPayload(email: email, password: password)
let signInResponse: APIResponse<AuthResponse> = try await apiClient.post("api/auth/sign-in", body: signInPayload)
if let error = response.error { // If sign in succeeds, use that response
if let authData = signInResponse.data, signInResponse.error == nil {
return try await _completeAuthentication(authData)
}
// If sign in fails with user not found, try sign up
let displayName = email.split(separator: "@").first.map(String.init) ?? email
let signUpPayload = SignUpPayload(email: email, password: password, name: displayName)
let signUpResponse: APIResponse<AuthResponse> = try await apiClient.post("api/auth/sign-up", body: signUpPayload)
if let error = signUpResponse.error {
throw AuthError.serverError(message: error.message) throw AuthError.serverError(message: error.message)
} }
guard let data = response.data else { guard let authData = signUpResponse.data else {
throw AuthError.invalidResponse throw AuthError.invalidResponse
} }
try await keychainManager.saveToken(data.session.token) try await _completeAuthentication(authData)
self.currentUser = data.user
self.currentHousehold = data.household
try await cacheManager.cacheUser(data.user)
try await cacheManager.cacheHousehold(data.household)
self.isAuthenticated = true
await webSocketManager.connect(
householdId: data.household.id,
userId: data.user.id,
baseURL: serverURL
)
} catch let error as APIError { } catch let error as APIError {
throw AuthError.apiError(error) throw AuthError.apiError(error)
} }
} }
func signIn(email: String, password: String) async throws { private func _completeAuthentication(_ authData: AuthResponse) async throws {
isLoading = true try await keychainManager.saveToken(authData.session.token)
errorMessage = nil self.currentUser = authData.user
defer { isLoading = false } self.currentHousehold = authData.household
try await cacheManager.cacheUser(authData.user)
try await cacheManager.cacheHousehold(authData.household)
self.isAuthenticated = true
let payload = SignInPayload(email: email, password: password) await webSocketManager.connect(
householdId: authData.household.id,
userId: authData.user.id,
baseURL: serverURL
)
do { // Set token in PasskeyHelper and initiate passkey setup
let response: APIResponse<AuthResponse> = try await apiClient.post("auth/sign-in", body: payload) PasskeyHelper.shared.setAuthToken(authData.session.token)
try await setupPasskey()
if let error = response.error {
throw AuthError.serverError(message: error.message)
}
guard let data = response.data else {
throw AuthError.invalidResponse
}
try await keychainManager.saveToken(data.session.token)
self.currentUser = data.user
self.currentHousehold = data.household
try await cacheManager.cacheUser(data.user)
try await cacheManager.cacheHousehold(data.household)
self.isAuthenticated = true
await webSocketManager.connect(
householdId: data.household.id,
userId: data.user.id,
baseURL: serverURL
)
} catch let error as APIError {
throw AuthError.apiError(error)
}
} }
func createHousehold(name: String) async throws { func createHousehold(name: String) async throws {
@ -301,6 +284,7 @@ class AppState: ObservableObject {
struct SignUpPayload: Codable { struct SignUpPayload: Codable {
let email: String let email: String
let password: String let password: String
let name: String
} }
struct SignInPayload: Codable { struct SignInPayload: Codable {
@ -368,6 +352,7 @@ class PasskeyHelper: NSObject, ObservableObject, ASAuthorizationControllerDelega
var relyingPartyID: String = "localhost" var relyingPartyID: String = "localhost"
var serverBaseURL: String = "http://localhost:3001" var serverBaseURL: String = "http://localhost:3001"
private var authToken: String?
var isAvailable: Bool { var isAvailable: Bool {
if #available(iOS 16.0, *) { return true } if #available(iOS 16.0, *) { return true }
@ -377,6 +362,10 @@ class PasskeyHelper: NSObject, ObservableObject, ASAuthorizationControllerDelega
private var authContinuation: CheckedContinuation<ASAuthorizationPlatformPublicKeyCredentialAssertion, Error>? private var authContinuation: CheckedContinuation<ASAuthorizationPlatformPublicKeyCredentialAssertion, Error>?
private var regContinuation: CheckedContinuation<ASAuthorizationPlatformPublicKeyCredentialRegistration, Error>? private var regContinuation: CheckedContinuation<ASAuthorizationPlatformPublicKeyCredentialRegistration, Error>?
func setAuthToken(_ token: String) {
self.authToken = token
}
func signIn() async throws -> PasskeySignInResult { func signIn() async throws -> PasskeySignInResult {
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") let options = try await fetchOptions(path: "generate-authentication-options")
@ -409,7 +398,7 @@ class PasskeyHelper: NSObject, ObservableObject, ASAuthorizationControllerDelega
func register(userId: String, email: String) async throws -> PasskeyRegistrationResult { func register(userId: String, email: String) async throws -> PasskeyRegistrationResult {
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 options = try await fetchRegistrationOptions()
let challengeData: Data = { let challengeData: Data = {
var b64 = options.challenge.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/") var b64 = options.challenge.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
let rem = b64.count % 4; if rem != 0 { b64 += String(repeating: "=", count: 4 - rem) } let rem = b64.count % 4; if rem != 0 { b64 += String(repeating: "=", count: 4 - rem) }
@ -447,6 +436,19 @@ class PasskeyHelper: NSObject, ObservableObject, ASAuthorizationControllerDelega
return try JSONDecoder().decode(WebAuthnOptionsResponse.self, from: data) return try JSONDecoder().decode(WebAuthnOptionsResponse.self, from: data)
} }
private func fetchRegistrationOptions() async throws -> WebAuthnOptionsResponse {
guard let token = authToken else {
throw PasskeyError.invalidCredential
}
let url = URL(string: "\(serverBaseURL)/api/auth/passkey/add-passkey")!
var req = URLRequest(url: url)
req.httpMethod = "POST"
req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
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, *) {
if let assertion = authorization.credential as? ASAuthorizationPlatformPublicKeyCredentialAssertion { if let assertion = authorization.credential as? ASAuthorizationPlatformPublicKeyCredentialAssertion {

View file

@ -5,7 +5,7 @@ struct SignInView: View {
@State private var email = "" @State private var email = ""
@State private var password = "" @State private var password = ""
@State private var showError = false @State private var showError = false
@State private var isUsingPasskey = true @State private var usePasskey = false
@FocusState private var focusedField: FocusedField? @FocusState private var focusedField: FocusedField?
enum FocusedField { enum FocusedField {
@ -14,114 +14,54 @@ struct SignInView: View {
let bagsyOrange = Color(red: 1.0, green: 0.42, blue: 0.21) let bagsyOrange = Color(red: 1.0, green: 0.42, blue: 0.21)
var isFormValid: Bool {
!email.isEmpty && !password.isEmpty && password.count >= 8
}
var body: some View { var body: some View {
NavigationStack { ZStack {
ZStack { LinearGradient(
// Background gradient: Gradient(colors: [
Color(.systemBackground) Color(red: 0.98, green: 0.96, blue: 0.94),
.ignoresSafeArea() Color(red: 1.0, green: 0.98, blue: 0.96)
]),
startPoint: .topLeading,
endPoint: .bottomTrailing
)
.ignoresSafeArea()
VStack(spacing: 20) { VStack(spacing: 20) {
VStack(alignment: .leading, spacing: 8) { VStack(alignment: .leading, spacing: 8) {
Text("Welcome to Bagsy") Text("Welcome to Bagsy")
.font(.title2) .font(.largeTitle)
.fontWeight(.bold) .fontWeight(.bold)
.foregroundColor(.primary) .foregroundColor(.black)
Text("Sign in to your account") Text("Sign in or create account")
.font(.subheadline) .foregroundColor(.gray)
.foregroundColor(.secondary) }
} .frame(maxWidth: .infinity, alignment: .leading)
.frame(maxWidth: .infinity, alignment: .leading) .padding(.bottom, 20)
.padding(.bottom, 20)
if isUsingPasskey { if usePasskey {
VStack(spacing: 16) { // Passkey Option
Image(systemName: "faceid") VStack(spacing: 16) {
.font(.system(size: 64)) Image(systemName: "faceid")
.foregroundColor(bagsyOrange) .font(.system(size: 48))
.padding(.vertical, 20) .foregroundColor(bagsyOrange)
Text("Sign in with Passkey") Text("Use Passkey")
.font(.headline) .font(.headline)
.foregroundColor(.primary) .foregroundColor(.black)
Text("Use Face ID or Touch ID to sign in securely") Text("Faster and more secure")
.font(.subheadline) .font(.caption)
.foregroundColor(.secondary) .foregroundColor(.gray)
.multilineTextAlignment(.center)
Button(action: signInWithPasskey) { Button(action: authenticateWithPasskey) {
if appState.isLoading {
ProgressView()
.tint(.white)
} else {
HStack {
Image(systemName: "touchid")
Text("Use Passkey")
.fontWeight(.semibold)
}
}
}
.frame(maxWidth: .infinity)
.frame(height: 56)
.background(bagsyOrange)
.foregroundColor(.white)
.cornerRadius(16)
.disabled(appState.isLoading)
Button(action: { isUsingPasskey = false }) {
Text("Use Email Instead")
.foregroundColor(bagsyOrange)
.fontWeight(.semibold)
}
}
.padding(.bottom, 20)
} else {
VStack(spacing: 16) {
// Email Field
VStack(alignment: .leading, spacing: 8) {
Text("Email")
.font(.subheadline)
.foregroundColor(.primary)
TextField("you@example.com", text: $email)
.textInputAutocapitalization(.never)
.keyboardType(.emailAddress)
.autocorrectionDisabled(true)
.focused($focusedField, equals: .email)
.padding(14)
.background(Color(.systemGray6))
.cornerRadius(12)
.overlay(
RoundedRectangle(cornerRadius: 12)
.stroke(bagsyOrange, lineWidth: focusedField == .email ? 2 : 0)
)
}
// Password Field
VStack(alignment: .leading, spacing: 8) {
Text("Password")
.font(.subheadline)
.foregroundColor(.primary)
SecureField("Enter your password", text: $password)
.focused($focusedField, equals: .password)
.padding(14)
.background(Color(.systemGray6))
.cornerRadius(12)
.overlay(
RoundedRectangle(cornerRadius: 12)
.stroke(bagsyOrange, lineWidth: focusedField == .password ? 2 : 0)
)
}
}
.padding(.bottom, 20)
// Sign In Button
Button(action: signIn) {
if appState.isLoading { if appState.isLoading {
ProgressView() ProgressView().tint(.white)
.tint(.white)
} else { } else {
Text("Sign In") Text("Continue with Passkey")
.fontWeight(.semibold) .fontWeight(.semibold)
} }
} }
@ -130,35 +70,88 @@ struct SignInView: View {
.background(bagsyOrange) .background(bagsyOrange)
.foregroundColor(.white) .foregroundColor(.white)
.cornerRadius(16) .cornerRadius(16)
.disabled(appState.isLoading || email.isEmpty || password.isEmpty) .disabled(appState.isLoading)
Button(action: { isUsingPasskey = true }) { Button(action: { usePasskey = false }) {
Text("Use Passkey Instead") Text("Use Email & Password")
.foregroundColor(bagsyOrange) .foregroundColor(bagsyOrange)
.fontWeight(.semibold) .fontWeight(.semibold)
} }
} }
.padding(.bottom, 20)
} else {
// Email & Password Form
VStack(spacing: 16) {
VStack(alignment: .leading, spacing: 8) {
Text("Email")
.font(.subheadline)
.fontWeight(.semibold)
.foregroundColor(.black)
TextField("you@example.com", text: $email)
.keyboardType(.emailAddress)
.textInputAutocapitalization(.never)
.autocorrectionDisabled(true)
.focused($focusedField, equals: .email)
.padding(14)
.background(Color.white)
.cornerRadius(16)
.overlay(
RoundedRectangle(cornerRadius: 16)
.stroke(bagsyOrange, lineWidth: focusedField == .email ? 2 : 0)
)
}
// Sign Up Link VStack(alignment: .leading, spacing: 8) {
HStack(spacing: 4) { Text("Password")
Text("Don't have an account?") .font(.subheadline)
.foregroundColor(.secondary) .fontWeight(.semibold)
NavigationLink("Sign up", destination: SignUpView()) .foregroundColor(.black)
.foregroundColor(bagsyOrange) SecureField("At least 8 characters", text: $password)
.focused($focusedField, equals: .password)
.padding(14)
.background(Color.white)
.cornerRadius(16)
.overlay(
RoundedRectangle(cornerRadius: 16)
.stroke(bagsyOrange, lineWidth: focusedField == .password ? 2 : 0)
)
}
} }
.font(.subheadline) .padding(.bottom, 20)
Spacer() // Auth Button
} Button(action: authenticate) {
.padding(16) if appState.isLoading {
.alert("Error", isPresented: $showError) { ProgressView().tint(.white)
Button("OK") { } } else {
} message: { Text("Continue")
Text(appState.errorMessage ?? "An error occurred") .fontWeight(.semibold)
} }
.onChange(of: appState.errorMessage) { newValue in }
showError = newValue != nil .frame(maxWidth: .infinity)
.frame(height: 56)
.background(bagsyOrange)
.foregroundColor(.white)
.cornerRadius(16)
.disabled(appState.isLoading || !isFormValid)
Button(action: { usePasskey = true }) {
Text("Use Passkey Instead")
.foregroundColor(bagsyOrange)
.fontWeight(.semibold)
}
} }
Spacer()
}
.padding()
.alert("Error", isPresented: $showError) {
Button("OK") { }
} message: {
Text(appState.errorMessage ?? "An error occurred")
}
.onChange(of: appState.errorMessage) { newValue in
showError = newValue != nil
} }
.onTapGesture { .onTapGesture {
focusedField = nil focusedField = nil
@ -166,20 +159,20 @@ struct SignInView: View {
} }
} }
private func signInWithPasskey() { private func authenticate() {
Task { Task {
do { do {
try await appState.signInWithPasskey() try await appState.authenticate(email: email, password: password)
} catch { } catch {
appState.errorMessage = error.localizedDescription appState.errorMessage = error.localizedDescription
} }
} }
} }
private func signIn() { private func authenticateWithPasskey() {
Task { Task {
do { do {
try await appState.signIn(email: email, password: password) try await appState.signInWithPasskey()
} catch { } catch {
appState.errorMessage = error.localizedDescription appState.errorMessage = error.localizedDescription
} }

View file

@ -149,7 +149,7 @@ struct SignUpView: View {
private func signUp() { private func signUp() {
Task { Task {
do { do {
try await appState.signUp(email: email, password: password) try await appState.authenticate(email: email, password: password)
} catch { } catch {
appState.errorMessage = error.localizedDescription appState.errorMessage = error.localizedDescription
} }