示例#1
0
def getAll(**kwargs):
    session = create_session()
    token = kwargs.get("token_info").get("token")
    user_q = decode_auth_token(session, token)
    if not user_q.is_admin:
        return "No autorizado", 401
    user_schema = UserSchema(exclude=["password", "id"])
    user_q_list = get_all_users_by_kwargs(session)
    data = user_schema.dump(user_q_list, many=True)
    return data, 200
    def test_user_schema_deserialization_succeeds(self):
        """Test the user data deserialization."""

        schema = UserSchema()

        user = schema.load_into_schema(USER_DATA, partial=True)

        user_deserialized = {
            'last_name': USER_DATA['lastname'],
            'password': USER_DATA['password'],
            'email': USER_DATA['email'],
            'first_name': USER_DATA['firstname']
        }

        assert user == user_deserialized
示例#3
0
    def post(self):
        """Post request for user registration"""

        # instantiate the user schema
        user_schema = UserSchema()

        # get the request data in json format
        request_json = request.get_json()

        # serialize and validate the request
        user_details = user_schema.load_into_schema(request_json, partial=True)
        user_details['first_name'] = user_details['first_name'].strip()
        user_details['last_name'] = user_details['last_name'].strip()

        # check if the user already exist
        found_user = User.query_(email=user_details['email']).first()
        if found_user:
            return {
                'status': 'error',
                'message': MESSAGES['DUPLICATES'].format(found_user.email)
            }, 409

        # hash password
        user_details['password'] = Encryption.hash(user_details['password'])

        # generate a random unique username
        user_details['username'] = push_id.next_id()[8:]

        link, user_details['token'] = generate_link(request, user_details)

        # save to database and serialize the returned user data
        saved_user = User(**user_details).save()

        # if the save was successful, send out the verification email and
        # return a success message.
        if saved_user:
            MailGun.with_api(
                saved_user.email,
                email_verification.format(style, link, 'Verification Link'),
                'Email verification')

            return {
                'status': 'success',
                'message': MESSAGES['REGISTER'],
            }, 201
    def post(self):
        """Post request to reset password"""

        # instantiate the user schema
        schema = UserSchema(only=['id', 'email', 'verified'])

        # get the request data in json format
        request_json = request.get_json()

        # serialize and find the user data in the database
        user = schema.load_into_schema(request_json, partial=True)
        found_user = User.query_(email=user['email'], deleted=False).first()

        # throw an error if not found
        if not found_user:
            return {'status': 'error', 'message': MESSAGES['NOT_FOUND']}, 404

        # throw an error if user is found but not yet verified
        if found_user and not found_user.verified:
            return {
                'status': 'error',
                'message': MESSAGES['NOT_VERIFIED']
            }, 401

        else:
            # generate a reset token and link
            link, user['password_reset'] = generate_link(request,
                                                         user,
                                                         type='password_reset')

            # send the link to the email provided
            MailGun.with_api(
                found_user.email,
                email_verification.format(style, link, 'Reset your password'),
                'Password Reset')

            # update the user data
            found_user.update_(**user)

            # return success messages
            return {
                'status': 'success',
                'message': MESSAGES['RESET_LINK'],
            }, 200
示例#5
0
    def post(self):
        """Post request for user login"""

        # initialize the schema
        schema = UserSchema()

        # get the request details as json
        request_json = request.get_json()

        # serialize and find the user data in the database
        user_details = schema.load_into_schema(request_json, partial=True)
        found_user = User.query_(email=user_details['email'], deleted=False)\
            .first()

        # throw an error if not found
        if not found_user:
            return {'status': 'error', 'message': MESSAGES['NOT_FOUND']}, 404

        # deserialize the user data if found, and verify the password
        user = schema.dump(found_user).data
        is_match = Encryption.verify(user['password'],
                                     user_details['password'])

        # if password did not match throw an error
        if not is_match:
            return {
                'status': 'error',
                'message': MESSAGES['UNAUTHORIZED']
            }, 401

        else:

            # format the data and generate a JWT token.
            formatted_data = format_user(user)
            token = Encryption.tokenize(
                formatted_data, subject='User_Login', days=14)

            return {
                'status': 'success',
                'message': MESSAGES['LOGIN'],
                'data': {
                    'token': token,
                }
            }, 200
示例#6
0
    def get(self):
        try:

            # Get usernames.
            usernames = [] if request.args.get(
                'usernames') is None else request.args.get('usernames').split(
                    ',')

            # Get emails.
            emails = [] if request.args.get(
                'emails') is None else request.args.get('emails').split(',')

            # Get start date.
            start_date = datetime.strptime(request.args.get('start_date'),
                                           '%d.%m.%Y')

            # Get end date.
            end_date = datetime.strptime(request.args.get('end_date'),
                                         '%d.%m.%Y')

            # Filter users by usernames, emails and range of date.
            users = User.query\
                .filter(User.username.in_(usernames))\
                .filter(User.email.in_(emails))\
                .filter(User.created.between(start_date, end_date))\
                .all()

            # Create user schema for serializing.
            user_schema = UserSchema(many=True)

            # Get json data
            data, errors = user_schema.dump(users)

            # Return json data from db.
            return data

        except Exception as why:

            # Log the error.
            logging.error(why)

            # Return error.
            return error.INVALID_INPUT_422
