Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • rc/account-app
  • louistw/account-app
  • krish94/self-reg-form
  • dwheel7/self-reg-form
  • dwheel7/feature-reanme-self-reg-app-to-account-app
  • atlurie/account-app
  • dwheel7/account-app
7 results
Show changes
Commits on Source (2)
Showing
with 277 additions and 117 deletions
"""
Initialize the main flask app
"""
# app/__init__.py
# local imports
# standard imports
from __future__ import print_function
import vars
import messages
# third-party imports
import re
import sys
import uuid
from flask import Flask, redirect, url_for, request, render_template, flash, session, send_from_directory
from flask_cors import CORS
# third-party imports
from flask import Flask, render_template, request, session
from flask_bootstrap import Bootstrap
import random
import os
import json
import sys
import re
from flask_cors import CORS
# local imports
import app_vars
import messages
sys.path.append(app_vars.rabbitmq_agents_loc)
# pylint: disable=wrong-import-order,wrong-import-position
import rc_util # noqa: E402
# pylint: enable=wrong-import-order,wrong-import-position
sys.path.append(vars.rabbitmq_agents_loc)
import rc_util
def create_app(config_name):
app = Flask(__name__, static_folder='static') # initialization of the flask app
cors = CORS(app, resources={r"/*": {"origins": vars.cors_allowed_origins}})
Bootstrap(app) # allowing app to use bootstrap
"""
Create main flask app
input:
config_name: environment of the app running
output:
Flask instance
"""
app = Flask(
__name__, static_folder="static"
) # initialization of the flask app
CORS(app, resources={r"/*": {"origins": app_vars.cors_allowed_origins}})
Bootstrap(app) # allowing app to use bootstrap
def get_authorized_user():
user = {
"username": re.search("([^!]+?)(@uab\.edu)?$", request.headers.get("Persistent-Id")).group(1),
"fullname": f'{request.headers.get("Givenname")} {request.headers.get("Sn")}',
"username": re.search(
r"([^!]+?)(@uab\.edu)?$", request.headers.get("Persistent-Id")
).group(1),
"fullname": (
f"{request.headers.get('Givenname')}"
f" {request.headers.get('Sn')}"
),
"email": request.headers.get("Mail"),
"eppa": request.headers.get("Unscoped-Affiliation"),
}
return user
@app.route('/', methods=['GET', 'POST']) # initial route to display the reg page
@app.route(
"/", methods=["GET", "POST"]
) # initial route to display the reg page
def index():
valid_eppa = vars.valid_eppa
valid_eppa = app_vars.valid_eppa
if 'uid' not in session:
session['uid']=str(uuid.uuid4())
if "uid" not in session:
session["uid"] = str(uuid.uuid4())
if 'user' not in session:
if "user" not in session:
session["user"] = get_authorized_user()
session['return_url'] = request.args.get('redir', vars.default_referrer)
if (not any(item in session['user'].get('eppa') for item in valid_eppa)):
return render_template('account/unauthorized.html', unauthorized_msg=messages.unauthorized_message)
if rc_util.check_state(session['user'].get('username')) == "hold":
return render_template('account/hold.html', account_hold_msg=messages.account_hold_message)
elif rc_util.check_state(session['user'].get('username')) == "certification":
return render_template('account/certify.html', room_id=session['uid'],
username=session['user'].get('username'),
fullname=session['user'].get('fullname'), email=session['user'].get('email'),
referrer=session['return_url'], cancel_url=vars.default_referrer,
cancel_msg=messages.cancel_message,
pre_certification_msg=messages.pre_certification_message,
certification_msg=messages.certification_message)
elif rc_util.check_state(session['user'].get('username')) == "ok":
return render_template('account/good_standing.html', good_standing_msg= messages.good_standing_message)
else:
return render_template('auth/SignUp.html', room_id=session['uid'],
username=session['user'].get('username'),
fullname=session['user'].get('fullname'), email=session['user'].get('email'),
referrer=session['return_url'], cancel_url=vars.default_referrer,
welcome_msg=messages.welcome_message,
cancel_msg=messages.cancel_message,
error_msg=messages.error_message)
session["return_url"] = request.args.get(
"redir", app_vars.default_referrer
)
if not any(item in session["user"].get("eppa") for item in valid_eppa):
return render_template(
"account/unauthorized.html",
unauthorized_msg=messages.unauthorized_message,
)
if rc_util.check_state(session["user"].get("username")) == "hold":
return render_template(
"account/hold.html",
account_hold_msg=messages.account_hold_message,
)
if (
rc_util.check_state(session["user"].get("username"))
== "certification"
):
return render_template(
"account/certify.html",
room_id=session["uid"],
username=session["user"].get("username"),
fullname=session["user"].get("fullname"),
email=session["user"].get("email"),
referrer=session["return_url"],
cancel_url=app_vars.default_referrer,
cancel_msg=messages.cancel_message,
pre_certification_msg=messages.pre_certification_message,
certification_msg=messages.certification_message,
)
if rc_util.check_state(session["user"].get("username")) == "ok":
return render_template(
"account/good_standing.html",
good_standing_msg=messages.good_standing_message,
)
return render_template(
"auth/SignUp.html",
room_id=session["uid"],
username=session["user"].get("username"),
fullname=session["user"].get("fullname"),
email=session["user"].get("email"),
referrer=session["return_url"],
cancel_url=app_vars.default_referrer,
welcome_msg=messages.welcome_message,
cancel_msg=messages.cancel_message,
error_msg=messages.error_message,
)
# misc page error catching
@app.errorhandler(403)
def forbidden(error):
return render_template('errors/403.html', title='Forbidden'), 403
return render_template("errors/403.html", title="Forbidden"), 403
@app.errorhandler(404)
def page_not_found(error):
return render_template('errors/404.html', title='Page Not Found'), 404
return render_template("errors/404.html", title="Page Not Found"), 404
@app.errorhandler(500)
def internal_server_error(error):
return render_template('errors/500.html', title='Server Error'), 500
return render_template("errors/500.html", title="Server Error"), 500
return app
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
......@@ -9,7 +9,7 @@ function preCertification() {
}
}
function check() {
function check() {
var submitButton = document.getElementById("submit");
let ckbox = document.getElementById('agree');
submitButton.disabled = !(ckbox.checked);
......@@ -49,7 +49,7 @@ function renderDom(title, message, error_msg) {
var error_button = document.createElement("BUTTON");
error_button.innerHTML = 'Read Error Message';
document.getElementById("form-wrapper").appendChild(error_button);
error_button.onclick = function(){document.getElementById("form-wrapper").innerHTML += "<br>" +error_msg}
error_button.onclick = function(){document.getElementById("form-wrapper").innerHTML += "<br>" +error_msg}
}
}
......
This diff is collapsed.
......@@ -25,12 +25,12 @@
$('#myModal2 .modal-body').text("Redirecting...");
setTimeout(() => {
window.location.replace('{{ referrer }}');
}, 5000);
}, 5000);
});
socket.on( 'certify error', function( msg ) {
console.log(msg);
$('#myModal2').modal('hide');
$('#myModal2').modal('hide');
renderDom("Account Certification Error", "{{ error_msg }}", msg);
});
......@@ -104,7 +104,7 @@
</div>
<div class="col-md-10 col-sm-10 my-col">
<br><input class="checks" id ="agree" type="checkbox" name="agree" value="agree" onchange= check() /> I have read & accept UAB <a href="https://secure2.compliancebridge.com/uab/public/index.php?fuseaction=print.preview&docID=786" target="_blank">Acceptable Use</a>, <a href="https://www.uab.edu/it/home/policies/data-classification/classification-overview" target="_blank">Data Classification</a> and all other Information Technology <a href="https://www.uab.edu/it/home/policies" target="_blank">Policies.</a><br/>
<br><button class="btn btn-danger btn-md" id="cancel" name="cancel" type="button" onClick="renderDom('Account Certification Cancelled','{{ cancel_msg |safe }}', null)">Cancel</button>
<br><button class="btn btn-danger btn-md" id="cancel" name="cancel" type="button" onClick="renderDom('Account Certification Cancelled','{{ cancel_msg |safe }}', null)">Cancel</button>
<button class="btn btn-primary btn-md" disabled id="submit" name="submit" type="button" value="Submit" onclick="displayloading1();certify_account()"> Certify Account</button>
</div>
</form>
......@@ -112,7 +112,7 @@
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="overlayModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-sm" role="document">
......
......@@ -56,7 +56,7 @@
<p style="font-size:110%;"> {{ good_standing_msg|safe }}</p>
</div>
</div>
</div>
</div>
<footer>
<div class="container-fluid">
......
......@@ -56,7 +56,7 @@
<p style="font-size:110%;"> {{ account_hold_msg |safe }}</p>
</div>
</div>
</div>
</div>
<footer>
<div class="container-fluid">
......
......@@ -56,7 +56,7 @@
<p style="font-size:110%;"> {{ unauthorized_msg |safe }}</p>
</div>
</div>
</div>
</div>
<footer>
<div class="container-fluid">
......
......@@ -26,7 +26,7 @@
socket.on( 'account error', function( msg ) {
console.log(msg);
$('#myModal2').modal('hide');
$('#myModal2').modal('hide');
renderDom("Account Create Error", "{{ error_msg |safe}}", msg);
});
......@@ -80,7 +80,7 @@
<div id="form-wrapper">
<h2>Welcome to UAB Research Computing</h2>
<p style="font-size:110%;"> {{ welcome_msg |safe }}</p>
<div id="user-input">
<div id="user-input">
<form id="signup" data-toggle="validator" role="form" action="." method="post" onsubmit="">
<div class="col-md-7 col-sm-7 my-col">
<label for="username" class="control-label">Blazer Id:</label>&#9;<input id="username" class="form-control" placeholder="Enter Username" required><br>
......@@ -97,14 +97,14 @@
</div>
<div class="col-md-10 col-sm-10 my-col">
<br><input class="checks" id ="agree" type="checkbox" name="agree" value="agree" onchange= check() /> I have read & accept UAB <a href="https://secure2.compliancebridge.com/uab/public/index.php?fuseaction=print.preview&docID=786" target="_blank">Acceptable Use</a>, <a href="https://www.uab.edu/it/home/policies/data-classification/classification-overview" target="_blank">Data Classification</a> and all other Information Technology <a href="https://www.uab.edu/it/home/policies" target="_blank">Policies.</a><br/>
<br><button class="btn btn-danger btn-md" id="cancel" name="cancel" type="button" onClick="renderDom('Account Creation Cancelled','{{ cancel_msg |safe }}', null)">Cancel</button>
<br><button class="btn btn-danger btn-md" id="cancel" name="cancel" type="button" onClick="renderDom('Account Creation Cancelled','{{ cancel_msg |safe }}', null)">Cancel</button>
<button class="btn btn-primary btn-md" disabled id="submit" name="submit" type="button" value="Submit" onclick="displayloading1();request_account()"> Create Account</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="overlayModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-sm" role="document">
......
......@@ -11,4 +11,4 @@
You will be emailed as soon as your request has been fulfilled.
</p>
</body>
</html>
\ No newline at end of file
</html>
......@@ -12,4 +12,4 @@
</body>
</html>
\ No newline at end of file
</html>
......@@ -9,4 +9,4 @@
<p>Page Not Found</p>
</body>
</html>
\ No newline at end of file
</html>
......@@ -9,4 +9,4 @@
<p>Internal Server Error</p>
</body>
</html>
\ No newline at end of file
</html>
"""
Define different environment running the app
"""
# config.py
......@@ -34,8 +38,7 @@ class TestingConfig(Config):
app_config = {
'development': DevelopmentConfig,
'production': ProductionConfig,
'testing': TestingConfig
"development": DevelopmentConfig,
"production": ProductionConfig,
"testing": TestingConfig,
}
This diff is collapsed.
welcome_message = "The information below will be used to create your account. Please fill in the reason for requesting your account as this helps us understand our user base. Please be aware that the use of this resource is governed by <a href='https://www.uab.edu/it/home/policies' target='_blank'>UAB Information Technology Security Policies.</a><br><br>Contact <a href='mailto:support@listserv.uab.edu'>Research Computing</a> if you have any questions.<br>"
cancel_message = "Close current tab to end session.<br>Contact <a href="'mailto:support@listserv.uab.edu'">Research Computing</a> if you have any questions.<br>"
error_message = "An error occurred while creating your account. Research Computing team has been notified and is working on fixing it.<br>Contact <a href='mailto:support@listserv.uab.edu'>Research Computing</a> if you have any questions.<br>"
unauthorized_message = "Your UAB login is not authorized to use UAB Research Computing Systems. Contact <a href='mailto:support@listserv.uab.edu'>Research Computing</a> to resolve this issue.<br>"
account_hold_message = "Your UAB Research Computing account is currently on hold.<br>Please contact <a href="'mailto:support@listserv.uab.edu'">Research Computing</a> or attend the weekly <a href='https://uabrc.github.io/#contact-us' target='_blank'>office hours</a> to resolve this issue.<br>"
pre_certification_message = "Annual account certification is required for continued access to Research Computing Systems.<br>To continue with the self certification process click on continue below.<br><br>"
certification_message= "This resource is governed by <a href='https://www.uab.edu/it/home/policies' target='_blank'>UAB Information Technology Security Policies.</a><br><br>Please verify your information in the form below and press the Certify Account to complete the certification process.<br>"
good_standing_message= "Your account is in good standing. Click <a href=https://rc.uab.edu>here</a> to proceed to dashboard.<br>"
"""
Messages used in account management app
"""
welcome_message = (
"The information below will be used to create your account. Please fill in"
" the reason for requesting your account as this helps us understand our"
" user base. Please be aware that the use of this resource is governed by"
" <a href='https://www.uab.edu/it/home/policies' target='_blank'>UAB"
" Information Technology Security Policies.</a><br><br>Contact <a"
" href='mailto:support@listserv.uab.edu'>Research Computing</a> if you"
" have any questions.<br>"
)
cancel_message = (
"Close current tab to end session.<br>Contact <a href="
"mailto:support@listserv.uab.edu"
">Research Computing</a> if you have any questions.<br>"
)
error_message = (
"An error occurred while creating your account. Research Computing team"
" has been notified and is working on fixing it.<br>Contact <a"
" href='mailto:support@listserv.uab.edu'>Research Computing</a> if you"
" have any questions.<br>"
)
unauthorized_message = (
"Your UAB login is not authorized to use UAB Research Computing Systems."
" Contact <a href='mailto:support@listserv.uab.edu'>Research Computing</a>"
" to resolve this issue.<br>"
)
account_hold_message = (
"Your UAB Research Computing account is currently on hold.<br>Please"
" contact <a href=mailto:support@listserv.uab.edu>Research Computing</a>"
" or attend the weekly <a href='https://uabrc.github.io/#contact-us'"
" target='_blank'>office hours</a> to resolve this issue.<br>"
)
pre_certification_message = (
"Annual account certification is required for continued access to Research"
" Computing Systems.<br>To continue with the self certification process"
" click on continue below.<br><br>"
)
certification_message = (
"This resource is governed by <a"
" href='https://www.uab.edu/it/home/policies' target='_blank'>UAB"
" Information Technology Security Policies.</a><br><br>Please verify your"
" information in the form below and press the Certify Account to complete"
" the certification process.<br>"
)
good_standing_message = (
"Your account is in good standing. Click <a"
" href=https://rc.uab.edu>here</a> to proceed to dashboard.<br>"
)
......@@ -3,6 +3,7 @@ line-length = 79
target-version = ['py36']
preview = true
[tool.pylint.main]
disable = ["import-error", "unused-argument", "broad-except"]
disable = ["invalid-name", "import-error", "unused-argument", "broad-except"]
ignore = ["config.py", "tests.py"]
[tool.pylint.format]
max-line-length = 79
"""
This python script conatins functions that talk with Flask frontend over
socketio.
It has functions to join a unique room, creating an account and
certifying an account.
"""
# run.py
# standard imports
import os
import time
import tasks
import vars
# third-party imports
from flask import session
from flask_socketio import SocketIO, join_room
from app import create_app
from gevent import monkey
# local imports
# pylint: disable=wrong-import-order
import tasks
import app_vars
# pylint: enable=wrong-import-order
from app import create_app
monkey.patch_all(subprocess=True)
config_name = os.getenv('FLASK_CONFIG')
config_name = os.getenv("FLASK_CONFIG")
app = create_app(config_name)
app.config['SECRET_KEY'] = vars.key
socketio = SocketIO(app, cors_allowed_origins=vars.cors_allowed_origins, message_queue=vars.message_queue)
app.config["SECRET_KEY"] = app_vars.key
socketio = SocketIO(
app,
cors_allowed_origins=app_vars.cors_allowed_origins,
message_queue=app_vars.message_queue,
)
@socketio.on('join_room')
@socketio.on("join_room")
def on_room(json):
room = str(session['uid'])
referrer = json['referrer']
"""
This function creates a unique room/flask session id, and joins it
Input:
json: conatins config information for the flask session
Output:
Join the unique room.
"""
room = str(session["uid"])
referrer = json["referrer"]
join_room(room)
print('\t\t\t|-----Room ID: ' + room)
print('\t\t\t|-----Referrer: ' + referrer)
@socketio.on('request account')
def request_account(json, methods=['GET', 'POST']):
print (time.strftime("%m-%d-%Y_%H:%M:%S") + '\tQueue request received: ' + str(json))
room = str(session['uid'])
print("Room: {}".format(room))
print("\t\t\t|-----Room ID: " + room)
print("\t\t\t|-----Referrer: " + referrer)
@socketio.on("request account")
def request_account(json):
"""
This function is called by the Flask frontend on an account request.
Input:
json: This contains information needed for the user that needs to be
created from the frontend.
methods: Defaults to ["GET", "POST"].
Output:
Send the json to Celery tasks file for account creation.
"""
print(
time.strftime("%m-%d-%Y_%H:%M:%S")
+ "\tQueue request received: "
+ str(json)
)
room = str(session["uid"])
print(f"Room: {room}")
try:
tasks.celery_create_account.delay(json, session=room )
tasks.celery_create_account.delay(json, session=room)
except Exception as e:
print(time.strftime("%m-%d-%Y_%H:%M:%S") + "\tError in account creation: ", e)
print(
time.strftime("%m-%d-%Y_%H:%M:%S")
+ "\tError in account creation: ",
e,
)
socketio.emit("Account creation failed", room)
@socketio.on('request certification')
def certify_account(json, methods=['GET', 'POST']):
print (time.strftime("%m-%d-%Y_%H:%M:%S") + '\tQueue request received: ' + str(json))
room = str(session['uid'])
print("CERTIFY Room: {}".format(room))
@socketio.on("request certification")
def certify_account(json):
"""
This function is called by the Flask frontend from self certification page.
Inputs:
json: Conatins information about the user that needs to be certified
from the frontend.
methods: Defaults to ["GET", "POST"].
Outputs:
Send the json to Celery tasks file for user certification.
"""
print(
time.strftime("%m-%d-%Y_%H:%M:%S")
+ "\tQueue request received: "
+ str(json)
)
room = str(session["uid"])
print(f"CERTIFY Room: {room}")
try:
tasks.celery_certify_account(json, session=room )
tasks.celery_certify_account(json, session=room)
except Exception as e:
print(time.strftime("%m-%d-%Y_%H:%M:%S") + "\tError in account certification: ", e)
print(
time.strftime("%m-%d-%Y_%H:%M:%S")
+ "\tError in account certification: ",
e,
)
socketio.emit("Account certification failed", room)
if __name__ == '__main__':
socketio.run(app, host='0.0.0.0')
if __name__ == "__main__":
socketio.run(app, host="0.0.0.0")