web.scm 16.2 KB
Newer Older
amirouche's avatar
amirouche committed
1
;;; Copyright © 2014       David Thompson <davet@gnu.org>
2
;;; Copyright © 2015-2018  Amirouche Boubekki <amirouche@hypermove.net>
amirouche's avatar
amirouche committed
3 4 5 6 7 8 9 10 11 12 13 14 15
;;
;; 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/>.
amirouche's avatar
amirouche committed
16
(define-module (culturia web))
amirouche's avatar
amirouche committed
17 18

;; stdlib
amirouche's avatar
amirouche committed
19
(use-modules ((ice-9 match)))
20 21
(use-modules ((rnrs bytevectors)))
(use-modules ((srfi srfi-1)))
amirouche's avatar
amirouche committed
22 23 24
(use-modules ((web request)))
(use-modules ((web server)))
(use-modules ((web uri)))
amirouche's avatar
amirouche committed
25

amirouche's avatar
amirouche committed
26 27 28
;; third party
(use-modules ((wiredtiger extra)))
(use-modules ((wiredtiger feature-space)))
29
(use-modules ((wiredtiger grf3) #:prefix grf3:))
amirouche's avatar
amirouche committed
30 31
(use-modules ((wiredtiger wiredtiger)))

32
;; wanna be guile modules
amirouche's avatar
amirouche committed
33 34 35 36 37 38 39 40
(use-modules ((culturia web decode)))
(use-modules ((culturia web helpers)))
(use-modules ((culturia web html)))
(use-modules ((culturia web lorem-ipsum)))
(use-modules ((culturia web mime-types)))
(use-modules ((culturia web static)))
(use-modules ((culturia web style)))
(use-modules ((culturia web validate)))
amirouche's avatar
amirouche committed
41

42
;; local
amirouche's avatar
amirouche committed
43 44 45 46
(use-modules ((culturia sha-2)))
(use-modules ((culturia argon2)))
(use-modules ((culturia app)))

47

amirouche's avatar
amirouche committed
48
(setlocale LC_ALL "")
amirouche's avatar
amirouche committed
49

50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
;;; sign

(define (make-hash string pepper)
  (let ((hash (make-sha-256)))
    (sha-256-update! hash (string->utf8 string))
    (sha-256-update! hash (string->utf8 pepper))
    (sha-256-finish! hash)
    (sha-256->string hash)))

(define (string-sign string pepper)
  (let ((hash (make-hash string pepper)))
    (string-append string "$" hash)))

(define (string-verify string pepper)
  (match (string-split string #\$)
    ((value signature)
     ;; TODO: subject to timing attack, use constant time comparison
     (if (string=? signature (make-hash value pepper)) value #f))
    (_ #f)))


;;; logging

(define (%log level) ;; TODO: add colors and env variable
  (lambda (message . args)
    (format #t "~a: ~a: " (current-time) level)
    (apply format #t message args)
    (newline)))

(define log-debug (%log 'debug))
(define log-info (%log 'info))

;;; wiredtiger helpers

(define (grf3:find key value) ;; TODO: move to wiredtiger
  (map grf3:get (fs:find key value)))

;;; alist helpers using equal?

(define (rm alist key)
  (alist-delete key alist))

(define (set alist key value)
  (acons key value (rm alist key)))

(define ref assoc-ref)

;; TODO: rm*

(define (ref* alist . keys)
  (let loop ((keys keys)
             (alist alist))
    (cond
     ((eq? alist #f) #f)
     ((null? keys) alist)
     (else (loop (cdr keys) (ref alist (car keys)))))))

(define (set* alist . args)
  (let* ((args* (reverse args))
         (value (car args*))
         (keys (reverse (cdr args*))))
    (let loop ((keys keys)
               (alist alist))
      (if (null? keys)
          value
          (set alist (car keys) (loop (cdr keys) (or (ref alist (car keys)) '())))))))

amirouche's avatar
amirouche committed
117 118
;;;

119
(define (template class body)
amirouche's avatar
amirouche committed
120 121 122 123
  `((doctype "html")
    (html
     (head
      (meta (@ (charset "utf-8")))
amirouche's avatar
amirouche committed
124
      (title "culturia")
amirouche's avatar
amirouche committed
125 126 127
      (link (@ (rel "stylesheet") (href "/static/normalize.css")))
      (link (@ (rel "stylesheet") (href "/static/main.css"))))
     (body
amirouche's avatar
amirouche committed
128 129
      (div (@ (id "header")))
      (div (@ (id "wrapper"))
130 131
           (div (@ (id "container")
                   (class ,class))
amirouche's avatar
amirouche committed
132 133
                ,body))
      (div (@ (id "footer")))))))
amirouche's avatar
amirouche committed
134

amirouche's avatar
amirouche committed
135 136 137 138
(define (random-tag uid)
  (let ((tag (lorem-ipsum 1)))
    `(span (@ (class "tag"))
           ,tag)))
139

amirouche's avatar
amirouche committed
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
(define (random-tags)
  (map random-tag (iota (+ 1 (random 3)))))

(define (random-post uid)
  `(a (@ (class "overview-item post")
         (href ,(string-append "/item/"
                               (number->string uid)
                               "/random-item-on-presence/")))
      (h2 ,(lorem-ipsum 5))
      (p (@ (class "overview-item-description"))
         "Published yesterday in " ,(random-tags))))

(define (random-message uid)
  `(a (@ (class "overview-item message")
         (href ,(string-append "/item/"
                               (number->string uid)
                               "/random-message-on-presence/")))
      (p ,(lorem-ipsum 20))
      (p (@ (class "overview-item-description"))
         "Published yesterday in " ,(random-tags))))

(define (random-link uid)
  `(a (@ (class "overview-item link")
         (href ,(string-append "/item/"
                               (number->string uid)
                               "/random-link-on-presence/")))
      (p ,(lorem-ipsum 7))
      (p (@ (class "overview-link-url")) "http://example.com/spam/egg/guile/win/")
      (p (@ (class "overview-item-description"))
         "Published yesterday in " ,(random-tags))))

(define (random-commit uid)
  `(a (@ (class "overview-item commit")
         (href ,(string-append "/commit/"
                               (number->string uid)
                               "/")))
      (p (code "1337decafbad42") " " ,(lorem-ipsum 7))
      (p (@ (class "overview-item-description"))
         "Published yesterday in presence")))

(define %items (list random-post
                     random-message
                     random-link
                     random-commit))

(define (random-item uid)
  ((list-ref %items (random (length %items))) uid))

amirouche's avatar
amirouche committed
188 189 190
(define (request-query request)
  (and=> ((compose uri-query request-uri) request) decode))

191
(define (query->maybe-response query user)
192 193
  (if (or (not query) (null? query))
      (values #f #f)
194
      (match query
195 196
        (("/signin") (redirect "/signin"))
        (("/signup") (redirect "/signup")))))
amirouche's avatar
amirouche committed
197

198 199 200 201 202 203 204 205 206 207 208 209
(define* (navigation/sxml #:key value autofocus)
  `(form (@ (id "navigation")
            (method "GET")
            (action "/"))
         (input (@ (id "query")
                   (name "query")
                   (type "text")
                   (value ,(or value ""))
                   ,@(if autofocus '((autofocus "")) '())))
         (input (@ (type "submit")
                   (value "submit")))))

210
(define (route/index app request)
211 212 213
  (let ((query (assoc-ref (request-query request) "query"))
        (user (request-user request app)))
    (call-with-values (lambda () (query->maybe-response query user))
amirouche's avatar
amirouche committed
214 215 216
      (lambda (header body)
        (if header
            (values header body)
217
            (sxml->response
amirouche's avatar
amirouche committed
218
             (template "overview"
219
               `(,(sxml/maybe (and user `((p "Héllo " ,(grf3:vertex-ref user 'user/username)))))
220
                 ,(navigation/sxml #:autofocus #t)
221 222 223
                 (div (@ (id "overview-intro"))
                      ,(lorem-ipsum 100))
                 ,(map random-item (iota 10))))))))))
224 225 226

;;; form helpers

227
(define* (form/input type name label value error #:key autofocus)
228 229 230 231 232
  `(div (@ (class ,(make-class `(("form-field" . #t)
                                 ("error" . ,error)))))
        (p (label (@ (for ,name)) ,label)
           (input (@ (type ,type)
                     (id ,name)
233
                     ,@(if autofocus '((autofocus "")) '())
234 235 236 237 238 239 240 241 242 243 244 245 246
                     (name ,name)
                     (value ,(if value (car value) ""))))
           ,(sxml/maybe (and error `(p (@ (class "error")) ,error))))))

(define (form/submit value)
  `(div (@ (class "form-field"))
        (p (@ (class "form-control"))
           (input (@ (type "submit") (value ,value))))))

;;; queries

(define (query-user-by-username username)
  "Return the vertex associated with USERNAME otherwise #f."
247 248 249 250 251
  (with-transaction
    (let ((out (grf3:find 'user/username username)))
      (if (null? out)
          #f
          (car out))))) ;; XXX: (user/username . username) must be unique
252 253

(define (query-user-by-uid uid)
254 255 256 257
  (with-transaction
    (and=> (grf3:get uid)
           (lambda (user)
             (and (eq? (grf3:vertex-ref user 'type) 'user) user)))))
258 259 260 261 262 263 264 265 266

(define (request-user request app)
  (and=> (assq-ref (request-cookies request) 'token)
         (lambda (token)
           (and=> (string-verify token (app-pepper app))
                  query-user-by-uid))))

;;; signin

267
(define (signin/sxml values errors)
268
  (template "signin"
269 270 271 272 273 274
    `(,(navigation/sxml #:value "/signin")
      (form (@ (method "POST"))
            ,(form/input "text"
                         "username"
                         "username"
                         (ref values "username")
275 276
                         (ref errors "username")
                         #:autofocus #t)
277 278 279 280 281 282
            ,(form/input "password"
                         "password"
                         "password"
                         #f
                         (ref errors "password"))
            ,(form/submit "submit")))))
amirouche's avatar
amirouche committed
283

284
(define (route/signin/get request)
285
  (sxml->response (signin/sxml '() '())))
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316

(define (required value)
  (and (or (not value)
           (< (string-length (car value)) 1))
       "this field is required."))


(define %signin-validator `(("username" . ,required)
                            ("password" . ,required)))

(define (signin/form-validate form)
  (validate %signin-validator form)) ;; shallow validation

(define (signin/signin app username password)
  (let ((user (query-user-by-username username)))
    (if user
        (if (verify* (grf3:vertex-ref user 'user/hash)
                     password
                     (app-pepper app))
            user
            #f)
        #f)))

(define (user-auth-token app user)
  ;; For privacy reasons, the user unique identifier (uid) is used to
  ;; build the authentication token. The user MUST be randomly
  ;; generated. Given a user's uid, it MUST NOT be possible to find
  ;; out the associated username. Otherwise said, this uid must appear
  ;; nowhere else, in particular it MUST NOT appear in urls.
  (string-sign (grf3:vertex-uid user) (app-pepper app)))

317
(define (route/signin/post app request body)
318 319 320 321 322 323 324 325 326 327 328
  (let ((form (decode body)))
    (let ((errors (signin/form-validate form)))
      (if (null? errors)
          (let ((user (signin/signin app
                                     (car (ref form "username"))
                                     (car (ref form "password")))))
            (if user
                (let* ((token (user-auth-token app user))
                       (cookies `((token . ,token))))
                  (redirect "/" #:cookies cookies))
                (sxml->response
329
                 (signin/sxml form `(("username" . "wrong username?")
330
                                         ("password" . "wrong password?"))))))
331
          (sxml->response (signin/sxml form errors))))))
332 333 334

;;; signup

335
(define (signup/sxml values errors)
336
  (template "signup"
337 338
    `(,(navigation/sxml #:value "/signup")
      (form (@ (method "POST"))
339 340 341 342
           ,(form/input "text"
                        "username"
                        "username"
                        (ref values "username")
343 344
                        (ref errors "username")
                        #:autofocus #t)
345 346 347 348 349 350 351 352 353 354
           ,(form/input "password"
                        "password"
                        "password"
                        #f
                        (ref errors "password"))
           ,(form/input "password"
                        "confirmation"
                        "confirmation"
                        #f
                        (ref errors "confirmation"))
355
           ,(form/submit "submit")))))
amirouche's avatar
amirouche committed
356 357


358
(define (route/signup/get request)
359
  (sxml->response (signup/sxml '() '())))
amirouche's avatar
amirouche committed
360

amirouche's avatar
amirouche committed
361 362
(define (username-valid? username)
  (and (or (not username)
363 364
           (< (string-length (car username)) 1))
       "username must be at least one character."))
amirouche's avatar
amirouche committed
365

366 367 368
(define (%char-set-predicate char-set)
  (lambda (char)
    (char-set-contains? char-set char)))
amirouche's avatar
amirouche committed
369

370 371 372
(define (char-set-predicate char-set)
  (lambda (lst)
    (any values (map (%char-set-predicate char-set) lst))))
amirouche's avatar
amirouche committed
373

374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
(define digit? (char-set-predicate char-set:digit))
(define lower? (char-set-predicate char-set:lower-case))
(define upper? (char-set-predicate char-set:upper-case))
(define other? (char-set-predicate (char-set-difference char-set:full
                                                        char-set:letter+digit)))

(define %strong-predicates (list digit? lower? upper? other?))

(define (strong-predicate password)
  (lambda (predicate)
    (predicate password)))

(define (strong? password)
  (and
   (<= 8 (string-length password))
   (every values (map (strong-predicate (string->list password)) %strong-predicates))))

(define (password-valid? password)
  (and (or (not password)
           (not (strong? (car password))))
       "password must be at least eight characters including lower case, upper case, digit and punctuation."))

(define (confirmation-valid? confirmation)
  (and (or (not confirmation)
           (not (strong? (car confirmation))))
       "confirmation must be the same as password."))

(define %signup-validator `(("username" . ,username-valid?)
                            ("password" . ,password-valid?)
                            ("confirmation" . ,confirmation-valid?)))

(define (validate-passwords-match form)
  (if (string=? (car (ref form "password")) (car (ref form "confirmation")))
      '()
      `(("confirmation" . "confirmation must be the same as password."))))

(define (validate-username-available form)
  (if (query-user-by-username (car (ref form "username")))
      `(("username" . "username already taken."))
      '()))

(define (signup/form-validate form)
  (let ((errors (validate %signup-validator form))) ;; shallow validation
    (if (null? errors)
        (append (validate-passwords-match form) ;; deep validation
                (validate-username-available form))
        errors)))

(define (query-single-user?)
423 424
  (with-transaction
    (eq? (length (fs:find 'type 'user)) 1)))
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448

(define (app-init user)
  "Initialize the application with USER as superuser. Return the app
vertex."
  (grf3:save (grf3:vertex-set user 'user/superuser #t))
  (let* ((username (grf3:vertex-ref user 'user/username))
         (app/name (string-append username "'s culturia")))
    (grf3:save (grf3:create-vertex `((type . app)
                                     (app/name . ,app/name)
                                     (app/tagline . "my place in the cyberspace"))))))

(define (signup/signup app username password)
  "Create an user with USERNAME and PASSWORD. Create app vertex if
it's the first user and set the created user as superuser. Return the
user vertex"
  (let ((hash (hash-secret password (app-pepper app))))
    (let ((user (grf3:save (grf3:create-vertex `((type . user)
                                                 (user/username . ,username)
                                                 (user/hash . ,hash))))))
      (when (query-single-user?)
        (log-info "First signup, initialize the application")
        (app-init user))
      user)))

449
(define (route/signup/post app request body)
amirouche's avatar
amirouche committed
450
  (let ((form (decode body)))
451
    (let ((errors (signup/form-validate form)))
amirouche's avatar
amirouche committed
452
      (if (null? errors)
453 454 455 456 457
          (begin
            (signup/signup app
                           (car (ref form "username"))
                           (car (ref form "password")))
            (redirect "/signin"))
458
          (sxml->response (signup/sxml form errors))))))
459

460
(define (router app request body)
461
  (log-debug "~a ~a" (request-method request) (uri-path (request-uri request)))
amirouche's avatar
amirouche committed
462
  (with-context*
463 464 465 466
   ;; TODO: only do it in debug mode
   (and=> (request-user request app)
          (lambda (user)
            (log-debug "user is ~s" (grf3:vertex-ref user 'user/username))))
amirouche's avatar
amirouche committed
467
   (match (cons (request-method request) (request-path-components request))
468 469 470 471 472
     ('(GET) (route/index app request))
     ('(GET "signin") (route/signin/get request))
     ('(POST "signin") (route/signin/post app request body))
     ('(GET "signup") (route/signup/get request))
     ('(POST "signup") (route/signup/post app request body))
amirouche's avatar
amirouche committed
473 474
     (('GET "static" path ...) (render-static-asset path))
     (_ (not-found (uri-path (request-uri request)))))))
amirouche's avatar
amirouche committed
475

amirouche's avatar
amirouche committed
476
(define-public (run-culturia app)
477
  (format #t "Server running @ http://localhost:8080\n")
478
    (with-env (env-open* "wt" (list *feature-space*) "create,log=(enabled=true)")
amirouche's avatar
amirouche committed
479
      (run-server (lambda (request body) (router app request body)))))