added basic cookie and session support

This commit is contained in:
overflowerror 2022-01-13 21:45:44 +01:00
parent f34a9cf8c1
commit 3c41344d17
3 changed files with 106 additions and 1 deletions

13
cookies.sh Normal file
View file

@ -0,0 +1,13 @@
#!/bin/bash
getCookie() {
key="$1"
echo "$HTTP_COOKIE" | tr ';' $'\n' | grep -e "^$1=" | cut -d= -f2 | sed -r 's/\s*$//g'
}
setCookie() {
key="$1"
value="$2"
attributes="$3"
header "Set-Cookie" "$key=$value; $attributes"
}

16
demo.sh
View file

@ -4,6 +4,8 @@
. uri.sh
. router.sh
. mysql.sh
. cookies.sh
. sessions.sh
. credentials.sh
. shinden/engine.sh
@ -20,7 +22,19 @@ index() {
template "templates/demo.html.templ" ""
}
route GET /session session
session() {
startSession
endHeaders
value="$(queryString "val")"
if test ! -z "$value"; then
setSession "$value"
echo "saved to session"
else
getSession
fi
}
route GET /debug debug
debug() {

78
sessions.sh Normal file
View file

@ -0,0 +1,78 @@
#!/bin/bash
_sessionDuration=
_sessionPath="/dev/shm/shochu/sessions/"
mkdir -p "$_sessionPath"
_sessionCookie="shochu_sessid"
_currentSessionId=""
_makeSessionPath() {
echo "$_sessionPath/$(basename "$1")"
}
_getSessionDate() {
date -Ins -u
}
_createSession() {
_getSessionDate > "$(_makeSessionPath "$1")"
}
_getSession() {
f="$(_makeSessionPath "$1")"
if test -f "$f"; then
cat "$f"
return 0
else
return 1
fi
}
_newSessionId() {
base="$(date -Ins -u)"
random="$RANDOM"
while _getSession "$(echo "$base$random" | md5sum | cut -d' ' -f1)" > /dev/null; do
random="$RANDOM"
done
echo "$base$random" | md5sum | cut -d' ' -f1
}
_hasSession() {
test ! -z "$(_getSessionId)"
return
}
_getSessionId() {
if test -z "$_currentSessionId"; then
_currentSessionId="$(getCookie "$_sessionCookie")"
fi
echo "$_currentSessionId"
}
startSession() {
_getSessionId > /dev/null # not in subshell to cache result
if _hasSession; then
return 1
else
id="$(_newSessionId)"
_currentSessionId="$id"
_createSession "$id"
setCookie "$_sessionCookie" "$id"
return 0
fi
}
getSession() {
_getSession "$(_getSessionId)" | tail -n +2
}
setSession() {
if _hasSession; then
echo "$1" | cat <(_getSessionDate) - > "$(_makeSessionPath "$(_getSessionId)")"
fi
}