Skip to content

Commit

Permalink
abstract firebase auth
Browse files Browse the repository at this point in the history
  • Loading branch information
petrpavlik committed Jan 21, 2024
1 parent 24fa991 commit 749a88c
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 13 deletions.
27 changes: 27 additions & 0 deletions Sources/App/Auth/FirebaseAuth.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
//
// File.swift
//
//
// Created by Petr Pavlik on 21.01.2024.
//

import Vapor
import FirebaseJWTMiddleware

protocol JWTUser {
var userID: String { get }
var email: String? { get }
}

extension FirebaseJWTPayload : JWTUser {

}

extension Request {
var jwtUser: some JWTUser {
get async throws {
// This is where you can swap Firebase Auth for another JWT-based provider (Amazon Congnito, Clerk, ...)
try await self.firebaseJwt.asyncVerify()
}
}
}
17 changes: 4 additions & 13 deletions Sources/App/Controllers/ProfileController.swift
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import Fluent
import Vapor
import FirebaseJWTMiddleware
import MixpanelVapor

extension Request {
var profile: Profile {
get async throws {
let token = try await self.firebaseJwt.asyncVerify()
let token = try await self.jwtUser
if let profile = try await Profile.query(on: self.db).filter(\.$firebaseUserId == token.userID).first() {
return profile
} else {
Expand All @@ -29,19 +28,11 @@ struct ProfileLiteDTO: Content {

extension Profile {
func toDTO() throws -> ProfileDTO {
guard let id else {
throw Abort(.internalServerError, reason: "missing profile id")
}

return .init(id: id, email: email, isSubscribedToNewsletter: subscribedToNewsletterAt != nil)
.init(id: try requireID(), email: email, isSubscribedToNewsletter: subscribedToNewsletterAt != nil)
}

func toLiteDTO() throws -> ProfileLiteDTO {
guard let id else {
throw Abort(.internalServerError, reason: "missing profile id")
}

return .init(id: id, email: email)
.init(id: try requireID(), email: email)
}
}

Expand All @@ -59,7 +50,7 @@ struct ProfileController: RouteCollection {
}

func create(req: Request) async throws -> ProfileDTO {
let token = try await req.firebaseJwt.asyncVerify()
let token = try await req.jwtUser
if let profile = try await Profile.query(on: req.db).filter(\.$firebaseUserId == token.userID).first() {

guard let email = token.email else {
Expand Down

0 comments on commit 749a88c

Please sign in to comment.