File: basic-auth.rkt

package info (click to toggle)
racket 6.7-3
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 97,344 kB
  • ctags: 39,484
  • sloc: ansic: 277,847; sh: 33,512; asm: 13,558; lisp: 7,113; cpp: 2,872; makefile: 2,421; pascal: 2,262; exp: 499; python: 274; xml: 11
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?)))])