/
LoginCache.swift
56 lines (48 loc) · 1.82 KB
/
LoginCache.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//===----------------------------------------------------------------------===//
//
// This source file is part of the Hummingbird server framework project
//
// Copyright (c) 2023 the Hummingbird authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Hummingbird
public struct LoginCache: Sendable {
public init() {
self.cache = [:]
}
/// Login with authenticatable object. Add object to cache
/// - Parameter auth: authentication details
public mutating func login<Auth: Authenticatable>(_ auth: Auth) {
self.cache = [ObjectIdentifier(Auth.self): auth]
}
/// Logout authenticatable object. Removes object from cache
/// - Parameter auth: authentication type
public mutating func logout<Auth: Authenticatable>(_: Auth.Type) {
self.cache[ObjectIdentifier(Auth.self)] = nil
}
/// Return authenticated type
/// - Parameter auth: Type required
public func get<Auth: Authenticatable>(_: Auth.Type) -> Auth? {
return self.cache[ObjectIdentifier(Auth.self)] as? Auth
}
/// Require authenticated type
/// - Parameter auth: Type required
public func require<Auth: Authenticatable>(_: Auth.Type) throws -> Auth {
guard let auth = get(Auth.self) else {
throw HTTPError(.unauthorized)
}
return auth
}
/// Return if cache is authenticated with type
/// - Parameter auth: Authentication type
public func has<Auth: Authenticatable>(_: Auth.Type) -> Bool {
return self.cache[ObjectIdentifier(Auth.self)] != nil
}
var cache: [ObjectIdentifier: Authenticatable]
}