示例#1
0
    def get_user_info(username):
        user_obj = get_user(username)
        user_info = load_user(user_obj)

        resp = Message(True, "user data sent.")
        resp["user"] = user_info
        return resp, 200
示例#2
0
    def get(fact_public_id):
        fact = Fact.query.filter_by(public_id=fact_public_id).first()

        if not fact:
            return ErrResp("Fact not found!", "fact_404", 404)

        fact_info = load_fact(fact)

        resp = Message(True, "Fact data sent.")
        resp["fact"] = fact_info
        return resp, 200
示例#3
0
    def get(limit):
        if limit > 100:
            return ErrResp("You have exceeded the limit (100)",
                           "limits_exceeded", 400)

        # Get random facts based on limits
        random_facts = Fact.query.order_by(func.random()).limit(limit)

        # Load their info
        random_facts_info = facts_schema.dump(random_facts)

        resp = Message(True, "Random facts sent!")
        resp["facts"] = random_facts_info
        return resp, 200
示例#4
0
    def delete(fact_public_id, current_user):
        fact = Fact.query.filter_by(public_id=fact_public_id).first()

        if not fact:
            return ErrResp("Fact not found!", "fact_404", 404)

        # Check fact owner
        elif current_user.id == fact.author_id:
            try:
                delete_fact(fact)

                resp = Message(True, "Fact has been deleted.")
                return resp, 200

            except Exception as error:
                current_app.logger.error(error)
                return InternalErrResp()

        return ErrResp("Insufficient permissions!", "insufficient_permission",
                       403)
示例#5
0
    def get_by_planet(planet_name, limit):
        if limit > 100:
            return ErrResp("You have exceeded the limit (100)",
                           "limits_exceeded", 400)

        # Get random facts that belongs to that planet
        if planet_name not in solar_planets:
            return ErrResp(
                "Planet not found!",
                "planet_404",
                404,
            )

        planet_random_facts = (Fact.query.filter_by(
            planet=planet_name).order_by(func.random()).limit(10))

        # Load their info
        planet_random_facts_info = facts_schema.dump(planet_random_facts)

        resp = Message(True, "Planet's random facts sent.")
        resp["facts"] = planet_random_facts_info
        return resp, 200
示例#6
0
    def update(fact_public_id, data, current_user):
        fact = Fact.query.filter_by(public_id=fact_public_id).first()

        if not fact:
            return ErrResp("Fact not found!", "fact_404", 404)

        # Check owner
        elif current_user.id == fact.author_id:
            if not data["content"]:
                return ErrResp("Update content not found!", "content_404", 400)

            try:
                update_fact(fact, data["content"])

                resp = Message(True, "Fact content updated.")
                return resp, 200

            except Exception as error:
                current_app.logger.error(error)
                return InternalErrResp()

        return ErrResp("Insufficient permissions!", "insufficient_permissions",
                       403)
示例#7
0
    def login_user(data):
        # Assign the vars
        email = data["email"]
        password = data["password"]

        try:
            # Check if the email or password was provided
            if not email or not password:
                return ErrResp("Credentials not fully provided!",
                               "invalid_credentials", 400)

            # Fetch user data
            user = User.query.filter_by(email=email).first()
            if not user:
                return ErrResp(
                    "The email you have entered does not match any account.",
                    "account_404",
                    404,
                )

            elif user and user.check_password(password):
                user_info = load_user(user)
                access_token = create_access_token(identity=user.id)

                if access_token:
                    resp = Message(True, "Logged user in.")
                    resp["Authorization"] = access_token
                    resp["user"] = user_info
                    return resp, 200

            # Return incorrect password if others fail
            return ErrResp("Failed to login, password may be incorrect.",
                           "invalid_password", 403)

        except Exception as error:
            current_app.logger.error(error)
            InternalErrResp()
