Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import string
- import random
- import mysql.connector
- from flask import Flask, render_template
- from flask_wtf import FlaskForm
- from wtforms import StringField, SubmitField
- from wtforms.validators import DataRequired
- app = Flask(__name__)
- app.config['SECRET_KEY'] = os.getenv('SECRET_KEY')
- class DBUserForm(FlaskForm):
- database = StringField('Database', validators=[DataRequired()])
- username = StringField('Username', validators=[DataRequired()])
- submit = SubmitField('Submit')
- @app.route('/', methods=['GET', 'POST'])
- def create_db_user():
- form = DBUserForm()
- if form.validate_on_submit():
- db_name = form.database.data
- db_username = form.username.data
- # Create a database user with full control over the specified database
- cnx = mysql.connector.connect(
- host=os.getenv('MARIADB_HOST'),
- user=os.getenv('MARIADB_ROOT_USER'),
- password=os.getenv('MARIADB_ROOT_PASSWORD')
- )
- cursor = cnx.cursor()
- cursor.execute(f"CREATE USER '{db_name}_{db_username}'@'%' IDENTIFIED BY '{random_password}';")
- cursor.execute(f"GRANT ALL PRIVILEGES ON {db_name}.* TO '{db_name}_{db_username}'@'%';")
- cnx.close()
- # Generate a random password and display it on the page
- password_characters = string.ascii_letters + string.digits + string.punctuation
- random_password = ''.join(random.choice(password_characters) for i in range(16))
- # Return the rendered HTML template with the generated password and database name
- return render_template('index.html', form=form, username=f'{db_name}_{db_username}', password=random_password, database=db_name, success=True)
- # If the request method is GET, pre-populate the form with a default username value
- form.username.data = "dbuser"
- # Return the rendered HTML template with the pre-populated form
- return render_template('index.html', form=form)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement