diff --git a/app/__init__.py b/app/__init__.py index 66b8cc1309b6bc5203f89e85d00bb007f14e82b1..a5451c13da702f4cc02e45400de13c43ad2c6da8 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -16,107 +16,27 @@ from wtforms import StringField, SubmitField, TextAreaField, validators from flask_socketio import SocketIO # global declarations -global time_stamp def create_app(config_name): app = Flask(__name__) # initialization of the flask app Bootstrap(app) # allowing app to use bootstrap - socketio = SocketIO(app) global return_url return_url = '' - class MainForm(FlaskForm): # class for the form itself - fullname = StringField('Full Name: ', [validators.DataRequired(), validators.length(max=50)]) - reason = TextAreaField('Reason for Requesting Account: ', [validators.DataRequired(), validators.length(max=150)]) - submit = SubmitField('Submit') - @app.route('/', methods=['GET', 'POST']) # initial route to display the reg page def index(): global return_url - username = "mmoo97" + username = "name_test" if "redir" in request.args and return_url == "": # check for redir arg in url return_url = request.args.get("redir") or "/pun/sys/dashboard" if name != "": - fullname = False - form = MainForm() # initialize form object - if form.is_submitted(): - - session["fullname"] = form.fullname.data - session['reason'] = form.reason.data - form.fullname.data = '' # reset form data upon capture - form.fullname.data = '' # reset form data upon capture - - return redirect(url_for('request_sent', username=username)) - - return render_template('auth/SignUp.html', form=form, user=username) - - @app.route('/request_sent/<username>') - def request_sent(username): - - fullname = session.get('fullname', None) - reason = session.get('reason', None) - - global return_url - global time_stamp - print(username, fullname, return_url, file=sys.stdout) - - # Deliver arguments to script. (for local vagrant implementation) - tempString = 'ssh ohpc "sudo /opt/ohpc_user_create/user_create ' + username + " " + fullname + '"' - print(tempString, file=sys.stdout) - - try: - # function to write out a flatdb with the name of the file being a timestamp and the content - # of the file beieng blazerID the user submitted from the flask form (fullname) - - time_stamp = time.strftime("%m-%d-%Y_%H:%M:%S") - directory = "flat_db/" - complete_file_name = os.path.join(directory, time_stamp + "_" + username + ".txt") - - if not os.path.exists(directory): - os.makedirs(directory) - - file = open(complete_file_name, "w") # create time stamped file to be queued - - file.write(fullname + "\n") - file.write(reason) - - file.close() - return "Hello" - # return render_template("auth/request_received.html") # Todo: replace template with redirect - # return redirect(return_url, 302) - - except Exception as e: - print(e) - flash("Registration Failed. Please try again.") # show error message upon failure - return redirect(url_for('index')) + return render_template('auth/SignUp.html', user=username) # misc page error catching - - def messageReceived(methods=['GET', 'POST']): - print('message was received!!!') - - @socketio.on('user connect') - def handle_my_custom_event(json, methods=['GET', 'POST']): - print('received my event: ' + str(json)) - - @socketio.on('my event') - def handle_my_custom_event(json, methods=['GET', 'POST']): - print('received my event: ' + str(json)) - socketio.emit('my response', json, callback=messageReceived) - # time_stamp = time.strftime("%m-%d-%Y_%H:%M:%S") - # complete_file_name = os.path.join(directory, time_stamp + ".txt") - # file = open(complete_file_name, "w") - # file.close() - # time.sleep(5) - # - # pre, ext = os.path.splitext(complete_file_name) - # os.rename(complete_file_name, pre + ".done") - socketio.emit('create response', json, callback=messageReceived) - @app.errorhandler(403) def forbidden(error): return render_template('errors/403.html', title='Forbidden'), 403 diff --git a/app/static/scripts/function.js b/app/static/scripts/function.js index 13956d77b1aced20fb6654c4eb88aade0703bc5f..42cce9f4f5342c661a130fcf6254701ad2736267 100644 --- a/app/static/scripts/function.js +++ b/app/static/scripts/function.js @@ -17,46 +17,13 @@ function displayloading() { } function socketIO() { - var socket = io.connect('http://' + document.domain + ':' + location.port); - - socket.on( 'connect', function() { - socket.emit( 'user connect', { - data: 'User Connected' - } ) - - document.getElementById("testo").innerHTML = "yo" - - - var form = $( 'form' ).on( 'submit', function( e ) { - e.preventDefault() - let user_name = $( 'input.username' ).val() - let user_input = $( 'input.message' ).val() - socket.emit( 'my event', { - user_name : user_name, - message : user_input - } ) - $( 'input.message' ).val( '' ).focus() - } ) - } ) - - - - socket.on( 'my response', function( msg ) { - console.log( msg ) - if( typeof msg.user_name !== 'undefined' ) { - $( 'h3' ).remove() - $( 'div.message_holder' ).append( '<div><b style="color: #002">'+msg.user_name+'</b> creating</div>' ) - } - }) - - - socket.on( 'create response', function( msg ) { - console.log( msg ) - if( typeof msg.user_name !== 'undefined' ) { - $( 'h3' ).remove() - $( 'div.message_holder' ).append( '<div><b style="color: #002">'+msg.user_name+'</b> created. WELCOME</div>' ) - } - }) - </script> + socket.emit('user data', { + fullname: document.getElementById("fullname").value, + reason: document.getElementById("reason").value, + username: document.getElementById("username").innerText + }) +} +function refresh() { + document.location.reload(true); } \ No newline at end of file diff --git a/app/templates/auth/SignUp.html b/app/templates/auth/SignUp.html index 155d1468525db957311932da9f3d420a97ba979a..3ad2970c376fee26ad535e4b7cb007c949e84933 100644 --- a/app/templates/auth/SignUp.html +++ b/app/templates/auth/SignUp.html @@ -1,12 +1,44 @@ -{% extends "auth/base.html" %} <html class="gr__rc_uab_edu"> -{% block title %} User Registration {% endblock %} -{% block head %} - {{ super() }} -<script src="{{ url_for('static', filename='scripts/function.js') }}"></script> -<script src="{{ url_for('static', filename='scripts/application.js') }}"></script> - <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> - <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script> +<title>User Registration </title> +<head> +<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> +<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script> +<script src="static/scripts/function.js"></script> +<script src="static/scripts/function.js"></script> + +<script> + var socket = io.connect('http://' + document.domain + ':' + location.port); + + socket.on( 'connect', function() { + socket.emit( 'user connect', { + user: document.getElementById("username").innerText + } ) + + socket.on( 'creating account', function( msg ) { + document.getElementById("error").innerText = ""; + displayloading(); + socket.emit("validate creation", { + username: document.getElementById("username").innerText + }) + }) + + socket.on( 'Account creation failed', function( msg ) { + document.getElementById("error").innerText = "Registration Failed. Please try again."; + }) + + + socket.on( 'Account created', function( msg ) { + let element = document.getElementById("notification_window"); + element.parentNode.removeChild(element); + element.innerHTML = " "; + alert("Account creation successful!"); + + }) + + +}) +</script> + <style type="text/css"> .important { color: #336699; } </style> @@ -21,13 +53,11 @@ } </style> -{% endblock %} - +</head> <body data-gr-c-s-loaded="true"> <header> - {% block body %} <nav class="navbar navbar-inverse navbar-static-top"> <div class="container-fluid"> <div class="navbar-header"> @@ -60,38 +90,32 @@ </a> </div> - <h2>Hello, {{ user }}!</h2> - - <form action="." method="post" onsubmit="displayloading(); socketIO();"> + <h2>Hello, <span id="username">{{ user }}</span>!</h2> + <div id="test"> + <form action="." method="post" onsubmit=""> <div class="signUpContainer"> - <label><b>{{ form.fullname.label }}<br></b></label> - {{ form.fullname(class_="form-control", placeholder="Enter Full Name") }} - <label><b>{{ form.reason.label }}<br></b></label> - {{ form.reason(class_="form-control", placeholder="Enter Reason for Account Request") }} - {{ form.submit(class_="btn btn-primary btn-block" ) }} - - {% with messages = get_flashed_messages() %} - {% if messages %} - {% for message in messages %} - <div> - <strong style="color: #be051b; text-align: center;">{{ message }}</strong> - </div> - {% endfor %} - {% endif %} -{% endwith %} + <label><b><label for="fullname">Full Name: </label><br></b></label> + <input class="form-control" id="fullname" name="fullname" placeholder="Enter Full Name" required="" type="text"> + <label><b><label for="reason">Reason for Requesting Account: </label><br></b></label> + <textarea class="form-control" id="reason" name="reason" placeholder="Enter Reason for Account Request" required=""></textarea> + <input class="btn btn-primary btn-block" id="submit" name="submit" type="button" value="Submit" onclick="socketIO()"> + + <div> + <strong id="error" style="color: #be051b; text-align: center;"></strong> + </div> </div> </form> </div> + </div> <div id="notification_window" > </div> <div id ="testo"></div> -{% endblock %} </body> -{% block footer %} +<footer> <div class="container-fluid"> <div class="row"> <div class="col-md-6 col-sm-6"> @@ -102,6 +126,6 @@ </div> </div><!-- /.container --> -{% endblock %} +</footer> </html> diff --git a/run.py b/run.py index 8df717ff5052ca9fe67c09a5a617cbff396ebb15..cf7cb8cd92d67fbdf5ac6482e3384007f9b23bcf 100644 --- a/run.py +++ b/run.py @@ -1,16 +1,89 @@ # run.py import os +import time from app import create_app from flask_socketio import SocketIO +from flask import flash config_name = os.getenv('FLASK_CONFIG') app = create_app(config_name) -app.secret_key = 'randomString' +app.config['SECRET_KEY'] = 'vnkdjnfjknfl1232#' socketio = SocketIO(app) +def messageReceived(methods=['GET', 'POST']): + print('message was received!!!') + + +def check_dir(user, interval): + """ + :param user: (string) username to check for in DB. + :param interval: (int) Frequency to check in seconds. + :return: (boolean) if account has been registered. + """ + seconds = 0 + + while seconds < 600: + querystring = "_" + user + ".done" + + for filename in os.listdir("flat_db/"): + if filename.endswith(querystring): + return True + time.sleep(interval) + seconds = seconds + interval + + return False + + +@socketio.on('user connect') +def handle_my_custom_event(json, methods=['GET', 'POST']): + username = json["user"] + print('User ' + username + ' connected.') + + +@socketio.on('user data') +def ingest_data(json, methods=['GET', 'POST']): + print ('Queue request received: ', str(json)) + + try: + fullname = json["fullname"] + reason = json["reason"] + username = json["username"] + + time_stamp = time.strftime("%m-%d-%Y_%H:%M:%S") + directory = "flat_db/" + complete_file_name = os.path.join(directory, time_stamp + "_" + username + ".txt") + + if not os.path.exists(directory): + os.makedirs(directory) + + file = open(complete_file_name, "w") # create time stamped file to be queued + + file.write(fullname + "\n") + file.write(reason) + + file.close() + print ('User ' + username + ' added to queue') + socketio.emit("creating account") + + except Exception as e: + print("Error in directory creation: ", e) + socketio.emit("Account creation failed") + + +@socketio.on("validate creation") +def creation_confirmation(json, methods=['GET', 'POST']): + username = json["username"] + + if check_dir(username, 10): + print ('Account successfully created for ' + username) + socketio.emit("Account created") + else: + socketio.emit("Account creation failed") + + if __name__ == '__main__': # app.run() socketio.run(app)