示例#1
0
def authenticate_user(user: schemas.UserAuthenticate,
                      db: Session = Depends(get_db)):
    db_user = crud.get_user_by_username(db, username=user.username)
    if db_user is None:
        raise HTTPException(status_code=400, detail="Username not existed")
    else:
        try:
            is_password_correct = crud.check_username_password(db, user)
            if is_password_correct is False:
                raise HTTPException(status_code=400,
                                    detail="Password is not correct")
            else:
                from datetime import timedelta
                access_token_expires = timedelta(minutes=15)
                from crud import create_access_token
                access_token = create_access_token(
                    data={"sub": user.username},
                    expires_delta=access_token_expires)
            return_value = {
                "access_token": access_token,
                "token_type": "Bearer"
            }
            return crud.create_user(db=db, user=user)
        except Exception as e:
            print(e)
            raise HTTPException(status_code=501, detail="Error here")
示例#2
0
def display_book_info(book_id):
    """ A function that display info on a book and any comments that have been written about that book """

    if session['user']:
        current_user = crud.get_user_by_username(session['user'])
        book = crud.get_book_by_id(book_id)

        comments = crud.get_comments_by_book_id(book_id)
        print(comments, book, "COMMENTS")

        comment_list = []
        for comment in comments:
            print(comment.comment_text)
            comment_list.append({
                "text": comment.comment_text,
                "user": comment.user.user_name,
                "likes": comment.like_count,
                "post_date": comment.date_written
            })

        image_url = 'https' + str(book.cover_img_source)[4:]
        serialized_book = {
            'book_id': book.book_id,
            "title": book.title,
            'author': book.author,
            'publisher': book.publisher,
            'description': book.description,
            "img": image_url,
            "comments": comment_list
        }

    return jsonify(serialized_book)
def register_user():
    """Create a new user."""
    username = request.form['username']
    email = request.form['email']
    password = request.form['password']
    created_on = datetime.now()
    profile_picture = '/static/images/anon_whale.png'
    user_bio = ''
    website = ''
    birthday = datetime.now()

    username_check = crud.get_user_by_username(username)
    email_check = crud.get_user_by_email(email)

    if username_check:
        flash('Sorry, that username is already taken. Try again.')
        return redirect('/signup')

    elif email_check:
        flash('An account with that email already exists. Try again.')
        return redirect('/signup')

    else:
        crud.create_user(username, email, password, created_on,
                         profile_picture, user_bio, website, birthday)

        flash(
            Markup('Account created! Please \
                     <a href="/signin"class="alert-link">Sign In</a>'))
        return redirect('/signup')
示例#4
0
def make_dict_books_a_shelf(user, shelf):

    current_user = crud.get_user_by_username(user)

    if shelf == "all":
        books_on_shelf = crud.return_all_books_on_shelves_by_user(current_user.user_id)

    else: 
        books_on_shelf = crud.return_books_on_shelf_by_nickname(shelf, current_user.user_id)

    # print("RETREIVED BOOKS ON SEHFL", books_on_shelf)
    shelf_books = []
    for book in books_on_shelf: 
    #get sheleved book info : shelf id, bookid, reading and owned statuses
    #print("SHEVLEDBOOK ID",current_user, current_user.user_id, book.book_id)
        shelf_st = crud.get_shelvedbook(current_user.user_id, book.book_id)
        #print("SHELF", shelf_st, shelf_st.bookshelf.nickname)
        own_st = crud.get_owned_status(shelf_st.owned_status)
        reading_st = crud.get_reading_status(shelf_st.reading_status)
    # print("TRYING TO GET SHELF NAME", book, book.book_id, shelf_st, shelf_st.bookshelf.nickname, shelf_st.owned_status, shelf_st.reading_status)
    # print(reading_st, own_st)
        if book.cover_img_source.startswith('http'):
            image_url = 'https'+ str(book.cover_img_source)[4:]
    
        shelf_books.append({'book_id': book.book_id, "title":book.title, 
                        'author': book.author, 'publisher': book.publisher, 
                                'description':book.description, "img":image_url, 
                                'shelf_name': shelf_st.bookshelf.nickname,
                                'shelf_id':shelf_st.bookshelf.shelf_id,
                                'reading_stat':reading_st,
                                'owned_stat':own_st
                                 })

    return shelf_books
