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

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
13
from flask_wtf import FlaskForm
14
from flask_bootstrap import Bootstrap
15
from wtforms import StringField, SubmitField, validators
16

17
18
19
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from watchdog.utils import dirsnapshot
20
21


22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
global snap_before
global snap_after
global snap_diff
global observing
global time_stamp

observing = False


class MyHandler(FileSystemEventHandler): # Watchdog handler class to take action when observation requested
    def on_modified(self, event):

        global snap_before
        global snap_after
        global snap_diff
        global observing
        global time_stamp

        # print(event.src_path + " modified.")
        snap_after = dirsnapshot.DirectorySnapshot("/home/reggie/flat_db", True) # take post flat_db creation snapshot of the directory
        snap_diff = dirsnapshot.DirectorySnapshotDiff(snap_before, snap_after) # object to compare the initial snapshot with the final snapshot

        try:

            if ("/home/reggie/flat_db/" + time_stamp + ".done") in snap_diff.files_moved[0]: # check for timestamped string with .done extention in flat_db

                observing = False
                # print("YES!")
        except Exception as e:
            print(e)
        # print("Created: ", snap_diff.files_created)
        # print("Deleted: ", snap_diff.files_deleted)
        # print("Modified: ", snap_diff.files_modified)
        # print("Moved: ", snap_diff.files_moved)

    def on_created(self, event):

        print(event.src_path + " created.")


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

66
67
    global return_url
    return_url = ''
68

69
70
71
    class MainForm(FlaskForm): # class for the form itself
        fullname = StringField('Full Name: ', [validators.DataRequired(), ])
        submit = SubmitField('Submit')
72

73
74
75
76
    @app.route('/', methods=['GET', 'POST']) # initial route to display the reg page
    def index():
        global return_url
        username = request.remote_user
77

78
        if "redir" in request.args and return_url == "": # check for redir arg in url
79
            return_url = request.args.get("redir") or "/pun/sys/dashboard"
80
            if name != "":
81

82
83
84
85
86
87
88
        fullname = False
        form = MainForm() # initialize form object
        if form.is_submitted():
            fullname = form.fullname.data
            form.fullname.data = '' # reset form data upon capture

            return redirect(url_for('success', username=str(username), fullname=fullname))
89

90
        return render_template('auth/SignUp.html', form=form, user=username)
91

92
93
    @app.route('/success/<username>/<fullname>')
    def success(username, fullname):
94

95
        global return_url
96
97
98
        global snap_before
        global observing
        global time_stamp
99
100
        print(username, fullname, return_url, file=sys.stdout)

101
        # Deliver arguments to script. (for local vagrant implementation)
102
103
        tempString = 'ssh ohpc "sudo /opt/ohpc_user_create/user_create ' + username + " " + fullname + '"'
        print(tempString, file=sys.stdout)
104

105
        try:
106
107
            # 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)
108

109
            time_stamp = time.strftime("%m-%d-%Y_%H:%M:%S")
110
111
            directory = "/home/reggie/flat_db/"
            complete_file_name = os.path.join(directory, time_stamp + "_" + request.remote_user + ".txt")
112
113
114
115

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

116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
            event_handler = MyHandler() # initialize handler
            observer = Observer() # initialize obsever to relay to handler
            observer.schedule(event_handler, path='/home/reggie/flat_db', recursive=True)
            observer.start()

            observing = True

            file = open(complete_file_name, "w") # create time stamped file to be queued
            file.write("Hey")

            # take an initial state snapshot of the db after file queued
            snap_before = dirsnapshot.DirectorySnapshot("/home/reggie/flat_db", True)

            while observing:
                # TODO: Update page ui element dynamically

                time.sleep(5)
            observer.stop()
134
            file.close()
135
136
137
138
139
140
141
            return render_template("errors/registration_failed.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'))
142

143
    # misc page error catching
144

145
146
147
148
149
150
151
152
153
154
155
156
157
    @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