Exemple #1
0
def logout():
    """
    Logout the current user.
    """
    logger.info('User {} logged out of the admin interface on {}'.format(current_user.user_email, datetime.now()))
    logout_user()
    return render_template("logout.html")
Exemple #2
0
    def post(self):
        request_args_dict = {
            'user_auth_token': fields.Str(required=True),
            'shared_to_guid': fields.Str(required=True),
        }
        request_args = parser.parse(request_args_dict, request)
        user_auth_token = request_args['user_auth_token']
        shared_to_guid = request_args['shared_to_guid']

        user_auth_record = AuthTokens.query.filter_by(auth_key=user_auth_token).first()
        share = ListShareMatrix.query.filter_by(shared_by_guid=user_auth_token,
                                                shared_to_guid=shared_to_guid).first()
        if share and user_auth_record:
            # take this occasion to delete old share inits that are older than 24 hours
            # clean old shares that have not been completed.
            current_time = datetime.datetime.utcnow()
            twenty_four_hours_ago = current_time - datetime.timedelta(hours=24)
            old_session_deleted_count = db.session.query(ListShareMatrix) \
                .filter(date_created < twenty_four_hours_ago, shared_to_guid="") \
                .delete()

            if old_session_deleted_count > 0:
                logger.info("{} old share inits have been deleted.".format(old_session_deleted_count))

            ListShareMatrix.query.where(shared_by_guid=user_auth_token, shared_to_guid=user_auth_token).delete()

            return jsonify(share_code=share.share_code,
                           is_share_successful=True,
                           share_init_error_message="")
        else:
            return jsonify(share_code="",
                           is_share_successful=False,
                           share_init_error_message="The shopping list was not found on the server.")
Exemple #3
0
def initialize_database(app):
    with app.app_context():
        logger.info('The database is being initialized for the first time.')
        db.create_all()

        logger.info(' A new api key is being created for testing. ')
        test_api_key = APIAuthRecord(
            'L37Iv0xi5JcF349DzEyj49MIFofYUcDAlOLp8HbtiIQ', '0.0.0.0',
            'test api key')
        db.session.add(test_api_key)
        db.session.commit()
Exemple #4
0
    def post(self):

        register_args = {
            'userName': fields.Str(required=True),
            'password': fields.Str(required=True),
            'firstName': fields.Str(required=False),
            'lastName': fields.Str(required=False)
        }

        request_args = parser.parse(register_args, request)

        userEmail = request_args['userName']
        password = request_args['password']
        firstName = request_args['firstName']
        lastName = request_args['lastName']

        # check if the users already exists
        user = UserAccount.query.filter_by(user_email=userEmail).first()
        if user:
            logger.error("User with email {} already exists. Registration failed.".format(userEmail))
            return jsonify(authToken="",
                           isRegistrationSuccessful=False,
                           registrationErrorMessage="User with email {} already exists. Registration failed.".format(
                               userEmail))
        else:
            authToken = generate_hash_key()

            new_user_guid = generate_hash_key()
            user_account = UserAccount(userEmail, password, new_user_guid, False, datetime.now())
            user_profile = UserProfile(new_user_guid, firstName, lastName)
            user_auth_token = AuthTokens(new_user_guid, authToken, -1)

            db.session.add(user_account)
            db.session.add(user_profile)
            db.session.add(user_auth_token)

            db.session.commit()

            logger.info("New user registered with email {}.".format(userEmail))

            return jsonify(authToken=authToken,
                           isRegistrationSuccessful=True,
                           registrationErrorMessage="")
Exemple #5
0
    def post(self):
        login_args = {
            'userEmail': fields.Str(required=True),
            'password': fields.Str(required=True)
        }

        request_args = parser.parse(login_args, request)

        userEmail = request_args['userEmail']
        password = request_args['password']

        if userEmail is None or password is None:
            logger.error("User name or password is empty. Login cannot continue.")
            return jsonify(isLoginSuccessful=False, access_token="")

        user = UserAccount.query.filter_by(user_email=userEmail).first()
        if user:
            # generate the password hash and compare to the one in the database
            hash_algo = hashlib.sha512()
            hash_algo.update(base64.b64encode(password) + user.password_salt)
            password_digest = hash_algo.hexdigest()

            if password_digest == user.password_digest:
                auth = AuthTokens.query.filter_by(user_guid=user.user_guid).first()

                if auth:
                    user.last_login = datetime.now()
                    db.session.add(user)
                    db.session.commit()
                    logger.info('User {} logged in.'.format(userEmail))
                    return jsonify(isLoginSuccessful=True, access_token=auth.auth_key)
                else:
                    logger.error("A user with this email exists but does not have auth token. Login cannot proceed.")
                    return jsonify(isLoginSuccessful=False, access_token="")
            else:
                logger.error("Incorrect password. Login failed.")
                return jsonify(isLoginSuccessful=False, access_token="")
        else:
            logger.error("No user found by the user email {}. Login failed.".format(userEmail))
            return jsonify(isLoginSuccessful=False, access_token="")
Exemple #6
0
def initialize_application(app):
    # create the directory for the database if it does not exist. This might happen if the app is being run for the
    # first time.
    if not os.path.exists(DB_DIRECTORY):
        logger.info('Database directory does not exist. Creating...')
        os.makedirs(DB_DIRECTORY)

    # create and initialize the database if it does not exist.
    if not os.path.isfile(app.config['SQLALCHEMY_DATABASE_URI']):
        logger.info("Data base file is missing {}".format(
            app.config['SQLALCHEMY_DATABASE_URI']))
        initialize_database(app)

    # check if there are any uses in the system. If there are none create at least one admin user to be able to access
    # the system.
    with app.app_context():
        users = UserAccount.query.all()
        if not users:
            logger.info(
                'There are no users in the database. Creating an admin user account with default settings.'
            )
            new_user_guid = generate_hash_key()
            admin_user = UserAccount('*****@*****.**', 'Up@8dHgd',
                                     new_user_guid, False, datetime.now())
            db.session.add(admin_user)
            db.session.commit()
Exemple #7
0
# the lines below are only used for debugging when we start the app manually using python xxxx.py
# command. If the application has never been initialized use the lines below to setup the database.
from achat_logging import logger
from wsgi import initialize_application, application

if __name__ == '__main__':
    initialize_application(application)
    logger.info("Application directly started by calling from command line.")
    application.run(host='0.0.0.0', debug=True)
Exemple #8
0
 def get(self):
     logger.info("Echo called with some ip")
     return jsonify(status=202, message='Everything ok.', caller_ip=get_client_ip())
Exemple #9
0
def initialize_application(app):
    # create the directory for the database if it does not exist. This might happen if the app is being run for the
    # first time.
    if not os.path.exists(DB_DIRECTORY):
        logger.info('Database directory does not exist. Creating...')
        os.makedirs(DB_DIRECTORY)

    # create and initialize the database if it does not exist.
    if not os.path.isfile(app.config['SQLALCHEMY_DATABASE_URI']):
        logger.info("Data base file is missing {}".format(
            app.config['SQLALCHEMY_DATABASE_URI']))
        initialize_database(app)

    # check if there are any uses in the system. If there are none create at least one admin user to be able to access
    # the system.
    with app.app_context():
        users = UserAccount.query.all()
        if not users:
            logger.info(
                'There are no users in the database. Creating an admin user account with default settings.'
            )
            new_user_guid = generate_hash_key()
            admin_user = UserAccount('*****@*****.**', 'Up@8dHgd',
                                     new_user_guid, False, datetime.now())
            db.session.add(admin_user)
            db.session.commit()


application = create_app()
logger.info("Application (re)started.")