示例#5
0
def update_book_statuses():
    status_dict = request.get_json()
    print("\n\n\n STATUS DICTIONARY FROM ADD A BOOK", status_dict)

    if session['user']:
        print(session['user'])

        # update book reading statusif 'reading_status' in status_dict:
        if 'reading_status' in status_dict:
            shelved_book = utility.update_reading_status(
                session['user'], status_dict['book_id'],
                status_dict['reading_status'])
        else:
            shelved_book = utility.update_reading_status(
                session['user'], status_dict['book_id'])

        if 'shelf' and 'change_shelf' in status_dict:
            if status_dict['change_shelf']:
                current_user = crud.get_user_by_username(session['user'])
                shelved_book = crud.update_shelf_for_shelvedbook(
                    current_user.user_id, status_dict['book_id'],
                    status_dict['shelf'])

        # update book owned status
        if 'owned_status' in status_dict:
            shelved_book = utility.update_owned_status(
                session['user'], status_dict['book_id'],
                status_dict['owned_status'])
        else:
            shelved_book = utility.update_owned_status(session['user'],
                                                       status_dict['book_id'])

        print("IS IT SAVING TE RIGHT STATUS", shelved_book,
              shelved_book.reading_status, shelved_book.owned_status)
        return (jsonify({"shelved_book": shelved_book.book.title}))
示例#6
0
    def authenticate_user(
        user: schemas.UserAuthenticate, db: Session = Depends(get_db)
    ):
        db_user = crud.get_user_by_username(db, username=user.username)
        if db_user is None:
            raise HTTPException(status_code=400, detail="Username not existed")
        else:
            is_password_correct = crud.check_username_password(db, user)
            if is_password_correct is False:
                raise HTTPException(
                    status_code=400, detail="Password is not correct"
                )  # noqa
            else:
                from datetime import timedelta

                access_token_expires = timedelta(
                    minutes=ACCESS_TOKEN_EXPIRE_MINUTES
                )  # noqa
                from app_utils import create_access_token

                access_token = create_access_token(
                    data={"sub": user.username},
                    expires_delta=access_token_expires,  # noqa
                )
                return {"access_token": access_token, "token_type": "Bearer"}
示例#7
0
 def create_user(user: UserCreate, db: Session = Depends(get_db)):
     db_user = crud.get_user_by_username(db, username=user.username)
     if db_user:
         raise HTTPException(
             status_code=400, detail="Username already registered"
         )  # noqa
     return crud.create_user(db=db, user=user)
示例#8
0
def user_stocks():
    username = session['username']
    user = crud.get_user_by_username(username)
    user_id = user.id
    subscription = Subscription.query.filter(user_id == user_id).first()

    return render_template('mystocks.html')
示例#9
0
def upload_image(username):
    """Upload an image."""

    # Cannot upload an image to another user's account
    if username != current_user.username:
        return jsonify({'status': 'fail', 'message': 'Access denied.'}), 401

    image_file = request.files.get('image')
    cloudinary_upload = cloudinary.uploader.upload(image_file)
    image_url = cloudinary_upload['url']

    # Check if request wants to set permissions
    permission = None
    if request.form.get('permission'):
        permission = request.form.get('permission')

    # Create Image and catch errors such as providing incorrect
    # permission values other than PRVIATE or PUBLIC
    try:
        user = crud.get_user_by_username(current_user.username)
        image = crud.create_image(image_url, user, permission)
    except:
        return jsonify(error_msg), 500

    return jsonify({
        'status': 'success',
        'message': 'Image successfully uploaded.',
        'permission': image.permission.name,
        "image_url": image_url
    })
示例#10
0
def add_to_bookshelf():
    # def add_book_to_db(new_book_info, user, shelfname)

    info = request.get_json()
    # print("AT UPLOAD PHOTO SENT THIS INFO", info)
    # print(info, "GETTING A POST RESPONSE")
    file = info['filepath'].split("\\").pop()
    shelf = info['shelfname']
    current_user = crud.get_user_by_username(session['user'])
    new_photos = api.localize_objects_with_crop(
        f"static/images/demo_pics/{file}")
    # print(new_photos)
    book_titles = api.get_text_from_list_of_photos(new_photos)
    print('HERE ARE TE BOOK TITLES', book_titles)

    book_dictions = []
    for book in book_titles:
        got_book = api.find_google_book_data_onetitle(book)
        print(got_book, "PRINTING FIND GOOGLE BOOK DATA")
        if got_book:
            got_book = api.parse_response_data_for_info(got_book)
            new_book = more_crud.add_book_to_db(got_book, current_user, shelf)
            book_dictions.append(new_book)
            print("GOOD BOOK API CALL FOR:", new_book)

    # serialized = MessageToJson()
    session['response'] = book_titles
    session['file'] = file
    session['shelf'] = shelf
    # TODO: CRUD ADD BOOKS FROM RESPONSE TO DATABASE to specific shelf
    print(book_dictions, session)
    # TO DO ADD TO BOOK DATABASE --> MAKE A FUNCTION!?
    return jsonify(book_dictions)
