#! /bin/sh

# Copyright (c) 2003-2011
# Distributed Systems Software.  All rights reserved.
# See the file LICENSE for redistribution information.
#
# $Id: do_reauth 2531 2011-09-23 22:35:48Z brachman $

# This script can be under Apache's Basic or Digest access control,
# identically to do_auth, or not under any access control.
#
# This script forces native reauthentication, sets a cookie to note that
# the user has been prompted, and redirects the user to the authentication
# script and deletes the cookie.

debug=
dacs_auth="do_auth"
use_cookies=1

# This realm must be the same as the one associated with do_auth
# i.e., it must match the AuthName value.
# For Digest, if the realm string is changed the passwords generated by
# htdigest become invalid.
realm="DACS authentication"

# Must be distinct from other DACS cookie names
reauth_cookie_name="DACS:reauth"

# Both Basic and Digest are supported.  Use the same auth_type in
# do_auth and do_reauth.
auth_type="Basic"
#auth_type="Digest"

# Select original or newer syntax for Set-Cookie expiration
#expires="Max-Age=0"
expires="expires=Thu, 01-Jan-1970 00:00:01 GMT"

if [ "${HTTPS}x" = "onx" ]
then
  scheme="https"
else
  scheme="http"
fi

server="${HTTP_HOST}"
dir_uri=`dirname "${REQUEST_URI}"`

auth_url="${scheme}://${server}${dir_uri}/${dacs_auth}"

if [ "${use_cookies}x" != "x" ]
then
  # Returns the number of characters matched
  is_first_call=`/bin/expr "${HTTP_COOKIE}" : ".*${reauth_cookie_name}"`
else
  # A non-cookie based method.  Although it's not safe wrt concurrency
  # it's useful for testing purposes.
  if [ -f /tmp/reauth ]
  then
    is_first_call="1"
    rm -f /tmp/reauth
  else
    is_first_call="0"
    touch /tmp/reauth
  fi
fi

if [ "${is_first_call}" = "0" ]
then
  # First call - see RFC 2617
  echo "WWW-Authenticate: ${auth_type} realm=\"${realm}\""
  if [ "${use_cookies}x" != "x" ]
  then
    echo "Set-Cookie: ${reauth_cookie_name}=17"
  fi
  echo "Status: 401"
  echo ""
else
  # The redirected call
  if [ "${debug}x" = x ]
  then
    # Status should really be a 303 "See Other" status code but most clients
    # treat 302 and 303 equivalently.  See RFC 2616.
    # Delete the cookie
    if [ "${use_cookies}x" != "x" ]
    then
      echo "Set-Cookie: ${reauth_cookie_name}=; ${expires}"
    fi
    echo "Location: ${auth_url}"
    echo "Status: 302"
    echo ""
  else
    echo "Content-Type: text/html"
    echo ""
    echo "<PRE>"
    echo "Redirect to URL <TT><B>${auth_url}</B></TT><BR>"
    echo "is_first_call=${is_first_call}<BR>"
    env
    echo "</PRE>"
  fi
fi

exit 0
