+#!/bin/zsh
+# Copyright 2011 Paul Haensch
+# This file is part of Busy
+#
+# Busy is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# Busy is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with Busy. If not, see <http://www.gnu.org/licenses/>.
+
+cgi_post
+
+user="$(echo -E "$_POST[\"user\"]" |sed -rn '1{/^[a-zA-Z0-9_+@.-]+$/p}')"
+pass="$_POST[\"pass\"]"
+userfile="$_DATA/auth/user$(echo -E "$user" |sha1sum |cut -c1-40)"
+
+if [ -r "$userfile" ]; then
+ salt=$(sed -nr 's:^salt=(.+)$:\1:p' "$userfile")
+ ssum=$(sed -nr 's:^auth=(.+)$:\1:p' "$userfile")
+ rsum=$(echo -E "$salt$pass" |sha1sum |cut -c1-40)
+fi
+if [ "$ssum" = "$rsum" ]; then
+ sid="$(apg -n1 -a1 -m32 -x32 -M CLN)"
+ sessionfile="$_DATA/auth/session$sid"
+ echo -E "$user $(($(date +%s) + 1800))" >"$sessionfile"
+ echo -E "Location: $HTTP_REFERER"
+ echo -E "Set-Cookie: session=$sid; HttpOnly"
+else
+ echo -E "Location: $HTTP_REFERER"
+fi
+echo ''