示例#11
0
def update_owned_status(user, book_id, owned_status=None):

    if not owned_status:
        owned_status = crud.get_owned_status(1)
    current_user = crud.get_user_by_username(user)
    shelved_book = crud.update_shelvedbook_owned_st(current_user.user_id, \
                            book_id, owned_status)

    return shelved_book
示例#12
0
def update_reading_status(user, book_id, reading_status=None):

    if not reading_status:
        reading_status = crud.get_reading_status(1)
    current_user = crud.get_user_by_username(user)
    shelved_book = crud.update_shelvedbook_reading_st(current_user.user_id, \
                            book_id, reading_status)

    return shelved_book
示例#13
0
def register_user():
    """Create a new user account."""

    username = request.form.get('username').lower()
    fname = request.form.get('fname')
    lname = request.form.get('lname')
    email = request.form.get('email')
    password = request.form.get('password')
    image = request.files.get('image')
    about = request.form.get('about')

    # Check if user with that email already exists
    user = crud.get_user_by_email(email)
    if user:
        return jsonify({
            'status': 'error',
            'message': 'Account with that email already exists.'
        })

    # Check if user with that username already exists
    user = crud.get_user_by_username(username)
    if user:
        return jsonify({
            'status':
            'error',
            'message':
            'Username already exists. Please pick a different one.'
        })

    # OK to create a new user account
    image_url = None
    if image:
        cloudinary_upload = cloudinary.uploader.upload(image)
        image_url = cloudinary_upload['url'].partition("upload")[2]

    user = crud.create_user(username, fname, lname, email, password, image_url,
                            about)

    session['user_id'] = user.id

    # create an initial welcome message for user from peppa
    crud.create_signup_message(user)

    notification_data = {
        'message': f'You have a new message from peppa.',
        'link': 'Go to messages.',
        'url': '/messages'
    }
    notification = crud.create_notification('new_message', user.id,
                                            json.dumps(notification_data))

    return jsonify({
        'status': 'success',
        'message':
        'Welcome! Account successfully created. Feel free to look around. \nTo check out our most popular user, go to http://meeteatapp.com/peppa',
        'user': user.to_dict('include_email')
    })
示例#14
0
async def auth_user(userAuth: schemas.UserIn, db: Session = Depends(get_db)):
    user_in_db = crud.get_user_by_username(db, username=userAuth.username)
    if user_in_db is None:
        raise HTTPException(status_code=404, detail="El usuario no existe")

    if user_in_db.user_password != userAuth.password:
        raise HTTPException(status_code=403, detail="Error de autenticacion")

    return {"Autenticado": True}
示例#15
0
    def mutate(root, info, email: str, username: str, password: str):
        logger.debug(f"username: {username}, password: {password}")
        ok = True

        if crud.get_user_by_username(db, username) is not None:
            raise GraphQLError("Username already registered")

        user = init_user(username=username, password=password, email=email)
        crud.create_user(db, user)
        token = create_access_token_with_username(user.username)
        return CreateUser(token=token)
示例#16
0
def register():
    """Create user, add to the database."""

    # submit button disabled if any field is left blank
    # cleared form in component after fetch to resolve infinite loop

    data = request.get_json()
    username = data.get('username')
    fname = data.get('fname')
    user_region = data.get('user_region')
    password = data.get('password')
    confirm_password = data.get('confirm_password')

    # check if a user is logged in, if so redirect to /garden
    current_user = session.get('user_id')
    if current_user is not None:
        flash("You're already logged in!")
        return jsonify({'response': 'success'})

    # check if username exists in db, if so redirect to /register
    user = crud.get_user_by_username(username)
    if user:
        flash("Username is already registered, please try another name.")
        return jsonify({'response': 'failed'})

    # if passwords entered don't match, redirect to /register
    if password != confirm_password:
        flash("Passwords do not match, please try again.")
        return jsonify({'response': 'failed'})

    # if password, encrypt
    if password is not None:
        hashed = hash_password(password)

        # create new user in db
        new_user = crud.create_user(username=username,
                                    fname=fname,
                                    password_hash=hashed,
                                    user_region=user_region)

        # create garden in db associated with new user
        new_usergarden = crud.create_user_garden(user_id=new_user.user_id)

        # save user_id, user_region, usergarden_id and fname to session
        session['usergarden_id'] = new_usergarden.usergarden_id
        session['user_id'] = new_user.user_id
        session['user_region'] = new_user.user_region
        session['fname'] = new_user.fname

        flash(f"Welcome, { fname }!")

        # redirect to /garden
        return jsonify({'response': 'success'})