示例#7
0
    def test_get(self, new_user):
        """Test that we can get data from the model.

        Args:
            new_user (func): Creates new user to the database.

        Returns:
            None

        """

        new_user.save()

        schema = UserSchema(many=True)
        user = schema.dump(User.query_()).data[0]

        assert user['firstName'] == FIXTURE_NEW_USER['first_name']
        assert user['lastName'] == FIXTURE_NEW_USER['last_name']
        assert user['email'] == FIXTURE_NEW_USER['email']
示例#8
0
    def get(self, email):
        """Get request to resend the user's verification link.

        Args:
            email (str): The email to send the verification link to

        Returns:
            JSON: The json response

        """

        # initialize the schema
        user_schema = UserSchema(only=['token', 'email', 'verified'])

        # find the email
        found_user = User.query_(email=email).first()

        # throw an error if not found
        if not found_user:
            return {'status': 'error', 'message': MESSAGES['NOT_FOUND']}, 404

        # throw an error if the user is not verified
        if found_user.verified:
            return {'status': 'error', 'message': MESSAGES['VERIFIED']}, 409

        # deserialize the user data and generate the verification link
        user_details = user_schema.dump(found_user).data
        link, user_details['token'] = generate_link(request, user_details)

        # updates the user in the database
        found_user.update_(**user_details)

        # sends out the email verification link
        MailGun.with_api(
            found_user.email,
            email_verification.format(style, link, 'Click to Verify'),
            'Email verification')

        # return a success message upon completion
        return {
            'status': 'success',
            'message': MESSAGES['RESEND_EMAIL'],
        }, 200
    def patch(self):
        """patch request to reset the user's password"""

        # instantiate the user schema
        user_schema = UserSchema()

        # get the verification_token from the request params
        reset_token = request.args.get('token')

        # get the request data in json format
        request_json = request.get_json()

        # check if the token is valid
        # serialize the request data and
        # look for the token in the database
        Encryption.detokenize(reset_token)
        user_details = user_schema.load_into_schema(request_json, partial=True)
        found_token = User.query_(password_reset=reset_token).first()

        # throw an error if not found
        if not found_token:
            return {
                'status': 'error',
                'message': MESSAGES['RESET_LINK_RESEND']
            }, 404

        else:
            # set the password reset column to none
            user_details['password_reset'] = None

            # hash the new password and update the password
            user_details['password'] = Encryption.hash(
                user_details['password'])
            found_token.update_(**user_details)

            return {
                'status':
                'success',
                'message':
                MESSAGES['PROCEED_TO_LOGIN'].format(
                    'Your password has been changed')
            }, 200
    def test_user_schema_serialization_succeeds(self, new_user):
        """Test the user data deserialization.

        Args:
            new_user (func): Creates new user to the database.

        Returns:
            None

        """

        schema = UserSchema(exclude=EXCLUDES)

        user = new_user.save()

        user_data_object = schema.dump(user).data

        assert FIXTURE_NEW_USER['first_name'] == user_data_object['firstName']
        assert FIXTURE_NEW_USER['last_name'] == user_data_object['lastName']
        assert FIXTURE_NEW_USER['email'] == user_data_object['email']
示例#11
0
def post(body):
    try:
        user_schema = UserSchema()
        errors = user_schema.validate(body)
        if errors:
            return errors, 400
        session = create_session()
        user_q = check_user_by_username_or_email(session, body.get('username'),
                                                 body.get('email'))
        if user_q is not None:
            if user_q.email == body.get(
                    'email') and user_q.username == body.get('username'):
                session.close()
                return "Usuario ya existente"
            if user_q.email == body.get('email'):
                session.close()
                return "Correo ya esta assignado", 404
            elif user_q.username == body.get('username'):
                session.close()
                return "Nombre usuario ya esta assignado", 404
        data = {
            'username': body.get('username'),
            'password': body.get('password'),
            'email': body.get('email')
        }
        user = create_user(session, data)
        created = user is not None
        if created:
            role_q = get_role_by_name(session, "user")
            user_role = {'user_id': user.id, 'role_id': role_q.id}
            insert_into_user_role(session, user_role)
            user_q = get_user_by_query(session, **data)
            session.close()
            send_activate_user(user_q.email, user_q.public_id)
            return "Usuario creado", 204
        else:
            session.close()
            return "Bad Request", 400
    except Exception as err:
        print(err)
        return "Bad Request", 400
    def test_user_schema_raises_exception(self):
        """Test the user schema validation exception."""

        schema = UserSchema()
        with pytest.raises(ValidationError):
            schema.load_into_schema(USER_DATA)