Skip to content

Commit

Permalink
Use NIOThreadPool for all Bcrypt operations (#78)
Browse files Browse the repository at this point in the history
* auth-jwt: Run password hash on NIOThreadPool

* Remove unused function
  • Loading branch information
adam-fowler authored May 4, 2024
1 parent da34b08 commit 9eeceaf
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 10 deletions.
2 changes: 1 addition & 1 deletion auth-jwt/Sources/App/Controllers/UserController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ struct UserController<Context: AuthRequestContext> {
// 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))
Expand Down
11 changes: 8 additions & 3 deletions auth-jwt/Sources/App/Models/User.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import FluentKit
import Foundation
import Hummingbird
import HummingbirdAuth
import NIOPosix

/// Database description of a user
final class User: Model {
Expand All @@ -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
}
}
}

Expand Down Expand Up @@ -82,4 +87,4 @@ struct AuthenticatedUser: Authenticatable {
self.id = try user.requireID()
self.name = user.name
}
}
}
6 changes: 0 additions & 6 deletions todos-auth-fluent/Sources/App/Models/User.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit 9eeceaf

Please sign in to comment.