File: basic-auth.rkt

package info (click to toggle)
racket 8.16%2Bdfsg1-3
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 167,812 kB
  • sloc: ansic: 306,492; lisp: 211,972; pascal: 79,874; sh: 20,446; asm: 15,252; makefile: 1,738; cpp: 1,715; javascript: 1,340; exp: 789; python: 452; csh: 369; perl: 275; xml: 106
file content (31 lines) | stat: -rw-r--r-- 1,139 bytes parent folder | download | duplicates (11)
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
#lang racket/base
(require racket/contract
         racket/match
         net/base64
         web-server/http/request-structs)

(define (request->basic-credentials req)
  (define headers (request-headers/raw req))
  (match (headers-assq* #"Authorization" headers)
    [#f #f]
    [(struct header (_ basic-credentials))
     (cond
       [(and (basic? basic-credentials)
             (regexp-match #rx"([^:]*):(.*)"
                           (base64-decode (subbytes basic-credentials 6 (bytes-length basic-credentials)))))
        => (lambda (user-pass)
             (cons (cadr user-pass) (caddr user-pass)))]
       [else #f])]))

;; basic?: bytes -> (or/c (listof bytes) #f)
;; does the second part of the authorization header start with #"Basic "
(define basic?
  (let ([rx (byte-regexp #"^Basic .*")])
    (lambda (a) (regexp-match rx a))))

(define (make-basic-auth-header realm)
  (make-header #"WWW-Authenticate" (string->bytes/utf-8 (format "Basic realm=\"~a\"" realm))))

(provide/contract
 [make-basic-auth-header (string? . -> . header?)]
 [request->basic-credentials (request? . -> . (or/c false/c (cons/c bytes? bytes?)))])