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
# 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_URL=http://localhost:3001

View file

@ -1,16 +1,9 @@
import { auth } from '@/lib/auth';
import { toNextJsHandler } from 'better-auth/next-js';
/**
* 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);
const handler = auth.handler;
export const GET = handlers.GET;
export const POST = handlers.POST;
export const PATCH = handlers.PATCH;
export const PUT = handlers.PUT;
export const DELETE = handlers.DELETE;
export const GET = handler;
export const POST = handler;
export const PATCH = handler;
export const PUT = handler;
export const DELETE = handler;

View file

@ -1,6 +1,6 @@
/// <reference types="next" />
/// <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
// 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 response: APIResponse<AuthResponse> = try await apiClient.post(
"auth/sign-in/passkey",
"api/auth/sign-in/passkey",
body: passkeyResult
)
@ -117,7 +117,7 @@ class AppState: ObservableObject {
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",
"api/auth/passkey/add-passkey",
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
errorMessage = nil
defer { isLoading = false }
let payload = SignUpPayload(email: email, password: password)
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)
}
guard let data = response.data else {
guard let authData = signUpResponse.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
)
try await _completeAuthentication(authData)
} catch let error as APIError {
throw AuthError.apiError(error)
}
}
func signIn(email: String, password: String) async throws {
isLoading = true
errorMessage = nil
defer { isLoading = false }
private func _completeAuthentication(_ authData: AuthResponse) async throws {
try await keychainManager.saveToken(authData.session.token)
self.currentUser = authData.user
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 {
let response: APIResponse<AuthResponse> = try await apiClient.post("auth/sign-in", body: payload)
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)
}
// Set token in PasskeyHelper and initiate passkey setup
PasskeyHelper.shared.setAuthToken(authData.session.token)
try await setupPasskey()
}
func createHousehold(name: String) async throws {
@ -301,6 +284,7 @@ class AppState: ObservableObject {
struct SignUpPayload: Codable {
let email: String
let password: String
let name: String
}
struct SignInPayload: Codable {
@ -368,6 +352,7 @@ class PasskeyHelper: NSObject, ObservableObject, ASAuthorizationControllerDelega
var relyingPartyID: String = "localhost"
var serverBaseURL: String = "http://localhost:3001"
private var authToken: String?
var isAvailable: Bool {
if #available(iOS 16.0, *) { return true }
@ -377,6 +362,10 @@ class PasskeyHelper: NSObject, ObservableObject, ASAuthorizationControllerDelega
private var authContinuation: CheckedContinuation<ASAuthorizationPlatformPublicKeyCredentialAssertion, Error>?
private var regContinuation: CheckedContinuation<ASAuthorizationPlatformPublicKeyCredentialRegistration, Error>?
func setAuthToken(_ token: String) {
self.authToken = token
}
func signIn() async throws -> PasskeySignInResult {
guard #available(iOS 16.0, *) else { throw PasskeyError.notAvailable }
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 {
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 = {
var b64 = options.challenge.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
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)
}
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) {
if #available(iOS 16.0, *) {
if let assertion = authorization.credential as? ASAuthorizationPlatformPublicKeyCredentialAssertion {

View file

@ -5,123 +5,63 @@ struct SignInView: View {
@State private var email = ""
@State private var password = ""
@State private var showError = false
@State private var isUsingPasskey = true
@State private var usePasskey = false
@FocusState private var focusedField: FocusedField?
enum FocusedField {
case email, password
}
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 {
NavigationStack {
ZStack {
// Background
Color(.systemBackground)
.ignoresSafeArea()
VStack(spacing: 20) {
VStack(alignment: .leading, spacing: 8) {
Text("Welcome to Bagsy")
.font(.title2)
.fontWeight(.bold)
.foregroundColor(.primary)
Text("Sign in to your account")
.font(.subheadline)
.foregroundColor(.secondary)
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.bottom, 20)
if isUsingPasskey {
VStack(spacing: 16) {
Image(systemName: "faceid")
.font(.system(size: 64))
.foregroundColor(bagsyOrange)
.padding(.vertical, 20)
Text("Sign in with Passkey")
.font(.headline)
.foregroundColor(.primary)
Text("Use Face ID or Touch ID to sign in securely")
.font(.subheadline)
.foregroundColor(.secondary)
.multilineTextAlignment(.center)
Button(action: signInWithPasskey) {
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) {
ZStack {
LinearGradient(
gradient: Gradient(colors: [
Color(red: 0.98, green: 0.96, blue: 0.94),
Color(red: 1.0, green: 0.98, blue: 0.96)
]),
startPoint: .topLeading,
endPoint: .bottomTrailing
)
.ignoresSafeArea()
VStack(spacing: 20) {
VStack(alignment: .leading, spacing: 8) {
Text("Welcome to Bagsy")
.font(.largeTitle)
.fontWeight(.bold)
.foregroundColor(.black)
Text("Sign in or create account")
.foregroundColor(.gray)
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.bottom, 20)
if usePasskey {
// Passkey Option
VStack(spacing: 16) {
Image(systemName: "faceid")
.font(.system(size: 48))
.foregroundColor(bagsyOrange)
Text("Use Passkey")
.font(.headline)
.foregroundColor(.black)
Text("Faster and more secure")
.font(.caption)
.foregroundColor(.gray)
Button(action: authenticateWithPasskey) {
if appState.isLoading {
ProgressView()
.tint(.white)
ProgressView().tint(.white)
} else {
Text("Sign In")
Text("Continue with Passkey")
.fontWeight(.semibold)
}
}
@ -130,56 +70,109 @@ struct SignInView: View {
.background(bagsyOrange)
.foregroundColor(.white)
.cornerRadius(16)
.disabled(appState.isLoading || email.isEmpty || password.isEmpty)
Button(action: { isUsingPasskey = true }) {
Text("Use Passkey Instead")
.disabled(appState.isLoading)
Button(action: { usePasskey = false }) {
Text("Use Email & Password")
.foregroundColor(bagsyOrange)
.fontWeight(.semibold)
}
}
// Sign Up Link
HStack(spacing: 4) {
Text("Don't have an account?")
.foregroundColor(.secondary)
NavigationLink("Sign up", destination: SignUpView())
.foregroundColor(bagsyOrange)
.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)
)
}
VStack(alignment: .leading, spacing: 8) {
Text("Password")
.font(.subheadline)
.fontWeight(.semibold)
.foregroundColor(.black)
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)
)
}
}
.padding(.bottom, 20)
// Auth Button
Button(action: authenticate) {
if appState.isLoading {
ProgressView().tint(.white)
} else {
Text("Continue")
.fontWeight(.semibold)
}
}
.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)
}
.font(.subheadline)
Spacer()
}
.padding(16)
.alert("Error", isPresented: $showError) {
Button("OK") { }
} message: {
Text(appState.errorMessage ?? "An error occurred")
}
.onChange(of: appState.errorMessage) { newValue in
showError = newValue != nil
}
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 {
focusedField = nil
}
}
}
private func signInWithPasskey() {
private func authenticate() {
Task {
do {
try await appState.signInWithPasskey()
try await appState.authenticate(email: email, password: password)
} catch {
appState.errorMessage = error.localizedDescription
}
}
}
private func signIn() {
private func authenticateWithPasskey() {
Task {
do {
try await appState.signIn(email: email, password: password)
try await appState.signInWithPasskey()
} catch {
appState.errorMessage = error.localizedDescription
}

View file

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