diff options
Diffstat (limited to 'dynamic')
| -rw-r--r-- | dynamic/README.md | 16 | ||||
| -rw-r--r-- | dynamic/api.scm | 80 | ||||
| -rw-r--r-- | dynamic/capabilities/comment-form.scm | 33 | ||||
| -rw-r--r-- | dynamic/capabilities/comments.scm | 152 | ||||
| -rw-r--r-- | dynamic/capabilities/gallery.scm | 111 | ||||
| -rw-r--r-- | dynamic/capabilities/rsvp.scm | 277 | ||||
| -rw-r--r-- | dynamic/captcha.scm | 170 | ||||
| -rw-r--r-- | dynamic/import-images.sh | 16 | ||||
| -rw-r--r-- | dynamic/logging.scm | 37 | ||||
| -rw-r--r-- | dynamic/schema-comments.sql | 16 | ||||
| -rw-r--r-- | dynamic/schema-gallery.sql | 18 | ||||
| -rw-r--r-- | dynamic/schema-rsvp.sql | 34 | ||||
| -rw-r--r-- | dynamic/util.scm | 69 |
13 files changed, 0 insertions, 1029 deletions
diff --git a/dynamic/README.md b/dynamic/README.md deleted file mode 100644 index 0f64827..0000000 --- a/dynamic/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# Dynamic API for jakob.space - -This is a Guile back-end for all dynamic capabilities on jakob.space. It is -assumed that the web server proxies all requests matching a `/api` prefix to -this server. - -## Dependencies - -Depending on who you ask, the package management situation for Guile is either -disappointing, or a pleasant reminder of simpler times. This module leverages -two Guile modules which, to my knowledge, are not packaged in the typical Guile -extension fashion. The respective `.scm` files will need to be downloaded and -added to Guile load path. - -- [base64 from guile-lib](https://github.com/jacobrec/guile-lib/blob/master/base64.scm) -- [squee](https://notabug.org/cwebber/guile-squee/) diff --git a/dynamic/api.scm b/dynamic/api.scm deleted file mode 100644 index 451c5c6..0000000 --- a/dynamic/api.scm +++ /dev/null @@ -1,80 +0,0 @@ -;;; Copyright © 2019 - 2022 Jakob L. Kreuze <zerodaysfordays@sdf.org> -;;; -;;; This program is free software; you can redistribute it and/or -;;; modify it under the terms of the GNU General Public License as -;;; published by the Free Software Foundation; either version 3 of the -;;; License, or (at your option) any later version. -;;; -;;; This program is distributed in the hope that it will be useful, -;;; but WITHOUT ANY WARRANTY; without even the implied warranty of -;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -;;; General Public License for more details. -;;; -;;; You should have received a copy of the GNU General Public License -;;; along with this program. If not, see -;;; <http://www.gnu.org/licenses/>. - -(use-modules (dynamic capabilities comment-form) - (dynamic capabilities comments) - (dynamic capabilities gallery) - (dynamic capabilities rsvp) - (dynamic logging) - (srfi srfi-1) - (ice-9 match) - (web server) - (web request) - (web response) - (web uri)) - -(define (not-found request) - "Build a (somewhat) descriptive response for a non-existent resource." - (values (build-response #:code 404) - (string-append "Resource not found: " - (uri->string (request-uri request))))) - -(define (handle-api-request request body endpoint) - "Route handler for the API server." - (let ((method (request-method request)) - (originating-ip (assoc-ref (request-headers request) 'X-Forwarded-For)) - (args (uri-query (request-uri request)))) - (log-append! 'info (format #f "~a ~a (~a) (~a)" method endpoint args originating-ip))) - ((match (cons (request-method request) endpoint) - ('(GET "dynamic" "comment-form") get-comment-form) - ('(GET "challenge") make-challenge) - ('(GET "api" "comments") get-comments) - ('(POST "api" "comment") put-comment) - ('(POST "api" "react") put-reaction) - ('(GET "api" "gallery") get-gallery) - ('(GET "api" "gallery" "image") get-image) - ('(GET "api" "rsvp" "event-info") get-event-info) - ('(POST "api" "rsvp") post-event-rsvp) - (_ (lambda (. args) (not-found request)))) - request body)) - -(define (main-request-handler request body) - "Server entry-point; parse `request' and defer to routing system." - (define (wrap-response response) - ;; This is either a response, or an alist of headers. The latter case is - ;; simple to handle, but the former requires us to do a (rather unweildy) - ;; copy of the response to inject our headers. - (if (response? response) - (build-response - #:version (response-version response) - #:code (response-code response) - #:reason-phrase (response-reason-phrase response) - #:headers (cons '(Access-Control-Allow-Origin . "*") - (response-headers response)) - #:port (response-port response) - #:validate-headers? #t) - (cons '(Access-Control-Allow-Origin . "*") response))) - (let* ((path-encoded (uri-path (request-uri request))) - (path (split-and-decode-uri-path path-encoded))) - (define-values (response resp-body) - (if (or (string= "api" (first path)) - (string= "dynamic" (first path))) - ;; (handle-api-request request body (drop path 1)) - (handle-api-request request body path) - (not-found request))) - (values (wrap-response response) resp-body))) - -(run-server main-request-handler 'http `(#:addr ,INADDR_ANY #:port 8080)) diff --git a/dynamic/capabilities/comment-form.scm b/dynamic/capabilities/comment-form.scm deleted file mode 100644 index beded53..0000000 --- a/dynamic/capabilities/comment-form.scm +++ /dev/null @@ -1,33 +0,0 @@ -;;; Copyright © 2019 - 2022 Jakob L. Kreuze <zerodaysfordays@sdf.org> -;;; -;;; This program is free software; you can redistribute it and/or -;;; modify it under the terms of the GNU General Public License as -;;; published by the Free Software Foundation; either version 3 of the -;;; License, or (at your option) any later version. -;;; -;;; This program is distributed in the hope that it will be useful, -;;; but WITHOUT ANY WARRANTY; without even the implied warranty of -;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -;;; General Public License for more details. -;;; -;;; You should have received a copy of the GNU General Public License -;;; along with this program. If not, see -;;; <http://www.gnu.org/licenses/>. - -(define-module (dynamic capabilities comment-form) - #:use-module (dynamic util) - #:use-module (haunt html) - #:use-module (ice-9 match) - #:use-module (jakob theme) - #:use-module (json) - #:use-module (web request) - #:use-module (web response) - #:use-module (web uri) - #:export (get-comment-form)) - -(define (get-comment-form request body) - "API endpoint handler for querying for the comments on a particular post - -This is a wrapper around `get-comments-by-slug'." - (values '((content-type . (text/html))) - (sxml->html-string (theme #:content '(p "Hello, world!"))))) diff --git a/dynamic/capabilities/comments.scm b/dynamic/capabilities/comments.scm deleted file mode 100644 index 945e382..0000000 --- a/dynamic/capabilities/comments.scm +++ /dev/null @@ -1,152 +0,0 @@ -;;; Copyright © 2019 - 2022 Jakob L. Kreuze <zerodaysfordays@sdf.org> -;;; -;;; This program is free software; you can redistribute it and/or -;;; modify it under the terms of the GNU General Public License as -;;; published by the Free Software Foundation; either version 3 of the -;;; License, or (at your option) any later version. -;;; -;;; This program is distributed in the hope that it will be useful, -;;; but WITHOUT ANY WARRANTY; without even the implied warranty of -;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -;;; General Public License for more details. -;;; -;;; You should have received a copy of the GNU General Public License -;;; along with this program. If not, see -;;; <http://www.gnu.org/licenses/>. - -(define-module (dynamic capabilities comments) - #:use-module (dynamic util) - #:use-module (ice-9 match) - #:use-module (json) - #:use-module (squee) - #:use-module (web request) - #:use-module (web response) - #:use-module (web uri) - #:export (get-comments - get-comments-by-slug - put-comment - put-reaction)) - -(define conn (connect-to-postgres-paramstring "dbname=jakob_comments")) - -(define (get-comments-by-slug slug) - "Internal function for querying the approved comments on a post - -This interface exists for dynamically generating the comment view from Haunt." - (define (format-comment comment) - (match comment - ((id name subject email comment url reactions) - `((id . ,id) - (name . ,name) - (subject . ,subject) - (email . ,email) - (comment . ,comment) - (url . ,url) - (reactions . ,(if reactions - (with-input-from-string reactions read) - '())))))) - (let* ((query "SELECT id, name, subject, email, comment, url, reactions - FROM comments WHERE slug = $1 and approved IS NOT NULL") - (result (exec-query conn query (list slug)))) - (map format-comment result))) - -(define (get-comments request body) - "API endpoint handler for querying for the comments on a particular post - -This is a wrapper around `get-comments-by-slug'." - (let* ((query-string (uri-query (request-uri request))) - (params (if query-string - (decode-form query-string) - '())) - (slug (assoc-ref params "p"))) - (if slug - (values '((content-type . (application/json))) - (scm->json-string - (list->vector - (get-comments-by-slug (car slug))))) - (values (build-response #:code 400) - (scm->json-string - `((success . #f) - (error . "missing `slug' query parameter"))))))) - - - -(define (put-comment request body) - "API endpoint handler for submitting a comment" - (define (valid-comment? form-data) - (and (assoc "slug" form-data) - (assoc "name" form-data) - (assoc "comment" form-data))) - (define (insert-comment form-data) - (exec-query conn - "INSERT INTO comments (submitted, slug, name, subject, - email, url, comment) - VALUES (now(), $1, $2, $3, $4, $5, $6);" - (list (assoc-value form-data "slug") - (assoc-value form-data "name") - (assoc-value form-data "subject") - (assoc-value form-data "email") - (assoc-value form-data "url") - (assoc-value form-data "comment"))) - (values '((content-type . (application/json))) - (scm->json-string `((success . #t))))) - (let ((form-data (decode-form body))) - (if (valid-comment? form-data) - (insert-comment form-data) - (values (build-response #:code 400) - (scm->json-string - `((success . #f) - (error . "missing `slug', `name', or `comment'"))))))) - - - -(define (add-reaction reactions reaction) - (with-output-to-string - (lambda () - (let ((parsed (call-with-input-string reactions read))) - (write (acons-normalize reaction - (if (assoc reaction parsed) (+ 1 (assoc-value parsed reaction)) 1) - parsed)))))) - -(define (put-reaction request body) - (define (set-reactions id reactions) - (exec-query conn "UPDATE comments SET reactions = $1 WHERE id = $2" - (list reactions id))) - (define (comment-reactions id) - (let* ((query "SELECT reactions FROM comments WHERE id = $1") - (result (exec-query conn query (list id)))) - ;; It could be NULL, in which case we want the empty list instead. - (if (positive? (length result)) (or (caar result) "()") #f))) - (define (valid-reaction? form-data) - (and (assoc "id" form-data) - (assoc "reaction" form-data))) - (let* ((query-string (uri-query (request-uri request))) - (form-data (if query-string - (decode-form query-string) - '()))) - (if (valid-reaction? form-data) - (let ((id (assoc-value form-data "id")) - (reaction (assoc-value form-data "reaction")) - (reactions (comment-reactions id))) - (if reactions - (begin - (set-reactions id (add-reaction reactions reaction)) - (values '((content-type . (application/json))) - (scm->json-string `((success . #t))))) - (values (build-response #:code 400) - (scm->json-string - `((success . #f) - (error . "no such comment")))))) - (values (build-response #:code 400) - (scm->json-string - `((success . #f) - (error . "missing `id', or `reaction'"))))))) - -;; (define (make-challenge request body) -;; (let-values (((uuid value image) (new-captcha))) -;; (hash-set! challenges uuid value) -;; (hash-for-each (lambda (x y) (display x) (newline)) challenges) -;; (values `((content-type . (application/base64)) -;; (access-control-allow-origin . "*") -;; (x-captcha-id . ,uuid)) -;; (base64-encode image)))) diff --git a/dynamic/capabilities/gallery.scm b/dynamic/capabilities/gallery.scm deleted file mode 100644 index 1d63061..0000000 --- a/dynamic/capabilities/gallery.scm +++ /dev/null @@ -1,111 +0,0 @@ -;;; Copyright © 2019 - 2022 Jakob L. Kreuze <zerodaysfordays@sdf.org> -;;; -;;; This program is free software; you can redistribute it and/or -;;; modify it under the terms of the GNU General Public License as -;;; published by the Free Software Foundation; either version 3 of the -;;; License, or (at your option) any later version. -;;; -;;; This program is distributed in the hope that it will be useful, -;;; but WITHOUT ANY WARRANTY; without even the implied warranty of -;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -;;; General Public License for more details. -;;; -;;; You should have received a copy of the GNU General Public License -;;; along with this program. If not, see -;;; <http://www.gnu.org/licenses/>. - -(define-module (dynamic capabilities gallery) - #:use-module (dynamic util) - #:use-module (ice-9 binary-ports) - #:use-module (ice-9 ftw) - #:use-module (ice-9 match) - #:use-module (json) - #:use-module (squee) - #:use-module (srfi srfi-1) - #:use-module (web request) - #:use-module (web response) - #:use-module (web uri) - #:export (get-gallery get-image)) - -(define conn (connect-to-postgres-paramstring "dbname=jakob_gallery")) - -;; How many bytes of entropy to use when generating vanity ID's. -(define %vanity-length (make-parameter 9)) - -;; Path where gallery images are stored. -(define %gallery-image-directory (make-parameter "/home/jakob/gallery-images/")) - -(define (valid-gallery-code code) - "Check database to see if `code' names a nonempty gallery." - (and (= (string-length code) (base64-length (%vanity-length))) - (positive? - (length - (exec-query conn "SELECT * FROM images WHERE vanity = $1" - (list code)))))) - -(define (get-gallery-images code) - "Handler for enumerating the image in a gallery." - (define (format-image image) - (match image - ((title filename thumbnail datetime) - `((title . ,title) - (filename . ,filename) - (thumbnail . ,thumbnail) - (datetime . ,datetime))))) - (let* ((images (exec-query conn "SELECT title, filename, thumb_filename, datetime FROM images WHERE vanity = $1" (list code)))) - (list->vector (map format-image images)))) - -(define (get-gallery-info code) - "Handler for enumerating the image in a gallery." - (define (format-gallery info) - (match info - ((title description datetime) - `((title . ,title) - (description . ,description) - (datetime . ,datetime))))) - (let* ((info (exec-query conn "SELECT title, description, datetime FROM galleries WHERE vanity = $1" (list code)))) - (format-gallery (car info)))) - -(define (get-gallery request body) - (let* ((query-string (uri-query (request-uri request))) - (params (if query-string - (decode-form query-string) - '())) - (code (car (assoc-ref params "g")))) - (if (valid-gallery-code code) - (values '((content-type . (application/json))) - (scm->json-string `((info . ,(get-gallery-info code)) - (images . ,(get-gallery-images code))))) - (values (build-response #:code 400) - (scm->json-string - `((success . #f) - (error . "Invalid gallery code"))))))) - -(define (image-exists? file-name) - (define (string/= a b) (not (string= a b))) - (and (string/= file-name ".") - (string/= file-name "..") - (member file-name (scandir (%gallery-image-directory))))) - -(define (read-image file-name) - (let* ((ext (string-downcase (last (string-split file-name #\.)))) - (mime (cond ((string= ext "jpg") 'image/jpeg) - ((string= ext "png") 'image/png) - (else (error "Unknown MIME type."))))) - (values `((content-type . (,mime))) - (call-with-input-file (format #f "~a/~a" (%gallery-image-directory) file-name) - (lambda (port) - (get-bytevector-all port)))))) - -(define (get-image request body) - (let* ((query-string (uri-query (request-uri request))) - (params (if query-string - (decode-form query-string) - '())) - (file-name (car (assoc-ref params "name")))) - (if (image-exists? file-name) - (read-image file-name) - (values (build-response #:code 400) - (scm->json-string - `((success . #f) - (error . "Invalid filename"))))))) diff --git a/dynamic/capabilities/rsvp.scm b/dynamic/capabilities/rsvp.scm deleted file mode 100644 index 4ac2eff..0000000 --- a/dynamic/capabilities/rsvp.scm +++ /dev/null @@ -1,277 +0,0 @@ -;;; Copyright © 2019 - 2022 Jakob L. Kreuze <zerodaysfordays@sdf.org> -;;; -;;; This program is free software; you can redistribute it and/or -;;; modify it under the terms of the GNU General Public License as -;;; published by the Free Software Foundation; either version 3 of the -;;; License, or (at your option) any later version. -;;; -;;; This program is distributed in the hope that it will be useful, -;;; but WITHOUT ANY WARRANTY; without even the implied warranty of -;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -;;; General Public License for more details. -;;; -;;; You should have received a copy of the GNU General Public License -;;; along with this program. If not, see -;;; <http://www.gnu.org/licenses/>. - -(define-module (dynamic capabilities rsvp) - #:use-module (base64) - #:use-module (dynamic util) - #:use-module (ice-9 binary-ports) - #:use-module (ice-9 match) - #:use-module (json) - #:use-module (rnrs bytevectors) - #:use-module (squee) - #:use-module (srfi srfi-1) - #:use-module (srfi srfi-9) - #:use-module (web request) - #:use-module (web response) - #:use-module (web uri) - #:export (get-event-info post-event-rsvp)) - -;; How many bytes of entropy to use when generating vanity ID's. -(define %vanity-length (make-parameter 9)) - -;; Path where event header images are stored. -(define %event-image-path-fmt (make-parameter "/home/jakob/event-images/~a.png")) - -;; Global handle to the RSVP database. -(define conn (connect-to-postgres-paramstring "dbname=jakob_rsvp")) - - - -(define (generate-vanity-code) - "Generate a random vanity ID. - -A vanity ID is used in the RSVP system for creating unique URLs for invitations. -It is a base64 string, encoding `%vanity-length' bytes of randomness." - (call-with-input-file "/dev/urandom" - (lambda (port) (base64-encode (get-bytevector-n port 9))))) - -(define (valid-invite-code invitation) - "Check database to see if `invitation' exists." - (and (= (string-length invitation) (base64-length (%vanity-length))) - (positive? - (length - (exec-query conn "SELECT * FROM invitations WHERE vanity = $1" - (list invitation)))))) - -(define (valid-receipt-code receipt) - "Check database to see if `receipt'." - (and (= (string-length receipt) (base64-length (%vanity-length))) - (positive? - (length - (exec-query conn "SELECT * FROM rsvps WHERE vanity = $1" - (list receipt)))))) - - - -(define-record-type <rsvp-create> - (make-rsvp-create-parameters) - rsvp-create-parameters? - (invitation-code rsvp-create-code set-rsvp-create-code!) - (name rsvp-create-name set-rsvp-create-name!) - (email rsvp-create-email set-rsvp-create-email!) - (attending rsvp-create-attending set-rsvp-create-attending!) - (guests rsvp-create-guests set-rsvp-create-guests!)) - -(define (params->rsvp-create params) - "Parse `params', an alist, into a `<rsvp-create>'." - (let ((res (make-rsvp-create-parameters))) - (set-rsvp-create-code! res (assoc-ref params "id")) - (set-rsvp-create-name! res (assoc-ref params "name")) - (set-rsvp-create-email! res (assoc-ref params "email")) - (set-rsvp-create-attending! res (assoc-ref params "rsvp")) - (set-rsvp-create-guests! res (assoc-ref params "guests")) - (if (any not - (list (rsvp-create-code res) - (rsvp-create-name res) - (rsvp-create-email res) - (rsvp-create-attending res) - (rsvp-create-guests res))) - #f - res))) - -(define (invitation->event-id vanity-code) - "For valid `vanity-code', find the corresponding event ID and capabilities." - (car - (exec-query conn "SELECT event_id, capabilities FROM invitations WHERE vanity = $1" - (list vanity-code)))) - -(define (create-new-event-rsvp params) - "Handler for RSVP'ing to an event." - (let ((params (params->rsvp-create params))) - (cond ((not params) - (values (build-response #:code 400) - (scm->json-string - `((success . #f) - (error . "Invalid form data"))))) - ((not (valid-invite-code (rsvp-create-code params))) - (values (build-response #:code 400) - (scm->json-string - `((success . #f) - (error . "Invalid invitation code"))))) - (else - (let ((receipt-code (generate-vanity-code)) - (event-id (car (invitation->event-id (rsvp-create-code params))))) - (exec-query conn - "INSERT INTO rsvps (vanity, invitation_id, event_id, fullname, email, attending, guests) VALUES ($1, $2, $3, $4, $5, $6, $7)" - (list receipt-code - (rsvp-create-code params) - event-id - (rsvp-create-name params) - (rsvp-create-email params) - (rsvp-create-attending params) - (rsvp-create-guests params))) - (values '((content-type . (application/json))) - (scm->json-string - `((receipt . ,receipt-code))))))))) - - - -(define-record-type <rsvp-update> - (make-rsvp-update-parameters) - rsvp-update-parameters? - (invitation-code rsvp-update-code set-rsvp-update-code!) - (name rsvp-update-name set-rsvp-update-name!) - (email rsvp-update-email set-rsvp-update-email!) - (attending rsvp-update-attending set-rsvp-update-attending!) - (guests rsvp-update-guests set-rsvp-update-guests!)) - -(define (params->rsvp-update params) - "Parse `params', an alist, into a `<rsvp-update>'." - (let ((res (make-rsvp-update-parameters))) - (set-rsvp-update-code! res (assoc-ref params "update")) - (set-rsvp-update-name! res (assoc-ref params "name")) - (set-rsvp-update-email! res (assoc-ref params "email")) - (set-rsvp-update-attending! res (assoc-ref params "rsvp")) - (set-rsvp-update-guests! res (assoc-ref params "guests")) - (if (any not - (list (rsvp-update-code res) - (rsvp-update-name res) - (rsvp-update-email res) - (rsvp-update-attending res) - (rsvp-update-guests res))) - #f - res))) - -(define (update-event-rsvp params) - "Handler for updating an RSVP to an event." - (let ((params (params->rsvp-update params))) - (cond ((not params) - (values (build-response #:code 400) - (scm->json-string - `((success . #f) - (error . "Invalid form data"))))) - ((not (valid-receipt-code (rsvp-update-code params))) - (values (build-response #:code 400) - (scm->json-string - `((success . #f) - (error . "Invalid receipt code"))))) - (else - (exec-query conn - "UPDATE rsvps SET fullname = $2, email = $3, attending = $4, guests = $5 WHERE vanity = $1" - (list - (rsvp-update-code params) - (rsvp-update-name params) - (rsvp-update-email params) - (rsvp-update-attending params) - (rsvp-update-guests params))) - (values '((content-type . (application/json))) - (scm->json-string - `((receipt . ,(rsvp-update-code params))))))))) - - - -(define (post-event-rsvp request body) - "Entry point for RSVP create/update. We dispatch on the parameters." - (let* ((params (json-string->scm (utf8->string body)))) - (cond ((assoc-ref params "id") (create-new-event-rsvp params)) - ((assoc-ref params "update") (update-event-rsvp params)) - (else (values (build-response #:code 400) - (scm->json-string - `((success . #f) - (error . "Invalid invite/update code")))))))) - - - -(define (get-event-image event-id) - "Return, as base64, the header image for `event-id'." - (call-with-input-file (format #f (%event-image-path-fmt) event-id) - (lambda (port) - (base64-encode (get-bytevector-all port))))) - -(define (get-event-invitation invitation-code) - "Handler for reading information about an event." - (define (format-rsvp rsvp) - (match rsvp - ((name email attending guests) - `((name . ,name) - (email . ,email) - (attending . ,attending) - (guests . ,guests))))) - (let* ((invitation (invitation->event-id invitation-code)) - (capabilities (cadr invitation)) - (event (exec-query conn "SELECT * FROM events WHERE id = $1" (list (car invitation)))) - (rsvps (exec-query conn "SELECT fullname, email, attending, guests FROM rsvps WHERE event_id = $1" (list (car invitation))))) - (match (car event) - ((i_ title description date location) - (values '((content-type . (application/json))) - (scm->json-string - `((title . ,title) - (description . ,description) - (image . ,(get-event-image (car invitation))) - (date . ,date) - (location . ,location) - ,@(if (= 1 (logand (string->number capabilities) 1)) - `((rsvps . ,(list->vector (map format-rsvp rsvps)))) - '())))))))) - -(define (get-event-receipt receipt-code) - "Handler for reading information about an event, with receipt info." - (define (format-rsvp rsvp) - (match rsvp - ((name email attending guests) - `((name . ,name) - (email . ,email) - (attending . ,attending) - (guests . ,guests))))) - (let* ((rsvp (exec-query conn "SELECT invitation_id, fullname, email, attending, guests FROM rsvps WHERE vanity = $1" (list receipt-code))) - (invitation (invitation->event-id (caar rsvp))) - (capabilities (cadr invitation)) - (event (exec-query conn "SELECT * FROM events WHERE id = $1" (list (car invitation)))) - (rsvps (exec-query conn "SELECT fullname, email, attending, guests FROM rsvps WHERE event_id = $1" (list (car invitation))))) - (match (car event) - ((i_ title description date location) - (values '((content-type . (application/json))) - (scm->json-string - `((title . ,title) - (description . ,description) - (image . ,(get-event-image (car invitation))) - (date . ,date) - (location . ,location) - (name . ,(list-ref (car rsvp) 1)) - (email . ,(list-ref (car rsvp) 2)) - (attending . ,(list-ref (car rsvp) 3)) - (guests . ,(list-ref (car rsvp) 4)) - ,@(if (= 1 (logand (string->number capabilities) 1)) - `((rsvps . ,(list->vector (map format-rsvp rsvps)))) - '())))))))) - -(define (get-event-info request body) - "Entry point to `get-event-receipt'/`get-event-invitation'." - (let* ((query-string (uri-query (request-uri request))) - (params (if query-string - (decode-form query-string) - '())) - (invitation-code (assoc-ref params "i")) - (receipt-code (assoc-ref params "r"))) - (cond ((and receipt-code (valid-receipt-code (car receipt-code))) - (get-event-receipt (car receipt-code))) - ((and invitation-code (valid-invite-code (car invitation-code))) - (get-event-invitation (car invitation-code))) - (else - (values (build-response #:code 400) - (scm->json-string - `((success . #f) - (error . "Invalid invitation or receipt code")))))))) diff --git a/dynamic/captcha.scm b/dynamic/captcha.scm deleted file mode 100644 index b095ebf..0000000 --- a/dynamic/captcha.scm +++ /dev/null @@ -1,170 +0,0 @@ -;;; Copyright © 2019 - 2022 Jakob L. Kreuze <zerodaysfordays@sdf.org> -;;; -;;; This program is free software; you can redistribute it and/or -;;; modify it under the terms of the GNU General Public License as -;;; published by the Free Software Foundation; either version 3 of the -;;; License, or (at your option) any later version. -;;; -;;; This program is distributed in the hope that it will be useful, -;;; but WITHOUT ANY WARRANTY; without even the implied warranty of -;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -;;; General Public License for more details. -;;; -;;; You should have received a copy of the GNU General Public License -;;; along with this program. If not, see -;;; <http://www.gnu.org/licenses/>. - -(define-module (captcha) - #:use-module (base64) - #:use-module (gcrypt hash) - #:use-module (gcrypt mac) - #:use-module (gcrypt random) - #:use-module (ice-9 binary-ports) - #:use-module (ice-9 iconv) - #:use-module (ice-9 local-eval) - #:use-module (ice-9 match) - #:use-module (ice-9 popen) - #:use-module (ice-9 rdelim) - #:use-module (ice-9 threads) - #:use-module (rnrs bytevectors) - #:use-module (srfi srfi-1) - #:use-module (srfi srfi-19) - #:export (new-captcha)) - -(define proc-mutex (make-mutex)) - -(define (random-term) - (match (random 5) - (0 `(* ,(+ 1 (random 10)) x)) - (1 `(* ,(+ 1 (random 10)) (expt x ,(random 10)))) - (2 `(* ,(+ 1 (random 10)) (exp x))) - (3 `(* ,(+ 1 (random 10)) (cos x))) - (4 `(* ,(+ 1 (random 10)) (sin x))))) - -(define (sexp->latex sexp) - (match sexp - (('+ rest ...) (string-join (map sexp->latex rest) " + ")) - (('* rest ...) (string-join (map sexp->latex rest) " \\cdot ")) - (('sin term) (format #f "\\sin(~a)" (sexp->latex term))) - (('cos term) (format #f "\\cos(~a)" (sexp->latex term))) - (('expt term n) (format #f "~a^{~a}" (sexp->latex term) (sexp->latex n))) - (('exp term) (format #f "e^{~a}" (sexp->latex term))) - ('x "x") - (n (cond ((and (number? n) (positive? n)) (format #f "~a" n)) - ((and (number? n) (negative? n)) (format #f "(~a)" n)) - ((number? n) "0") - (else (error "Do not know how to convert to latex." n)))))) - -(define (differentiate-sexp sexp) - (match sexp - (('+ rest ...) `(+ ,@(map differentiate-sexp rest))) - (('* coeff term) (if (number? coeff) - `(* ,coeff ,(differentiate-sexp term)) - (error "Do not know how to differentiate."))) - (('sin term) `(* ,(differentiate-sexp term) (cos ,term))) - (('cos term) `(* -1 ,(differentiate-sexp term) (sin ,term))) - (('exp term) `(* ,(differentiate-sexp term) (exp ,term))) - (('expt term n) `(* ,n (expt ,term ,(- n 1)))) - ('x 1) - (n (if (number? n) - 0 - (error "Do not know how to differentiate."))))) - -(define (simplify-sexp sexp) - (match sexp - (('+ rest ...) `(+ ,@(map simplify-sexp rest))) - (('* 1 term) (simplify-sexp term)) - (('* 1 rest ...) (simplify-sexp `(* ,@rest))) - (('sin term) `(sin ,(simplify-sexp term))) - (('sin term) `(cos ,(simplify-sexp term))) - (('exp term) `(exp ,(simplify-sexp term))) - (('expt term 1) (simplify-sexp term)) - (('expt term n) `(expt ,(simplify-sexp term) ,(simplify-sexp n))) - (term term))) - -(define (random-expression) - (let ((n-terms (+ 2 (random 3)))) - `(+ ,@(map (lambda (x) (random-term)) (iota n-terms))))) - -(define (latex->image src) - (chdir "/tmp") - (with-mutex proc-mutex - (call-with-output-file "formula.tex" - (lambda (port) - (format port "\\def\\formula{~a} -\\documentclass[border=2pt]{standalone} -\\usepackage{amsmath} -\\usepackage{varwidth} -\\begin{document} -\\begin{varwidth}{\\linewidth} -\\[ \\formula \\] -\\end{varwidth} -\\end{document} -" src))) - (unless (eqv? 0 (status:exit-val (system "pdflatex formula.tex"))) - (error "Cannot generate PDF")) - (let* ((port (open-input-pipe "convert -density 300 formula.pdf -quality 90 png:-")) - (data (get-bytevector-all port))) - (unless (eqv? 0 (status:exit-val (close-pipe port))) - (error "Cannot generate PNG")) - data))) - -(define (new-uuid) - (with-mutex proc-mutex - (let* ((port (open-input-pipe "uuidgen")) - (str (read-line port))) - (close-pipe port) - str))) - -(define (new-captcha) - (let* ((lower-bound (random 10)) - (upper-bound (+ lower-bound 1 (random 9))) - (expression (random-expression)) - (latex-src (sexp->latex (simplify-sexp (differentiate-sexp expression))))) - (values (new-uuid) - (- (local-eval expression (let ((x upper-bound)) (the-environment))) - (local-eval expression (let ((x lower-bound)) (the-environment)))) - (latex->image (format #f "\\int_{~a}^{~a} ~a \\, dx" - lower-bound - upper-bound - latex-src))))) - - - -;; How many zeroes the SHA-256 hash has to be prefixed by to be a valid proof of work. -(define %hardness 4) - -;; This is an ephemeral key. At this point, it doesn't make sense to store keys -;; locally, since the server process is singular and long-running. -(define %pow-mac-key (gen-random-bv 64)) - -(define (proof-of-work) - (define challenge - (call-with-input-file "/dev/urandom" - (lambda (port) (base64-encode (get-bytevector-n port 32))))) - (define expiry-timestamp - (date->string - (time-utc->date (make-time 'time-utc 0 (+ 512 (time-second (current-time))))) - "~Y-~m-~d ~H:~M:~S")) - (define challenge-signature - (sign-data-base64 %pow-mac-key challenge)) - (define timestamp-signature - (sign-data-base64 %pow-mac-key expiry-timestamp)) - (values challenge challenge-signature expiry-timestamp timestamp-signature)) - -(define (check-proof-of-work prefix - challenge challenge-signature - expiry-timestamp timestamp-signature) - (define hash-value - (chain (list prefix challenge) - (string-concatenate _) - (string->bytevector _ "utf8") - (bytevector-hash _ (lookup-hash-algorithm 'sha256)) - (bytevector->base16-string _))) - (define zero-prefix (string-join (map (lambda (_) "0") (iota %hardness)) "")) - (and (= 32 (string-length prefix)) - (string-prefix? zero-prefix hash-value) - (valid-base64-signature? %pow-mac-key challenge challenge-signature) - (valid-base64-signature? %pow-mac-key expiry-timestamp timestamp-signature) - (time<=? (current-time) - (date->time-utc (string->date expiry-timestamp "~Y-~m-~d ~H:~M:~S"))))) diff --git a/dynamic/import-images.sh b/dynamic/import-images.sh deleted file mode 100644 index 23f6130..0000000 --- a/dynamic/import-images.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env bash - -set -euo pipefail - -VANITY="$1" -shift - -for item in "$@"; do - filename=$(basename -- "$item") - extension="${filename##*.}" - filename="${filename%.*}" - uuid="$(uuidgen)" - cp "$item" "/home/jakob/gallery-images/$uuid.$extension" - convert "/home/jakob/gallery-images/$uuid.$extension" -thumbnail '100x100>' "/home/jakob/gallery-images/${uuid}_thumb.png" - psql jakob_gallery -c "INSERT INTO images (vanity, title, filename, thumb_filename, datetime) VALUES ('$VANITY', '$filename', '$uuid.$extension', '${uuid}_thumb.png', now());" -done diff --git a/dynamic/logging.scm b/dynamic/logging.scm deleted file mode 100644 index dab2464..0000000 --- a/dynamic/logging.scm +++ /dev/null @@ -1,37 +0,0 @@ -;;; Copyright © 2019 - 2022 Jakob L. Kreuze <zerodaysfordays@sdf.org> -;;; -;;; This program is free software; you can redistribute it and/or -;;; modify it under the terms of the GNU General Public License as -;;; published by the Free Software Foundation; either version 3 of the -;;; License, or (at your option) any later version. -;;; -;;; This program is distributed in the hope that it will be useful, -;;; but WITHOUT ANY WARRANTY; without even the implied warranty of -;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -;;; General Public License for more details. -;;; -;;; You should have received a copy of the GNU General Public License -;;; along with this program. If not, see -;;; <http://www.gnu.org/licenses/>. - -(define-module (dynamic logging) - #:use-module (ice-9 format) - #:use-module (srfi srfi-19) - #:export (log-append!)) - -(define %log-file-name (make-parameter "/var/log/jakob-dynamic.log")) -(define %log-level (make-parameter 'info)) - -(define (dominates message-level baseline-level) - "Determine if `a' should be shown for baseline log level `b'." - (define log-level-hierarchy '(debug info warn error)) - (>= (list-index log-level-hierarchy message-level) - (list-index log-level-hierarchy baseline-level))) - -(define (log-append! level message) - "Append `message', at `level', to the log buffer." - (when (dominates level (%log-level)) - (call-with-output-file (%log-file-name) - (lambda (port) - (let ((now (date->string (current-date) "~4"))) - (format port "[~a] ~a: ~a~%" now level message)))))) diff --git a/dynamic/schema-comments.sql b/dynamic/schema-comments.sql deleted file mode 100644 index b2cb652..0000000 --- a/dynamic/schema-comments.sql +++ /dev/null @@ -1,16 +0,0 @@ -CREATE TABLE comments( - id SERIAL PRIMARY KEY, - approved TIMESTAMP, - submitted TIMESTAMP NOT NULL, - slug VARCHAR(100) NOT NULL, - name VARCHAR(50) NOT NULL, - subject VARCHAR(100), - email VARCHAR(100), - url VARCHAR(100), - comment VARCHAR(1024) NOT NULL, - reactions VARCHAR(1024) -); - --- Use `now' for `submitted'. - --- INSERT INTO comments (submitted, slug, name, comment) VALUES (now(), 'test', 'Jakob', 'Hello, world!'); diff --git a/dynamic/schema-gallery.sql b/dynamic/schema-gallery.sql deleted file mode 100644 index bad4100..0000000 --- a/dynamic/schema-gallery.sql +++ /dev/null @@ -1,18 +0,0 @@ -CREATE TABLE IF NOT EXISTS galleries ( - id SERIAL, - vanity char(12) NOT NULL, - title varchar(128), - description varchar(4096) NOT NULL, - datetime timestamp with time zone NOT NULL, - PRIMARY KEY (id) -); - -CREATE TABLE IF NOT EXISTS images ( - id SERIAL, - vanity char(12) NOT NULL, - title varchar(128), - filename varchar(64) NOT NULL, - thumb_filename varchar(64) NOT NULL, - datetime timestamp with time zone NOT NULL, - PRIMARY KEY (id) -); diff --git a/dynamic/schema-rsvp.sql b/dynamic/schema-rsvp.sql deleted file mode 100644 index 3e6a21f..0000000 --- a/dynamic/schema-rsvp.sql +++ /dev/null @@ -1,34 +0,0 @@ -CREATE TABLE IF NOT EXISTS events ( - id SERIAL, - title varchar(128) NOT NULL, - description varchar(16384) NOT NULL, - datetime timestamp with time zone NOT NULL, - location varchar(128) NOT NULL, - PRIMARY KEY (id) -); - -CREATE TABLE IF NOT EXISTS invitations ( - id SERIAL, - vanity char(12) NOT NULL, - comments varchar(1024) NOT NULL, - created_on timestamp with time zone default current_timestamp, - capabilities bigint NOT NULL, - event_id integer NOT NULL, - PRIMARY KEY (id) -); - -CREATE TABLE IF NOT EXISTS rsvps ( - id SERIAL, - vanity char(12) NOT NULL, - invitation_id char(12) NOT NULL, - event_id bigint NOT NULL, - fullname varchar(128) NOT NULL, - email varchar(256) NOT NULL, - guests varchar(1024) NOT NULL, - attending varchar(32) NOT NULL, - PRIMARY KEY (id) -); - --- `rsvps` contains the bare minimum. If we later decide we need additional --- fields, we'll have an additional table mapping events.id to attribute names --- and rsvps.id to attribute values. diff --git a/dynamic/util.scm b/dynamic/util.scm deleted file mode 100644 index b2e7221..0000000 --- a/dynamic/util.scm +++ /dev/null @@ -1,69 +0,0 @@ -;;; Copyright © 2019 - 2022 Jakob L. Kreuze <zerodaysfordays@sdf.org> -;;; -;;; This program is free software; you can redistribute it and/or -;;; modify it under the terms of the GNU General Public License as -;;; published by the Free Software Foundation; either version 3 of the -;;; License, or (at your option) any later version. -;;; -;;; This program is distributed in the hope that it will be useful, -;;; but WITHOUT ANY WARRANTY; without even the implied warranty of -;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -;;; General Public License for more details. -;;; -;;; You should have received a copy of the GNU General Public License -;;; along with this program. If not, see -;;; <http://www.gnu.org/licenses/>. - -(define-module (dynamic util) - #:use-module (ice-9 match) - #:use-module (rnrs bytevectors) - #:use-module (srfi srfi-1) - #:use-module (srfi srfi-26) - #:use-module (web uri) - #:export (assoc-value - acons-normalize - base64-length - decode-form)) - -(define (assoc-value alist key) - "Return the `car' of `(assoc alist key)' if truthy" - (let ((result (assoc-ref alist key))) - (if result (car result) result))) - -(define (acons-list k v alist) - "Add V to K to alist as list" - (let ((value (assoc-ref alist k))) - (if value - (let ((alist (alist-delete k alist))) - (acons k (cons v value) alist)) - (acons k (list v) alist)))) - -(define (acons-normalize key value alist) - "Add KEY -> VALUE to ALIST such that no entries for KEY are duplicates" - (cons (cons key value) - (filter (lambda (pair) (not (equal? (car pair) key))) alist))) - -(define (list->alist lst) - "Build a alist of list based on a list of key and values. - - Multiple values can be associated with the same key" - (let next ((lst lst) - (out '())) - (if (null? lst) - out - (next (cdr lst) (acons-list (caar lst) (cdar lst) out))))) - -(define (decode-form bv) - "Convert BV querystring or form data to an alist" - (define string (if (string? bv) bv (utf8->string bv))) - (define pairs (map (cut string-split <> #\=) - ;; semi-colon and amp can be used as pair separator - (append-map (cut string-split <> #\;) - (string-split string #\&)))) - (list->alist (map (match-lambda - ((key value) - (cons (uri-decode key) (uri-decode value)))) pairs))) - -(define (base64-length n) - "The length of the base64 string encoding `n' bytes." - (inexact->exact (* 4 (ceiling (/ n 3.0))))) |