#!/bin/bash

# echo username=$1, password=$2, page=$3, roles=$4, remoteIp=$5

APP_NAME=$(basename $(dirname $(dirname $0)))
AUTH_XML="/home/$APP_NAME/sfiles/auth.xml"

if [ -f "$AUTH_XML" ]; then
    PWD_HASH=$(printf $2 | sha256sum | awk -F' ' '{print $1}')
    userroles=$(xmlstarlet sel -t -m "//user[@username='$1'][@password='$PWD_HASH']" -v "@roles" -n "$AUTH_XML")

    if [ -z "$userroles" ]; then
        # no user with provided username and password found
        logger -p error "Invalid authentication: Application name: $APP_NAME, Username: $1, Resource accessed: $3"
        exit 1
    else
        # username and password are valid
        # check roles
        for arole in $(echo "$4" | tr ',' '\n'); do
            for userrole in $(echo "$userroles" | tr ',' '\n'); do
                if [ "$arole" == "$userrole" ]; then
                    # echo "user authenticated successfully"
                    exit 0
                fi
            done
        done
    fi
    exit 1
else
    logger -p error "'$AUTH_XML' does not exist"
    exit 1
fi
