Commit 4c044deb authored by Mitchell Moore's avatar Mitchell Moore
Browse files

Add detection of account creation, remove overlay and clear text when response...

Add detection of account creation, remove overlay and clear text when response recieved by Signup. Remove Jinja references and form in __init__.py

- Fix error output
- Remove page return
- Remove Jinja references and form in __init__.py
- Get basic form data passed
- Clear text when response recieved
- Create directory and pass username variable
- Create refresh page function. Implement error handeling
- Add detection of account creation
- Remove overlay when creation succeeded
parent b23cf956
......@@ -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
......
......@@ -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
{% 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>
# 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)
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment