forked from vapor/postgres-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostgreSQLMessage+AuthenticationRequest.swift
51 lines (45 loc) · 1.71 KB
/
PostgreSQLMessage+AuthenticationRequest.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
extension PostgreSQLMessage {
/// Authentication request returned by the server.
enum AuthenticationRequest {
/// AuthenticationOk
/// Specifies that the authentication was successful.
case ok
/// AuthenticationCleartextPassword
/// Specifies that a clear-text password is required.
case plaintext
/// AuthenticationMD5Password
/// Specifies that an MD5-encrypted password is required.
case md5(Data)
}
}
// MARK: String
extension PostgreSQLMessage.AuthenticationRequest: CustomStringConvertible {
/// See `CustomStringConvertible`.
var description: String {
switch self {
case .ok: return "Ok"
case .plaintext: return "CleartextPassword"
case .md5(let salt): return "MD5Password(salt: 0x\(salt.hexEncodedString())"
}
}
}
// MARK: Parse
extension PostgreSQLMessage.AuthenticationRequest {
/// Parses an instance of this message type from a byte buffer.
static func parse(from buffer: inout ByteBuffer) throws -> PostgreSQLMessage.AuthenticationRequest {
guard let type = buffer.readInteger(as: Int32.self) else {
throw PostgreSQLError.protocol(reason: "Could not read authentication message type.")
}
switch type {
case 0: return .ok
case 3: return .plaintext
case 5:
guard let salt = buffer.readData(length: 4) else {
throw PostgreSQLError.protocol(reason: "Could not parse MD5 salt from authentication message.")
}
return .md5(salt)
default:
throw PostgreSQLError.protocol(reason: "Unkonwn authentication request type: \(type).")
}
}
}