Exemple #1
0
def login():
    form = LoginForm()
    if form.validate_on_submit():

        user = UserAccount.query.filter_by(user_email=form.email.data).first()
        if user:
            # generate the password hash and compare to the one in the database

            hash_algo = hashlib.sha512()
            hash_algo.update(base64.b64encode(form.password.data) + user.password_salt)
            password_digest = hash_algo.hexdigest()

            if password_digest == user.password_digest:
                user.authenticated = True
                db.session.add(user)
                db.session.commit()
                login_user(user, remember=True)
                logger.warn('User {} successfully logged into the admin interface on {}'.format(user.user_email,
                                                                                                datetime.now()))
                return redirect(url_for('admin.get_api_keys'))
            else:
                logger.error('wrong password, failed to log into the admin interface.')
        else:
            logger.error('The user email passed does not exist in the user database.')

    return render_template('login.html', form=form)
Exemple #2
0
    def post(self):
        try:
            list_add_args = {
                'user_auth_token': fields.Str(required=True),
                'list_guid': fields.Str(required=True),
                'item_name': fields.Str(required=True),
                'item_description': fields.Str(required=False),
                'item_quantity': fields.Int(missing=1)
            }

            request_args = parser.parse(list_add_args, request)

            user_auth_token = request_args['user_auth_token']
            list_guid = request_args['list_guid']
            item_name = request_args['item_name']
            item_desc = request_args['item_description']
            item_quantity = request_args['item_quantity']

            user_auth_record = AuthTokens.query.filter_by(auth_key=user_auth_token).first()
            shopping_list = ShoppingList.query.filter_by(list_guid=list_guid,
                                                         user_guid=user_auth_record.user_guid).first()
            if shopping_list:
                new_item = ShoppingItem(list_guid, item_name, item_desc, "", item_quantity, "")
                db.session.add(new_item)
                db.session.commit()

            return jsonify(isItemAddSuccessful=True,
                           itemAddErrorMessage="")

        except Exception as e:
            logger.error(e)
            return jsonify(isItemAddSuccessful=True,
                           itemAddErrorMessage=e)
Exemple #3
0
    def post(self):
        try:
            list_add_args = {
                'user_auth_token': fields.Str(required=True),
                'listName': fields.Str(required=True),
                'description': fields.Str(required=False)
            }

            request_args = parser.parse(list_add_args, request)

            user_auth_token = request_args['user_auth_token']
            listName = request_args['listName']
            description = request_args['description']

            user_auth_record = AuthTokens.query.filter_by(auth_key=user_auth_token).first()
            list_guid = generate_hash_key()
            new_list = ShoppingList(user_auth_record.user_guid, list_guid, listName, description)
            db.session.add(new_list)
            db.session.commit()

            return jsonify(isListAddSuccessful=True,
                           listAddErrorMessage="")

        except Exception as e:
            logger.error(str(e))
            return jsonify(isListAddSuccessful=False,
                           listAddErrorMessage="An exception occurred while adding list to database.")
Exemple #4
0
 def get(self):
     try:
         user_args = {'user_auth_token': fields.Str()}
         request_args = parser.parse(user_args, request)
         user_auth_token = request_args['user_auth_token']
         user_auth_record = AuthTokens.query.filter_by(auth_key=user_auth_token).first()
         lists = ShoppingList.query.filter_by(user_guid=user_auth_record.user_guid).all()
         return_list = []
         if lists:
             for l in lists:
                 return_list.append(l.serialize())
             return Response(json.dumps(return_list), mimetype='application/json')
         else:
             return None
     except Exception as e:
         logger.error(e)
Exemple #5
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 #6
0
def match_user_auth_token(key):
    """
    Match API keys and discard ip
    @param key: API key from request
    @param ip: remote host IP to match the key.
    @return: boolean
    """
    if key is None:
        logger.error(
            'Either the user auth key is missing. This is an unauthorized attempt to access services.'
        )
        return False
    auth = get_user_auth_object_by_keyid(key)
    if auth is None:
        logger.error(
            "The auth record for the auth_key_token {} is not found.".format(
                key))
        return False
    else:
        return True
Exemple #7
0
    def get(self):
        try:
            request_args_dict = {
                'user_auth_token': fields.Str(required=True)
            }
            request_args = parser.parse(request_args_dict, request)
            user_auth_token = request_args['user_auth_token']

            user_auth_record = AuthTokens.query.filter_by(auth_key=user_auth_token).first()
            shopping_lists = ShoppingList.query.filter_by(user_guid=user_auth_record.user_guid).all()
            return_list_items = []
            if shopping_lists:
                for s in shopping_lists:
                    list_items = ShoppingItem.query.filter_by(list_guid=s.list_guid).all()
                    for item in list_items:
                        return_list_items.append(item.serialize())
                return Response(json.dumps(return_list_items), mimetype='application/json')
            else:
                return Response(json.dumps(return_list_items), mimetype='application/json')
        except Exception as e:
            logger.error(e)
Exemple #8
0
def match_api_keys(key, ip):
    """
    Match API keys and discard ip
    @param key: API key from request
    @param ip: remote host IP to match the key.
    @return: boolean
    """
    if key is None or ip is None:
        logger.error(
            'Either the api key or ip address is missing. This is an unauthorized attempt to access services.'
        )
        return False
    api_key = get_apiauth_object_by_key(key)
    if api_key is None:
        logger.error(
            'Someone from ip address {} is attempting to access the service without a valid api key.'
            .format(ip))
        return False
    elif api_key.ip == "0.0.0.0":  # 0.0.0.0 means all IPs.
        return True
    elif api_key.key == key and api_key.ip == ip:
        return True

    logger.error(
        'Someone from ip address {} is trying to access the service with a valid api key that is not assigned to this ip.'
        .format(ip))
    return False
Exemple #9
0
 def decorated(*args, **kwargs):
     try:
         request_args = parser.parse(user_args, request)
         if request_args is None:
             logger.error("Cannot parse request to get the required arg.")
             abort(401)
         token = request_args['user_auth_token']
         if token is None:
             logger.error(
                 "Request does not contain any arg user_auth_token")
             abort(401)
         if match_user_auth_token(token):
             return f(*args, **kwargs)
         else:
             logger.error(
                 "Method does not qualify the required conditions. Could not find it in db."
             )
             abort(401)
     except Exception as e:
         logger.error(e)
         abort(401)
Exemple #10
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="")