Make email configuration optional

This commit is contained in:
Christoph Hagen 2022-11-24 21:31:03 +01:00
parent bb8eb7ac82
commit 1c36d8c480
2 changed files with 30 additions and 15 deletions

View File

@ -4,7 +4,7 @@ struct Configuration {
let serverPort: Int
let mail: EMail
let mail: EMail?
/**
Use a database file and reduce logging.

View File

@ -6,6 +6,15 @@ import SwiftSMTP
typealias PasswordHash = String
typealias SessionToken = String
private struct MailConfig {
let mailConfiguration: Configuration.EMail
let smtp: SMTP
let mailSender: Mail.User
}
final class SQLiteDatabase {
/// A mapping between player name and generated access tokens for a session
@ -16,20 +25,21 @@ final class SQLiteDatabase {
private let tables: TableManagement
private let mailConfiguration: Configuration.EMail
private let mail: MailConfig?
private let smtp: SMTP
private let mailSender: Mail.User
init(db: Database, mail: Configuration.EMail) throws {
init(db: Database, mail: Configuration.EMail?) throws {
self.tables = try TableManagement(db: db)
self.smtp = SMTP(
guard let mail else {
self.mail = nil
return
}
let smtp = SMTP(
hostname: mail.emailHostname,
email: mail.email,
password: mail.password)
self.mailSender = Mail.User(name: "Schafkopf Server", email: mail.email)
self.mailConfiguration = mail
let mailSender = Mail.User(name: "Schafkopf Server", email: mail.email)
self.mail = .init(mailConfiguration: mail, smtp: smtp, mailSender: mailSender)
}
func registerPlayer(named name: PlayerName, hash: PasswordHash, email: String?, in database: Database) async throws -> SessionToken {
@ -81,10 +91,15 @@ final class SQLiteDatabase {
}
private func sendEmail(name: PlayerName, email: String, token: String) {
guard let mailData = mail else {
print("Recovery email not set up")
return
}
let recipient = Mail.User(name: name, email: email)
let mailConfiguration = mailData.mailConfiguration
let url = "\(mailConfiguration.serverDomain)/recovery.html?token=\(token)"
let mail = Mail(
from: mailSender,
from: mailData.mailSender,
to: [recipient],
subject: "Schafkopf Server Password Reset",
text:
@ -104,7 +119,7 @@ final class SQLiteDatabase {
"""
)
smtp.send(mail) { (error) in
mailData.smtp.send(mail) { (error) in
if let error = error {
print("Failed to send recovery email to \(email): \(error)")
}