Compare commits

..

5 Commits
1.1.0 ... main

11 changed files with 64 additions and 28 deletions

View File

@ -5,6 +5,7 @@ async function loadData (block) {
const response = await fetch (source);
if (response.ok) {
const items = await response.json();
var itemLoaders = [];
if (Array.isArray (items)) {
const template = block.querySelector ("template");
@ -12,15 +13,25 @@ async function loadData (block) {
tableBody.innerHTML = "";
items.forEach (item => {
const clone = template.content.cloneNode (true);
window["populate" + block.dataset.item] (clone, item);
const loader = window["populate" + block.dataset.item] (clone, item);
if (loader != null) {
itemLoaders.push (loader);
}
tableBody.appendChild (clone);
tableBody.lastElementChild.dataset.itemid = item.id;
});
} else {
window["populate" + block.dataset.item] (block, items);
const loader = window["populate" + block.dataset.item] (block, items);
if (loader != null) {
itemLoaders.push (loader);
}
}
block.classList.add ("loaded");
for (const loader of itemLoaders) {
await loader();
}
} else {
if ((response.status == 401) || (response.status == 403)) {
document.location.href = document.body.dataset.baseurl;

View File

@ -20,6 +20,7 @@ CREATE TABLE "user_tokens" (
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
"user_id" UUID NOT NULL,
"token" CHARACTER VARYING (1000) NOT NULL,
"realm" CHARACTER VARYING (10) NOT NULL CHECK ("realm" IN ('invite', 'forgot')),
"insert_time" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "user_tokens_user_fk" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE CASCADE
);

View File

@ -13,9 +13,11 @@ WITH "created" AS (
SELECT "id", 'admin'
FROM "created"
)
INSERT INTO "user_tokens" ("user_id", "token")
SELECT "id", (SELECT string_agg (substr (c, (random() * length (c) + 1)::integer, 1), '') AS "token"
INSERT INTO "user_tokens" ("user_id", "token", "realm")
SELECT "id",
(SELECT string_agg (substr (c, (random() * length (c) + 1)::integer, 1), '') AS "token"
FROM (VALUES ('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789')) AS x(c),
generate_series (1, 32))
generate_series (1, 32)),
'invite'
FROM "created"
RETURNING 'https://example.com/auth/password/' || "token" AS "Password URL"

View File

@ -1,3 +1,5 @@
Välkommen till #(host).
Welcome to #(host).
För att aktivera ditt konto, gå till #baseURL/auth/password/#(token) och skriv in ett lösenord.
To activate your account, go to #baseURL/auth/password/#(token) and enter a password.
The link is valid until #date(expiration, "yyyy-MM-dd HH:mm (z)").

View File

@ -1,3 +1,5 @@
Du har begärt ett nytt lösenord på #(host).
You have requested a new password on #(host).
För att ändra ditt lösenord, gå till #baseURL/auth/password/#(token) och skriv in ett lösenord.
To change your password, go to #baseURL/auth/password/#(token) and enter a password.
The link is valid until #date(expiration, "yyyy-MM-dd HH:mm (z)").

View File

@ -88,7 +88,7 @@ public struct AdminController<User: ManagedUser>: Sendable where User.SessionID
let token = try await UserToken.create (connection: connection).token
try await User.create (email: invitation.email, fullname: invitation.fullname, roles: invitation.roles, token: token, on: connection)
let host = try Environment.baseURL.host() ?? ""
let body = try await request.view.render ("email/invite", ["token": token, "host": host])
let body = try await request.view.render ("email/invite", AuthenticationController<User>.TokenEmailContext (token: token, host: host, expiration: Calendar.current.date (byAdding: .day, value: 1, to: Date()) ?? Date()))
.data
let message = Email (sender: Email.Contact (emailAddress: try Environment.emailSender),
recipients: [Email.Contact(emailAddress: invitation.email)],
@ -117,7 +117,7 @@ public struct AdminController<User: ManagedUser>: Sendable where User.SessionID
let save = try request.content.decode(Save.self)
return try await request.db.withSQLConnection (user: try request.auth.require (BasicUser.self)) { connection in
guard (try await User.find (userId, on: connection)) != nil else {
guard (try await User.fetch (userId, on: connection)) != nil else {
throw Abort (.notFound)
}
guard !save.email.isEmpty && !save.fullname.isEmpty else {

View File

@ -91,6 +91,12 @@ public struct AuthenticationController<User: ManagedUser>: Sendable where User.S
let email: String
}
struct TokenEmailContext: Encodable {
let token: String
let host: String
let expiration: Date
}
func forgotPassword (request: Request) async throws -> Response {
let input = try request.content.decode (Input.self)
@ -101,7 +107,7 @@ public struct AuthenticationController<User: ManagedUser>: Sendable where User.S
let token = try await UserToken.create (connection: connection).token
try await User.store (token: token, userId: user.id, on: connection)
let host = try Environment.baseURL.host() ?? ""
let body = try await request.view.render ("email/reset", ["token": token, "host": host, "section": "login"])
let body = try await request.view.render ("email/reset", TokenEmailContext (token: token, host: host, expiration: Calendar.current.date (byAdding: .hour, value: 1, to: Date()) ?? Date()))
.data
let message = Email (sender: Email.Contact (emailAddress: try Environment.emailSender),
recipients: [Email.Contact(emailAddress: input.email)],

View File

@ -4,14 +4,22 @@ import FluentPostgresDriver
import SwiftSMTPVapor
public struct ManageableUsers {
public static func configure (_ app: Application, mainMenu: [MenuItem] = [], homePageName: String = "Home", userAdminPageName: String = "User Administration") async throws {
app.databases.use(DatabaseConfigurationFactory.postgres(configuration: .init(
hostname: Environment.get("DATABASE_HOST") ?? "localhost",
public static func configure (_ app: Application,
mainMenu: [MenuItem] = [],
homePageName: String = "Home",
userAdminPageName: String = "User Administration",
maxConnectionsPerEventLoop: Int = 1,
connectionPoolTimeout: TimeAmount = .seconds(10),
sqlLogLevel: Logger.Level = .debug) async throws {
app.databases.use(DatabaseConfigurationFactory.postgres(configuration: .init (hostname: Environment.get("DATABASE_HOST") ?? "localhost",
port: Environment.get("DATABASE_PORT").flatMap(Int.init(_:)) ?? SQLPostgresConfiguration.ianaPortNumber,
username: Environment.get("DATABASE_USERNAME") ?? "sampleapp",
password: Environment.get("DATABASE_PASSWORD") ?? "sampleapp_password",
database: Environment.get("DATABASE_NAME") ?? "sampleapp",
tls: .prefer(try .init(configuration: .clientDefault)))
tls: .prefer(try .init(configuration: .clientDefault))),
maxConnectionsPerEventLoop: maxConnectionsPerEventLoop,
connectionPoolTimeout: connectionPoolTimeout,
sqlLogLevel: sqlLogLevel
), as: .psql)
_ = try Environment.baseURL

View File

@ -49,8 +49,8 @@ extension ManagedUser {
TRUE)
RETURNING "id"
)
INSERT INTO "user_tokens" ("user_id", "token")
SELECT "id", \(bind: token)
INSERT INTO "user_tokens" ("user_id", "token", "realm")
SELECT "id", \(bind: token), 'invite'
FROM created
""")
.run()
@ -72,8 +72,8 @@ extension ManagedUser {
FROM "created"
CROSS JOIN unnest (\(bind: roles)) AS "role_name"
)
INSERT INTO "user_tokens" ("user_id", "token")
SELECT "id", \(bind: token)
INSERT INTO "user_tokens" ("user_id", "token", "realm")
SELECT "id", \(bind: token), 'invite'
FROM "created"
""")
.run()
@ -121,8 +121,8 @@ extension ManagedUser {
public static func store (token: String, userId: UUID, on connection: any SQLDatabase) async throws {
try await connection.raw("""
INSERT INTO "user_tokens" ("user_id", "token")
VALUES (\(bind: userId), \(bind: token))
INSERT INTO "user_tokens" ("user_id", "token", "realm")
VALUES (\(bind: userId), \(bind: token), 'forgot')
""")
.run()
}

View File

@ -30,7 +30,9 @@ struct UserToken: Decodable {
JOIN "users"
ON "users"."id" = "user_tokens"."user_id"
WHERE "token" = \(bind: token)
AND "insert_time" >= CURRENT_TIMESTAMP - INTERVAL '1 HOUR'
AND "insert_time" >= CURRENT_TIMESTAMP - CASE WHEN "realm" = 'invite'
THEN INTERVAL '1 DAY'
ELSE INTERVAL '1 HOUR' END
""")
.first (decoding: Token.self)
}

View File

@ -9,6 +9,8 @@ struct AuthorizationTests {
private func withApp(_ test: (Application) async throws -> ()) async throws {
let app = try await Application.make (.testing)
do {
setenv ("BASE_URL", "http://localhost", 0)
setenv ("EMAIL_SENDER", "nobody@example.com", 0)
try await SampleApp.configure (app)
let mockDatabase = MockDatabase (eventLoop: app.eventLoopGroup.next())
app.storage[Application.MockDatabaseKey.self] = mockDatabase