You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
2.5 KiB
Bash

#!/bin/bash
# Get root password for the mariadb server
read -s -p "Enter current ROOT password: " ROOT_PASSWORD
echo
# Ask user for a password for new user
read -s -p "Enter password for user: " PASSWORD
echo
read -s -p "Confirm password: " PASSWORD_CONFIRM
echo
# Validate match
if [[ "$PASSWORD" != "$PASSWORD_CONFIRM" ]]; then
echo "Passwords do not match. Exiting."
exit 1
fi
# IN /etc/mysql/mariadb.conf.d/50-server.cnf
# bind-address = 127.0.0.1 # To only allow localhost access (If wanted)
# use -it for interactive, use i for just passing commands 'silent'
# sudo docker exec -it mariadb mysql -u root -p
# <<- Strips tabs, so just looks nicer, << would not strip the tabs and would error
sudo docker exec -i mariadb mysql -uroot -p"$ROOT_PASSWORD" <<-EOF
# Remove anonymous users
DROP USER IF EXISTS ''@'localhost';
DROP USER IF EXISTS ''@'%';
# Disable test db
DROP DATABASE IF EXISTS test;
# Create Admin Role
CREATE ROLE IF NOT EXISTS admin;
# Grant Full Permissions
GRANT ALL PRIVILEGES ON *.* TO admin WITH GRANT OPTION;
# Create Admin User
CREATE USER IF NOT EXISTS 'nathan'@'localhost' IDENTIFIED BY '$PASSWORD';
CREATE USER IF NOT EXISTS 'nathan'@'%' IDENTIFIED BY '$PASSWORD';
# Asign Admin role
GRANT admin TO 'nathan'@'localhost';
GRANT admin TO 'nathan'@'%';
# Set Admin role as default
SET DEFAULT ROLE 'admin' FOR 'nathan'@'localhost';
SET DEFAULT ROLE 'admin' FOR 'nathan'@'%';
# ALSO, CREATE USER privilege to user to allow mysql user editing
GRANT CREATE USER ON *.* TO 'nathan'@'localhost';
GRANT GRANT OPTION ON *.* TO 'nathan'@'localhost';
GRANT CREATE USER ON *.* TO 'nathan'@'%';
GRANT GRANT OPTION ON *.* TO 'nathan'@'%';
GRANT SELECT ON mysql.* TO 'nathan'@'%';
# Set the priveleges
FLUSH PRIVILEGES;
EOF
echo "User 'nathan' has been created and assigned admin role."
echo "Check the login works, and all permissions exist, then drop root"
# Check Login
#mysql -u nathan -p
sudo docker exec -i mariadb mysql -unathan -p"$PASSWORD" <<-EOF
SHOW GRANTS FOR 'nathan'@'localhost';
EOF
echo "Do the above grants look correct? If so we will remove root"
echo "Looking for CREATE USER, and * or super,process,reload,replication..."
echo "Ideally, login to the DB and check quickly, ey"
read -n 1 -p "Proceed? (y/n): " yn
echo
if [[ "${yn,,}" != "y" ]]; then
echo "Exited"
exit 0
fi
# Drop root (IDEALLY AFTER CHECKING EVERYTHING WORKS AS ADMIN)
sudo docker exec -i mariadb mysql -unathan -p"$PASSWORD" <<-EOF
DROP USER 'root'@'localhost';
DROP USER 'root'@'%';
EOF