Beispiel #1
0
def login():
    """ Login function. This is is the first page the user sees.
    Unauthenticated users are also redirected here if they try to access something restricted.
    After logging in, it should then forward them to resource they requested.
    """
    logger.debug("request.args: {0}".format(request.args))
    logger.debug("request.form: {0}".format(request.form))
    ajaxRequest = validation.convertRequestToPythonBool("ajaxRequest", request.args)
    previousUsername = validation.extractValueFromNextOrRequest("previousUsername")

    errorValue = None
    nextValue = routing.getRedirectTarget()

    # Check for users and notify if there are none!
    if not db["config"].has_key("users") or not db["config"]["users"]:
        logger.fatal("No users found in database!")
        if serverParameters.debug:
            # It should be extremely unlikely for this condition to be met!
            logger.warning("Since we are debugging, adding users to the database automatically!")
            # Transactions saved in the function
            utilities.updateDBSensitiveParameters(dbRoot, debug = serverParameters.debug)

    # A post request Attempt to login the user in
    if request.method == "POST":
        # Validate the request.
        (errorValue, username, password) = validation.validateLoginPostRequest(request)

        # If there is an error, just drop through to return an error on the login page
        if errorValue == None:
            # Validate user
            validUser = auth.authenticateUser(username, password, db)

            # Return user if successful
            if validUser is not None:
                # Login the user into flask
                login_user(validUser, remember=True)

                flash("Login Success for {0}.".format(validUser.id))
                logger.info("Login Success for {0}.".format(validUser.id))

                return routing.redirectBack("index")
            else:
                errorValue = "Login failed with invalid credentials"

    if previousUsername == serverParameters.defaultUsername:
        logger.debug("Equal!")
    logger.debug("serverParameters.defaultUsername: {0}".format(serverParameters.defaultUsername))
    # If we are not authenticated and we have a default username set and the previous username is 
    if not current_user.is_authenticated and serverParameters.defaultUsername and previousUsername != serverParameters.defaultUsername:
        # Clear previous flashes which will be confusing to the user
        # See: https://stackoverflow.com/a/19525521
        session.pop('_flashes', None)
        # Get the default user
        defaultUser = auth.User.getUser(serverParameters.defaultUsername, db)
        # Login the user into flask
        login_user(defaultUser, remember=True)
        # Note for the user
        logger.info("Logged into user \"{0}\" automatically!".format(current_user.id))
        flash("Logged into user \"{0}\" automatically!".format(current_user.id))

    # If we visit the login page, but we are already authenticated, then send to the index page.
    if current_user.is_authenticated:
        logger.info("Redirecting logged in user \"{0}\" to index...".format(current_user.id))
        return redirect(url_for("index", ajaxRequest = json.dumps(ajaxRequest)))

    if ajaxRequest == False:
        return render_template("login.html", error=errorValue, nextValue=nextValue)
    else:
        drawerContent = ""
        mainContent = render_template("loginMainContent.html", error=errorValue, nextValue=nextValue)
        return jsonify(drawerContent = drawerContent, mainContent = mainContent)
print("parentFolder: ", parentFolder)
# Adds to the import path
sys.path.insert(0, parentFolder)
# Sets the execution folder
os.chdir(parentFolder)

# Server configuration
from config.processingParams import processingParameters
from config import sensitiveParams

# Get the most useful fucntions
from processRuns import utilities

import logging
# By not setting a name, we get everything!
logger = logging.getLogger("")
# Alternatively, we could set processRuns to get everything derived from that
#logger = logging.getLogger("processRuns")

# Setup logging
utilities.setupLogging(logger, processingParameters.loggingLevel, processingParameters.debug, "processRuns")
# Log settings
logger.info(processingParameters.printSettings())

if __name__ == "__main__":
    (db, connection) = utilities.getDB(processingParameters.databaseLocation)
    utilities.updateDBSensitiveParameters(db = db, debug = processingParameters.debug)

    # Close the database connection
    connection.close()