def check_access_token(token: str) -> Optional[User]:
    try:
        payload = decode_access_token(token=token)

        username = payload.get("sub")
        if username is None:
            return None
    except jwt.PyJWTError:
        return None

    user = crud.get_user_by_username(db=db, username=username)
    return user
示例#18
0
def display_bookshelf():

    if session.get('user'):
        print(session['user'])
        current_user = crud.get_user_by_username(session['user'])
        print("\n\n\n CHECK USER", current_user)

        user_books = utility.make_dict_books_a_shelf(session['user'], "all")

        # print("CHECK BOOKS", user_books, "\n\n\n")
        user_shelves = crud.return_all_shelves_by_user(current_user.user_id)

        reading_stats = crud.return_all_types_reading()
        owned_stats = crud.return_all_types_owned()

    else:

        return (jsonify({"status": "please login first"}))

    # print(f"\n\n\n {current_user} \n {user_shelves} \n {reading_stats} \n {owned_stats}")
    print("PRINTING SHELVES", user_shelves)
    serial_shelves = []
    for shelf in list(set(user_shelves)):
        serial_shelves.append({
            'shelf_id': shelf.shelf_id,
            'name': shelf.nickname
        })

    serialized_reading_statuses = []
    for stat in reading_stats:
        serialized_reading_statuses.append({
            'reading_status_id':
            stat.reading_status_id,
            'reading_status':
            stat.reading_status_name
        })

    serialized_owned_statuses = []
    for stat in owned_stats:
        serialized_owned_statuses.append({
            'owned_id': stat.owned_id,
            'owned_status': stat.owned_text
        })

    # print("WHY ARE ALL SHELVES BOOKWORMMArY", serialized_books)
    return jsonify({
        "user": session['user'],
        "books": user_books,
        "shelves": serial_shelves,
        "reading_st_list": serialized_reading_statuses,
        "owned_st_list": serialized_owned_statuses
    })
示例#19
0
def register_user():
    """Create a new user"""

    username = request.form.get('username')
    password = request.form.get('password')

    user = crud.get_user_by_username(username)

    if user:
        flash('Username taken! Please create one.')
        return redirect('/signup')
    else:
        crud.create_user(username, password)
        flash('Account created! Please log in.')
        return redirect('/')
示例#20
0
    def mutate(root, info, token, title):

        query = AnimeSchema.get_query(info)
        try:
            payload = decode_access_token(data=token)
            username: str = payload.get("sub")
            if username is None:
                raise GraphQLError("Invalid credentials")
            token_data = TokenData(username=username)
        except PyJWTError:
            raise GraphQLError("Invalid credentials")
        user = crud.get_user_by_username(db, username=token_data.username)
        if user is None:
            raise GraphQLError("Invalid credentials")
        AnimeSearch = route_optima_search(query, title, str(title))
        return SearchAnime(AnimeSearch=AnimeSearch)
示例#21
0
 def mutate(root, info, title, content, token):
     try:
         payload = decode_access_token(data=token)
         username: str = payload.get("sub")
         if username is None:
             raise GraphQLError("Invalid credentials")
         token_data = TokenData(username=username)
     except PyJWTError:
         raise GraphQLError("Invalid credentials")
     user = crud.get_user_by_username(db, username=token_data.username)
     if user is None:
         raise GraphQLError("Invalid credentials")
     blog = BlogBase(title=title, content=content)
     crud.create_new_blog(db=db, blog=blog)
     ok = True
     return CreateNewBlog(ok=ok)
示例#22
0
def show_logged_in_user_profile():
    """Show details for a logged-in user"""

    if "username" in session:
        username = session["username"]
        user = crud.get_user_by_username(username)
        ratings = crud.get_user_ratings(username)

        return render_template("/user_details.html",
                               user=user,
                               ratings=ratings)

    else:
        flash("You need to be logged in to access that page", 'warning')

        return redirect("/login")
