From f00b15706419ea2807ab2cf58c7965c2139c32ac Mon Sep 17 00:00:00 2001 From: Adam Fowler Date: Fri, 3 May 2024 18:07:18 +0100 Subject: [PATCH 1/2] auth-jwt: Run password hash on NIOThreadPool --- auth-jwt/Sources/App/Controllers/UserController.swift | 2 +- auth-jwt/Sources/App/Models/User.swift | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/auth-jwt/Sources/App/Controllers/UserController.swift b/auth-jwt/Sources/App/Controllers/UserController.swift index d7838946..dc140c79 100644 --- a/auth-jwt/Sources/App/Controllers/UserController.swift +++ b/auth-jwt/Sources/App/Controllers/UserController.swift @@ -43,7 +43,7 @@ struct UserController { // if user already exist throw conflict guard existingUser == nil else { throw HTTPError(.conflict) } - let user = User(from: createUser) + let user = try await User(from: createUser) try await user.save(on: db) return .init(status: .created, response: UserResponse(from: user)) diff --git a/auth-jwt/Sources/App/Models/User.swift b/auth-jwt/Sources/App/Models/User.swift index aeba144a..90e8f6b2 100644 --- a/auth-jwt/Sources/App/Models/User.swift +++ b/auth-jwt/Sources/App/Models/User.swift @@ -16,6 +16,7 @@ import FluentKit import Foundation import Hummingbird import HummingbirdAuth +import NIOPosix /// Database description of a user final class User: Model { @@ -38,10 +39,14 @@ final class User: Model { self.passwordHash = passwordHash } - internal init(from userRequest: CreateUserRequest) { + internal init(from userRequest: CreateUserRequest) async throws { self.id = nil self.name = userRequest.name - self.passwordHash = userRequest.password.map { Bcrypt.hash($0, cost: 12) } + if let password = userRequest.password { + self.passwordHash = try await NIOThreadPool.singleton.runIfActive { Bcrypt.hash(password, cost: 12) } + } else { + self.passwordHash = nil + } } } @@ -82,4 +87,4 @@ struct AuthenticatedUser: Authenticatable { self.id = try user.requireID() self.name = user.name } -} \ No newline at end of file +} From 3f32894866bb2b2e4e47cd07a83e8127f5324d5a Mon Sep 17 00:00:00 2001 From: Adam Fowler Date: Fri, 3 May 2024 18:10:09 +0100 Subject: [PATCH 2/2] Remove unused function --- todos-auth-fluent/Sources/App/Models/User.swift | 6 ------ 1 file changed, 6 deletions(-) diff --git a/todos-auth-fluent/Sources/App/Models/User.swift b/todos-auth-fluent/Sources/App/Models/User.swift index 926fb212..c88204f5 100644 --- a/todos-auth-fluent/Sources/App/Models/User.swift +++ b/todos-auth-fluent/Sources/App/Models/User.swift @@ -46,12 +46,6 @@ final class User: Model, Authenticatable, @unchecked Sendable { self.email = email self.passwordHash = passwordHash } - - internal init(from userRequest: CreateUserRequest) { - self.id = nil - self.name = userRequest.name - self.passwordHash = Bcrypt.hash(userRequest.password, cost: 12) - } } extension User {