This repository has been archived on 2024-04-08. You can view files and clone it, but cannot push or open issues or pull requests.
user-mgmt/management/user-mgmt.sh

83 lines
2 KiB
Bash
Raw Permalink Normal View History

2023-07-14 07:38:01 +00:00
#!/bin/bash
# User Management Script, powered by an SQL database
2023-07-14 08:46:19 +00:00
# (c) Sangelo 2023 | Read Licenses for more info: https://gitpot.dev/sangelo/user-mgmt
2023-07-14 07:38:01 +00:00
# Variables
E_BADARGS=65
2023-07-14 08:22:49 +00:00
MYSQL=$(which mysql)
2023-07-14 07:48:10 +00:00
MYSQL_USER="root"
2023-07-14 07:38:01 +00:00
USAGE="
$0 -- user management script
Usage:
init
add {username} {name} {description}
delete {username}
list
"
# Check for correct number of arguments and action
2023-07-14 08:22:49 +00:00
if [ $# -lt 1 ]; then
echo "$USAGE"
exit $E_BADARGS
2023-07-14 07:38:01 +00:00
fi
# Switch between different actions
case "$1" in
2023-07-14 08:22:49 +00:00
"init")
2023-07-14 07:48:10 +00:00
Q1="CREATE SCHEMA if not exists usermgmt; use usermgmt; CREATE TABLE if not exists users (username varchar(255), name varchar(255), description varchar(255));"
2023-07-14 07:38:01 +00:00
SQL="${Q1}"
;;
2023-07-14 08:13:43 +00:00
2023-07-14 08:22:49 +00:00
"add")
if [ $# -ne 4 ]; then
2023-07-14 08:19:20 +00:00
echo "Error: Invalid action."
echo "$USAGE"
exit $E_BADARGS
2023-07-14 07:38:01 +00:00
fi
2023-07-14 08:23:57 +00:00
Q1="INSERT INTO usermgmt.users (username, name, description) VALUES ('$2', '$3', '$4');"
2023-07-14 07:38:01 +00:00
SQL="${Q1}"
2023-07-14 08:22:49 +00:00
PASSWORD=$(openssl rand -base64 12)
2023-07-14 08:23:57 +00:00
useradd -m -p "$PASSWORD" -s /bin/bash "$2"
echo "$PASSWORD" >"/home/$2/password.txt"
echo "This is your password. Please delete this file after saving the password." >>"/home/$2/password.txt"
2023-07-14 07:38:01 +00:00
;;
2023-07-14 08:13:43 +00:00
2023-07-14 08:22:49 +00:00
"delete")
if [ $# -ne 2 ]; then
2023-07-14 08:13:43 +00:00
echo "Error: Invalid action."
echo "$USAGE"
exit $E_BADARGS
fi
echo -n "Are you sure you want to delete user "$2"? [y/N] "
read confirm
2023-07-14 08:22:49 +00:00
if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
2023-07-14 08:13:43 +00:00
Q1="DELETE FROM usermgmt.users WHERE username = '$2';"
SQL="${Q1}"
userdel -r "$2"
else
echo "User deletion cancelled."
exit 0
2023-07-14 07:38:01 +00:00
fi
;;
2023-07-14 08:13:43 +00:00
2023-07-14 08:22:49 +00:00
"list")
if [ $# -ne 1 ]; then
echo "Error: Invalid action."
echo "$USAGE"
exit $E_BADARGS
2023-07-14 07:38:01 +00:00
fi
Q1="SELECT username, name, description FROM usermgmt.users;"
SQL="${Q1}"
;;
2023-07-14 08:13:43 +00:00
2023-07-14 08:22:49 +00:00
*)
2023-07-14 07:38:01 +00:00
echo "Error: Invalid action. Please use a valid argument."
echo "$USAGE"
exit $E_BADARGS
;;
esac
2023-07-14 08:14:39 +00:00
echo "Creating MySQL connection... Enter your password if prompted."
2023-07-14 07:38:01 +00:00
$MYSQL -u "$MYSQL_USER" -p -e "$SQL"
2023-07-14 08:22:49 +00:00
echo "Done."