示例#23
0
def show_other_user_profile(username):
    """Show the user profile of other registered users"""

    account = crud.get_user_by_username(username)
    reviews = account.reviews
    collections = account.collections
    profile_picture = account.profile_picture
    user_bio = account.user_bio
    created_on = account.created_on
    user_id = account.user_id
    birthday = account.birthday
    website = account.website

    user_friends = []
    user_friendships = account.added_friends
    for friendship in user_friendships:
        user_friend_id = friendship.friend_id
        friend_account = crud.get_user_by_user_id(user_friend_id)
        user_friends.append(friend_account)

    collection_names = {}
    collections_pods = {}

    for collection in collections:

        collection_names[collection.collection_id] = collection.name

        collection_pods = []

        for pod in collection.collection_podcasts:
            pod_object = crud.get_podcast_by_id(pod.podcast_id)
            collection_pods.append(pod_object)

        collections_pods[collection.name] = collection_pods

    return render_template('other_users.html',
                           user=username,
                           reviews=reviews,
                           profile_picture=profile_picture,
                           birthday=birthday,
                           website=website,
                           user_bio=user_bio,
                           friends=user_friends,
                           created_on=created_on,
                           collections=collections,
                           collections_details=collections_pods,
                           profile_user_id=user_id)
示例#24
0
def login_user():
    username = request.json['username'].lower()
    password = request.json['password']

    user = crud.get_user_by_username(username)
    if not user:
        return jsonify({'status': 'error', 'message': 'User does not exist.'})
    else:
        if user.check_password(password):
            session['user_id'] = user.id
            return jsonify({
                'status': 'success',
                'message': 'Successfully logged in.',
                'user': user.to_dict('include_email')
            })
        else:
            return jsonify({'status': 'error', 'message': 'Invalid password.'})
示例#25
0
    def mutate(root, info, token):

        query = AnimeSchema.get_query(info)
        try:
            payload = decode_access_token(data=token)
            username: str = payload.get("sub")
            if username is None:
                raise GraphQLError("Invalid credentials")
            token_data = TokenData(username=username)
        except PyJWTError:
            raise GraphQLError("Invalid credentials")
        user = crud.get_user_by_username(db, username=token_data.username)
        if user is None:
            raise GraphQLError("Invalid credentials")
        AnimeList = route_optima(query, "allanime")

        return GetAnimeList(AnimeList=AnimeList)
示例#26
0
def register_users():
    """Create a new user."""

    username = request.form.get('username')
    email = request.form.get('email')
    password = request.form.get('password')

    if email in crud.get_all_emails():
        # flash('Email has already taken. Try again')
        return redirect('/account')

    else:
        crud.create_user(username, email, password)
        user = crud.get_user_by_username(username)
        session['user'] = user.username
        # flash('Your account has been created.')
        return redirect(f'/build/{user.username}')
示例#27
0
def login():
    """Log user into account."""
# TODO: bug here
    user = crud.get_user_by_username(request.form['username']) # this one is a little complicated, wanna keep it
    password = request.form['password']

    if user == None:
        flash("We could not find an account with that username, please try again or create an account.")
        return redirect('/')
#why does this flash on homepage and not login page?
    elif password != user.password:
        flash('Incorrect password. Please try again.')
        return redirect('login.html')

    else:
        flash(f'Logged in as {user.user_fname}!')
        login_user(user)
        return render_template('homepage.html')
示例#28
0
async def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)):
    credentials_exception = HTTPException(
        status_code = status.HTTP_401_UNAUTHORIZED,
        detail = "Could not validate credentials",
        headers = {"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = decode_access_token(data=token)
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_data = TokenData(username=username)
    except PyJWTError:
        raise credentials_exception
    user = get_user_by_username(db, username=token_data.username)
    if user is None:
        raise credentials_exception
    return user
示例#29
0
async def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)):
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"}
    )
    try:
        payload = jwt.decode(token, utils.SECRET_KEY,
                             algorithms=[utils.ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_data = schemas.TokenData(username=username)
    except PyJWTError:
        raise credentials_exception
    user = crud.get_user_by_username(db, token_data.username)
    if user is None:
        raise credentials_exception
    return user
示例#30
0
def create_new_user_account():
    """Create a new user account."""

    email = request.form.get('email')
    username = request.form.get('username')
    password = request.form.get('password')

    if crud.get_user_by_email(email):
        flash('An account with that email already exists. Please login!')
    else:
        if crud.get_user_by_username(username):
            flash(
                'That username is taken. Please choose a different username :)'
            )
        else:
            crud.create_user(username, email, password)
            flash('Account successfully created :D. Please login!')

    return redirect('/login')