Advertisement
-Dal-

Untitled

Apr 23rd, 2023
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. import os
  2. import string
  3. import random
  4. import mysql.connector
  5. from flask import Flask, render_template
  6. from flask_wtf import FlaskForm
  7. from wtforms import StringField, SubmitField
  8. from wtforms.validators import DataRequired
  9.  
  10. app = Flask(__name__)
  11. app.config['SECRET_KEY'] = os.getenv('SECRET_KEY')
  12.  
  13.  
  14. class DBUserForm(FlaskForm):
  15. database = StringField('Database', validators=[DataRequired()])
  16. username = StringField('Username', validators=[DataRequired()])
  17. submit = SubmitField('Submit')
  18.  
  19.  
  20. @app.route('/', methods=['GET', 'POST'])
  21. def create_db_user():
  22. form = DBUserForm()
  23.  
  24. if form.validate_on_submit():
  25. db_name = form.database.data
  26. db_username = form.username.data
  27.  
  28. # Create a database user with full control over the specified database
  29. cnx = mysql.connector.connect(
  30. host=os.getenv('MARIADB_HOST'),
  31. user=os.getenv('MARIADB_ROOT_USER'),
  32. password=os.getenv('MARIADB_ROOT_PASSWORD')
  33. )
  34. cursor = cnx.cursor()
  35. cursor.execute(f"CREATE USER '{db_name}_{db_username}'@'%' IDENTIFIED BY '{random_password}';")
  36. cursor.execute(f"GRANT ALL PRIVILEGES ON {db_name}.* TO '{db_name}_{db_username}'@'%';")
  37. cnx.close()
  38.  
  39. # Generate a random password and display it on the page
  40. password_characters = string.ascii_letters + string.digits + string.punctuation
  41. random_password = ''.join(random.choice(password_characters) for i in range(16))
  42.  
  43. # Return the rendered HTML template with the generated password and database name
  44. return render_template('index.html', form=form, username=f'{db_name}_{db_username}', password=random_password, database=db_name, success=True)
  45.  
  46. # If the request method is GET, pre-populate the form with a default username value
  47. form.username.data = "dbuser"
  48.  
  49. # Return the rendered HTML template with the pre-populated form
  50. return render_template('index.html', form=form)
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement