Schafkopf-Server/Sources/App/Model/PasswordReset.swift

73 lines
1.6 KiB
Swift
Raw Normal View History

2022-10-11 12:04:15 +02:00
import Foundation
import FluentSQLiteDriver
import Crypto
private extension FieldProperty {
convenience init(_ key: PasswordReset.Key) {
self.init(key: key.key)
}
}
private extension ParentProperty {
convenience init(_ key: PasswordReset.Key) {
self.init(key: key.key)
}
}
extension PasswordReset.Key {
var key: FieldKey {
.init(stringLiteral: rawValue)
}
}
final class PasswordReset: Model {
/// The name of the SQLite table
static let schema = "reset"
enum Key: String {
case id = "id"
case user = "user"
case token = "token"
case expiry = "expiry"
}
/// The unique identifier for the reset request
@ID(key: .id)
var id: UUID?
/// The user associated with the reset request
@Parent(.user)
var user: User
/// The random reset token issued with the email
@Field(.token)
var resetToken: String
/// The time when the reset token expires and can't be used anymore
@Field(.expiry)
var expiryDate: Date
2022-10-12 19:28:28 +02:00
init() {
self.resetToken = .newToken()
self.expiryDate = Self.currentExpiryDate()
}
func renew() {
self.resetToken = .newToken()
self.expiryDate = Self.currentExpiryDate()
}
2022-10-11 12:04:15 +02:00
/// Creates a new password reset.
init(id: UUID? = nil, user: User) {
self.id = id
2022-10-12 19:28:28 +02:00
self.$user.id = user.id!
2022-10-11 12:04:15 +02:00
self.resetToken = .newToken()
2022-10-12 19:28:28 +02:00
self.expiryDate = Self.currentExpiryDate()
}
private static func currentExpiryDate() -> Date {
Date().addingTimeInterval(15*60)
2022-10-11 12:04:15 +02:00
}
}