;; modules/auth_utils.fnl
;; Provides a collection of utilities for working with passwords and TOTP passcodes

;; -------------------------------------------------------------------------- ;;
;; Dependencies

(local basexx (require :basexx))
(local otp (require :otp))
(local qrprinter (require :qrprinter))

;; -------------------------------------------------------------------------- ;;
;; Local modules

(local config (require :modules.config))

;; -------------------------------------------------------------------------- ;;
;; TOTP generator/validator

(local totp (otp.new_totp_from_key (basexx.to_base32 config.auth_secret)))

;; -------------------------------------------------------------------------- ;;
;; Module definition

(local auth_utils {})

(fn auth_utils.verify_password [password]
  "Return true if `password` is valid.
Compares `password` to config.auth_secret if config.use_totp is set to false.
Compares `password` to the current valid TOTP (generated with config.auth_secret as the key)."
  (if config.use_totp
      (totp:verify password)
      (= password config.auth_secret)))

(fn auth_utils.print_totp_qr []
  "Print a QR code containing the TOTP configuration URL to stdout."
  (let [totp_url (totp:get_url "simple-shortener" "User")
        qr (qrprinter.encode_string totp_url)]
    (print "TOTP configuration:")
    (qrprinter.print_qr qr)))

;; -------------------------------------------------------------------------- ;;
;; Return module

auth_utils
