__init__.py 4.62 KB
Newer Older
1
    # app/__init__.py
2

3
4
5
6
7
# local imports
from __future__ import print_function

import os
import sys
8
import subprocess
9
10
import time

11
# third-party imports
12
from flask import Flask, redirect, url_for, request, render_template, flash, session
13
from flask_wtf import FlaskForm
14
from flask_bootstrap import Bootstrap
15
16
from wtforms import StringField, SubmitField, TextAreaField, validators
from flask_socketio import SocketIO
17

18
# global declarations
19
20
21
22
23
24
global time_stamp


def create_app(config_name):
    app = Flask(__name__) # initialization of the flask app
    Bootstrap(app) # allowing app to use bootstrap
25
    socketio = SocketIO(app)
26

27
28
    global return_url
    return_url = ''
29

30
    class MainForm(FlaskForm): # class for the form itself
31
32
        fullname = StringField('Full Name: ', [validators.DataRequired(), validators.length(max=50)])
        reason = TextAreaField('Reason for Requesting Account: ', [validators.DataRequired(), validators.length(max=150)])
33
        submit = SubmitField('Submit')
34

35
36
37
    @app.route('/', methods=['GET', 'POST']) # initial route to display the reg page
    def index():
        global return_url
38
        username = "mmoo97"
39

40
        if "redir" in request.args and return_url == "": # check for redir arg in url
41
            return_url = request.args.get("redir") or "/pun/sys/dashboard"
42
            if name != "":
43

44
45
46
        fullname = False
        form = MainForm() # initialize form object
        if form.is_submitted():
47
48
49
50

            session["fullname"] = form.fullname.data
            session['reason'] = form.reason.data
            form.fullname.data = '' # reset form data upon capture
51
52
            form.fullname.data = '' # reset form data upon capture

53
            return redirect(url_for('request_sent', username=username))
54

55
        return render_template('auth/SignUp.html', form=form, user=username)
56

57
58
59
60
61
    @app.route('/request_sent/<username>')
    def request_sent(username):

        fullname = session.get('fullname', None)
        reason = session.get('reason', None)
62

63
        global return_url
64
        global time_stamp
65
66
        print(username, fullname, return_url, file=sys.stdout)

67
        # Deliver arguments to script. (for local vagrant implementation)
68
69
        tempString = 'ssh ohpc "sudo /opt/ohpc_user_create/user_create ' + username + " " + fullname + '"'
        print(tempString, file=sys.stdout)
70

71
        try:
72
73
            # 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)
74

75
            time_stamp = time.strftime("%m-%d-%Y_%H:%M:%S")
76
77
            directory = "flat_db/"
            complete_file_name = os.path.join(directory, time_stamp + "_" + username + ".txt")
78
79
80
81

            if not os.path.exists(directory):
                os.makedirs(directory)

82
83
            file = open(complete_file_name, "w") # create time stamped file to be queued

84
85
            file.write(fullname + "\n")
            file.write(reason)
86

87
            file.close()
88
89
            return "Hello"
            # return render_template("auth/request_received.html") # Todo: replace template with redirect
90
91
92
93
94
95
            # 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'))
96

97
    # misc page error catching
98

99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
    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)

120
121
122
123
124
125
126
127
128
129
130
131
132
    @app.errorhandler(403)
    def forbidden(error):
        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

    @app.errorhandler(500)
    def internal_server_error(error):
        return render_template('errors/500.html', title='Server Error'), 500

    return app