94 lines
2.4 KiB
Swift
94 lines
2.4 KiB
Swift
import Fluent
|
|
import Foundation
|
|
import Vapor
|
|
|
|
func routes(_ app: Application) throws {
|
|
app.get { req in
|
|
let output = try await req.view.render("login")
|
|
return output
|
|
}
|
|
|
|
app.get("loggedIn") { req in
|
|
guard let userIdString = req.session.data["userId"],
|
|
let displayName = req.session.data["displayName"],
|
|
let userId = UUID(uuidString: userIdString)
|
|
else {
|
|
return try await req.view.render("/")
|
|
}
|
|
guard let user = try await User.query(on: req.db)
|
|
.filter(\.$id == userId)
|
|
.with(\.$prosAndCons)
|
|
.first()
|
|
else {
|
|
throw Abort(.unauthorized)
|
|
}
|
|
// let prosAndCons = try await user.$prosAndCons.get(on: req.db)
|
|
return try await req.view.render(
|
|
"loggedIn",
|
|
LoggedInContext(name: displayName, prosAndCons: user.prosAndCons)
|
|
)
|
|
}
|
|
|
|
app.get("submitProOrCon") { req in
|
|
let params = try req.query.decode(SubmitProOrCon.self)
|
|
guard let userIdString = req.session.data["userId"],
|
|
let userId = UUID(uuidString: userIdString)
|
|
else {
|
|
throw Abort(.unauthorized)
|
|
}
|
|
let proOrCon = ProCon(type: params.type, description: params.description, userId: userId)
|
|
_ = try await req.db.transaction {
|
|
proOrCon.save(on: $0)
|
|
}
|
|
.get()
|
|
|
|
return req.redirect(to: "loggedIn")
|
|
}
|
|
|
|
app.get("login") { req in
|
|
let params = try req.query.decode(LoginParams.self)
|
|
req.logger.info("params: \(params)")
|
|
|
|
do {
|
|
try checkForBadWords(in: params.displayName)
|
|
} catch {
|
|
throw Abort(.unauthorized, reason: "Stop using such naughty language.")
|
|
}
|
|
|
|
let user = User(displayName: params.displayName)
|
|
_ = try await req.db.transaction {
|
|
user.save(on: $0)
|
|
}.get()
|
|
|
|
let userId = user.id?.uuidString ?? "nil"
|
|
req.session.data["userId"] = userId
|
|
req.session.data["displayName"] = user.displayName
|
|
|
|
// return try await req.view.render("loggedIn", ["name": user.displayName])
|
|
return req.redirect(to: "loggedIn")
|
|
}
|
|
}
|
|
|
|
struct DisplayNameError: Error {}
|
|
|
|
struct LoginParams: Content {
|
|
let displayName: String
|
|
}
|
|
|
|
struct SubmitProOrCon: Content {
|
|
let type: ProCon.ProConType
|
|
let description: String
|
|
}
|
|
|
|
struct LoggedInContext: Encodable {
|
|
let name: String
|
|
let pros: [ProCon]
|
|
let cons: [ProCon]
|
|
|
|
init(name: String, prosAndCons: [ProCon]) {
|
|
self.name = name
|
|
self.cons = prosAndCons.filter { $0.type == .con }
|
|
self.pros = prosAndCons.filter { $0.type == .pro }
|
|
}
|
|
}
|