summaryrefslogtreecommitdiff
path: root/authentication.rkt
blob: 9a1597683ca76cc549581d422ff0ea3724a5729c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#lang racket

(provide authentication-credentials-defined?
         make-auth-dispatch)

(require web-server/http
         web-server/http/basic-auth)

(define ferti-user (make-parameter (getenv "FERTI_USER")))
(define ferti-pass (make-parameter (getenv "FERTI_PASS")))

(define (authentication-credentials-defined?)
  (and (ferti-user) (ferti-pass)))

(define (make-auth-dispatch handler)
  (if (authentication-credentials-defined?)
      (lambda (req)
        (if (authorized? req)
            (handler req)
            (unauthorized-response)))
      (error
       'authentication
       "Undefined authentication credentials (FERTI_USER and FERTI_PASS environment variables)")))

(define (authorized? req)
  (match (request->basic-credentials req)
    [(cons user-b pass-b)
     (define user (bytes->string/utf-8 user-b))
     (define pass (bytes->string/utf-8 pass-b))
     (and (string=? user (ferti-user)) (string=? pass (ferti-pass)))]
    [_ #f]))

(define (unauthorized-response)
  (response 401
            #"Unauthorized"
            (current-seconds)
            TEXT/HTML-MIME-TYPE
            (list (make-basic-auth-header (format "Basic Auth Test: ~a" (gensym))))
            void))
Copyright 2019--2026 Marius PETER