示例#8
0
    def register(data):
        try:
            # Assign the vars
            email = data["email"]
            username = data["username"]
            full_name = data["full_name"]
            password = data["password"]

            # Check if email exists
            if len(email) == 0 or email is None:
                return ErrResp("Email is required!", "invalid_email", 400)

            # Check if the email is being used
            if User.query.filter_by(email=email).first() is not None:
                return ErrResp("Email is used by another account.",
                               "email_used", 403)

            # Check if the email is valid
            elif not EMAIl_REGEX.match(email):
                return ErrResp("Invalid email!", "email_invalid", 400)

            # Check if the username is empty
            if len(username) == 0 or username is None:
                return ErrResp("Username is required!", "invalid_username",
                               400)

            # Check if the username is being used
            elif User.query.filter_by(username=username).first() is not None:
                return ErrResp("Username is already taken!", "username_taken",
                               403)

            # Check if the username is equal to or between 4 and 15
            elif not 4 <= len(username) <= 15:
                return ErrResp("Username length is invalid!",
                               "invalid_username", 400)

            # Check if the username is alpha numeric
            elif not username.isalnum():
                return ErrResp("Username is not alpha numeric.",
                               "username_not_alphanum", 400)

            # Verify the full name and if it exists
            if len(full_name) == 0 or full_name is None:
                full_name = None

            else:
                # Validate the full name
                # Remove any spaces so that it properly checks.
                if not full_name.replace(" ", "").isalpha():
                    return ErrResp("Name is not alphabetical.", "invalid_name",
                                   400)

                # Check if the full name is equal to or between 2 and 50
                elif not 2 <= len(full_name) <= 50:
                    return ErrResp("Name length is invalid.", "invalid_name",
                                   400)

                # Replace multiple spaces with one.
                # 'firstName    lastName' -> 'firstName lastName'
                re.sub(" +", " ", full_name)

            # Create new user object
            new_user = User(
                email=email,
                username=username,
                full_name=full_name,
                password=password,
                joined_date=datetime.utcnow(),
            )

            # Add and commit the user to the database
            db.session.add(new_user)
            db.session.flush()

            # Get the user's info
            user_info = load_user(new_user)

            # Save changes
            db.session.commit()

            # Return success response
            access_token = create_access_token(identity=new_user.id)

            resp = Message(True, "User has been registered.")
            resp["Authorization"] = access_token
            resp["user"] = user_info
            return resp, 201

        except Exception as error:
            current_app.logger.error(error)
            InternalErrResp()
示例#9
0
    def create(data, current_user):
        # Assign the vars
        content = data["content"]
        planet = data["planet"]

        # Set limits
        content_limit = 500
        title_limit = 50

        if data["title"] is not None:
            title = data["title"]

            # Validate title
            if len(title) > title_limit:
                return ErrResp(
                    f"Given data exceeds limits (Title: {title_limit}, Content: {content_limit})",
                    "exceeded_limits",
                    400,
                )
        else:
            title = None

        # Check if the content doesn't exceed limits
        if not content:
            return ErrResp("Required items are empty", "data_404", 400)

        # Make sure content and title don't exceed their limits
        elif len(content) > content_limit:
            return ErrResp(
                f"Given data exceeds limits (Title: {title_limit}, Content: {content_limit})",
                "exceeded_limits",
                400,
            )

        if planet.title() not in solar_planets:
            return ErrResp(
                f"The planet specified is not in the solar system!\
                  If it is just a general knowledge fact, use 'unspecified'",
                "planet_unknown",
                400,
            )

        try:
            public_id = str(uuid4())[:15]
            new_fact = Fact(
                public_id=public_id,
                author_id=current_user.id,
                planet=planet.title(),
                title=title,
                content=content,
            )

            latest_fact = add_fact_and_flush(new_fact)

            resp = Message(True, "Fact added.")
            resp["fact"] = latest_fact
            return resp, 201

        except Exception as error:
            current_app.logger.error(error)
            return InternalErrResp()