An Express-like HTTP router for Bash compatible with CGI 1.1
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
2.0 KiB

#!/bin/bash
source exprash.sh;
redirect_stdout 'log';
use_session
use_body
username='admin'
password='password'
# Authorization middleware
function is_authorized() {
if [ "$(session 'authorized')" != "1" ]; then
next 'unauthorized'
return 1
fi
}
get '/' && {
if [ "$(session 'authorized')" == "1" ]; then
html="<h1>Welcome $username</h1>"
html+="<a href='admin'>Click Here For Secrets</a><br /><br />"
html+="<a href='logout'>Logout</a>"
else
html="<h1>Welcome</h1>"
html+="<p>You must login to learn secrets</p>"
html+="<a href='login'>Login</a>"
fi
printf '%s\n' "$html" | send
}
get '/admin' && is_authorized && {
html='<h1>Here are all of my secrets:</h1>'
html+="<ul><li>Rabbits are soft.</li></ul>"
html+="<a href='.'>Go Home</a>"
printf '%s' "$html" | send
}
get '/login' && {
html="<h1>Login:</h1>"
html+='<form method="POST" action="login">'
html+=' <input type="text" name="username" placeholder="username" />'
html+=' <input type="password" name="password" placeholder="password" />'
html+=' <input type="submit" value="login" />'
html+='</form>'
printf '%s\n' "$html" | send
}
get '/incorrect-password' && {
if [ "$(session 'authorized')" == "1" ]; then
redirect '.'
else
html="<h1>Incorrect Password</h1>"
html+="<p>Try again:</p>"
html+="<a href='login'>Login</a>"
printf '%s\n' "$html" | send
fi
}
post '/login' && {
post_user=$(body 'username')
post_pass=$(body 'password')
if [ "$post_user" == "$username" ] && [ "$post_pass" == "$password" ]; then
session 'authorized' 1
redirect '.'
else
redirect 'incorrect-password'
fi
}
get '/logout' && {
session 'authorized' 0
redirect '.'
}
(use || use_error) && {
if [ "$(get_error_message)" == "unauthorized" ]; then
html='<h1>Error: Access Denied</h1>'
html+='<a href='login'>Click here to login</a>'
printf '%s' "$html" | send
else
status '404'
printf '<h1>404</h1>' | send
fi
}