예제 #1
0
def test_register(client, auth):
    """ Test that registration page opens up """
    resp = client.get("/register")
    assert resp.status_code == 200
    response = auth.register()
    assert response.status_code == 200
    user = User.objects(username="******").first()
    assert user is not None
예제 #2
0
def account():
    username_form = UpdateUsernameForm()
    password_form = UpdatePasswordForm()
    profile_pic_form = UpdateProfilePicForm()

    if password_form.validate_on_submit():
        hashed = bcrypt.generate_password_hash(
            password_form.new_password.data).decode("utf-8")

        msg = Message('Password Change',
                      sender='*****@*****.**',
                      recipients=[str(temp.email)])
        msg.body = "Your password has been updated! Please reply to this e-mail if you did not request this change."
        mail.send(msg)

        current_user.modify(password=hashed)
        current_user.save()

        return redirect(url_for('users.account'))

    if username_form.validate_on_submit():
        temp = User.objects(username=current_user.username).first()
        current_user.username = username_form.username.data

        msg = Message('Username Change',
                      sender='*****@*****.**',
                      recipients=[str(temp.email)])
        msg.body = "Your username has been updated!\nYour new username is: " + str(
            username_form.username.data)
        mail.send(msg)

        current_user.modify(username=username_form.username.data)
        current_user.save()

        return redirect(url_for('users.account'))

    if profile_pic_form.validate_on_submit():
        img = profile_pic_form.propic.data
        filename = secure_filename(img.filename)

        if current_user.profile_pic.get() is None:
            current_user.profile_pic.put(img.stream, content_type='images/png')
        else:
            current_user.profile_pic.replace(img.stream,
                                             content_type='images/png')
        current_user.save()

        return redirect(url_for('users.account'))

    image = images(current_user.username)

    return render_template("account.html",
                           title="Account",
                           username_form=username_form,
                           password_form=password_form,
                           profile_pic_form=profile_pic_form,
                           image=image)
예제 #3
0
def user_detail(username):
    mongo_lock.acquire()
    user = User.objects(username=username).first()
    comments = Comment.objects(commenter=user)
    mongo_lock.release()

    if (user == None):
        return render_template('user_detail.html',
                               error_msg=f'User {username} not found.')

    mongo_lock.acquire()
    game_subscriptions = User.objects(
        username=user.username).first().game_subscriptions
    mongo_lock.release()

    return render_template('user_detail.html',
                           username=username,
                           comments=comments,
                           client=sport_client,
                           game_subscriptions=game_subscriptions)
예제 #4
0
def user_detail(username):
    user = User.objects(username=username).first()
    reviews = Review.objects(commenter=user)
    pim = CatImage.objects(commenter=user)
    image = images(username)

    proposed = {}
    for p in pim:
        bytes_im = io.BytesIO(p['im'].read())
        img = base64.b64encode(bytes_im.getvalue()).decode()
        proposed[p['cat_name']] = img
    return render_template('user_detail.html',
                           username=username,
                           reviews=reviews,
                           image=image,
                           pim=proposed)
예제 #5
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('features.index'))

    form = LoginForm()
    if form.validate_on_submit():
        user = User.objects(username=form.username.data).first()
        if user is not None and bcrypt.check_password_hash(
                user.password, form.password.data):
            login_user(user)
            return redirect(url_for('users.account'))
        else:
            flash('Login failed. Check your username and/or password')
            return redirect(url_for('users.login'))

    return render_template('login.html', title='Login', form=form)
예제 #6
0
def account():
    username_form = UpdateUsernameForm()

    if username_form.validate_on_submit():
        # current_user.username = username_form.username.data
        mongo_lock.acquire()
        current_user.modify(username=username_form.username.data)
        current_user.save()
        mongo_lock.release()
        return redirect(url_for('users.account'))

    mongo_lock.acquire()
    user = User.objects(username=current_user.username).first()
    mongo_lock.release()

    return render_template("account.html",
                           title="Account",
                           username_form=username_form,
                           user=user)
예제 #7
0
def test_change_username(client, auth):
    '''
    Test that the account page loads successfully and that you can 
    successfully change the username of the logged-in user.
    Test that the new username shows up on the account page
    Test that the new username change is reflected in the database
    '''
    resp = client.get("/login")
    assert resp.status_code == 200
    old_username, new_username = "******", "I CHANGED"
    # REGISTER A NEW USER
    register_resp = auth.register(
        username=old_username, email="*****@*****.**", passwrd="password", confirm="password"
    )
    # LOG IN BRAND NEW USER AND CHECK THAT LOGIN IS SUCCESSFUL.
    login_resp = auth.login(username=old_username, password="******")
    assert login_resp.status_code == 200
    resp = client.get("/account")
    assert resp.status_code == 200
    # CHECK THAT SESSION ID IS SET TO ORIGINAL USERNAME
    with client:
        client.get("/")
        assert session["_user_id"] == old_username
    # FILL IN FORM FOR USERNAME CHANGE
    change_name = SimpleNamespace(username=new_username, submit="Update Username")
    form = UpdateUsernameForm(formdata=None, obj=change_name)
    response = client.post("/account", data=form.data, follow_redirects=True)
    # FILLING OUT FOR REIDIRECTS BACK TO LOG IN PAGE, SO LOGIN W/ NEW CREDENTIALS.
    login_resp = auth.login(username=new_username, password="******")
    # CHECK THAT NEW LOGIN WORKED
    assert login_resp.status_code == 200
    # CHECK THAT SESSION ID CHANGES TO NEW USERNAME AFTER LOGING IN.
    with client:
        client.get("/")
        assert session["_user_id"] == new_username
    # CHECK THAT NEW USERNAME APPEARS IN ACCOUNT PAGE HTML.
    resp = client.get("/account")
    assert resp.status_code == 200
    assert str.encode(new_username) in resp.data
    # FINALLY, CHECK FOR NEW USERNAME IN DB.
    new_username_check = User.objects(username=new_username).first().username
    assert new_username == new_username_check
예제 #8
0
def send_scheduled_messages():
    mongo_lock.acquire()
    for user in User.objects():
        for subscription in user.game_subscriptions:
            game = sport_client.getEventByID(subscription)

            if game.dateEventLocal is not None:
                game_date = utils.extract_date_tuple(game.dateEventLocal)
                curr_date = utils.current_date_tuple()

            if game.dateEventLocal is None or game_date <= curr_date:
                send_message(game.getEventDescription(True), user.phone_number)
                new_subscriptions = user.game_subscriptions
                new_subscriptions.remove(int(subscription))
                user.modify(game_subscriptions=new_subscriptions)

    mongo_lock.release()

    # reschedule the timer
    Timer(twilio_timer_interval, send_scheduled_messages).start()
예제 #9
0
def test_change_username(client, auth):
    auth.register()
    auth.login()

    resp = client.get("/account")
    assert resp.status_code == 200

    new_username = SimpleNamespace(username="******",
                                   submit="Update Username")
    form = UpdateUsernameForm(formdata=None, obj=new_username)
    response = client.post("/account", data=form.data, follow_redirects=True)

    auth.login(username="******")

    response = client.get("/account")

    assert b"peepeehands" in response.data

    users = User.objects(username="******")
    assert len(users) == 1
예제 #10
0
def account():
    username_form = UpdateUsernameForm()
    profile_pic_form = UpdateProfilePicForm()

    if username_form.validate_on_submit():
        # current_user.username = username_form.username.data

        temp = User.objects(username=current_user.username).first()

        msg = Message('Username Change',
                      sender='*****@*****.**',
                      recipients=[str(temp.email)])
        msg.body = "Your username has been updated!\nYour new username is: " + str(
            username_form.username.data)
        mail.send(msg)

        current_user.modify(username=username_form.username.data)
        current_user.save()

        return redirect(url_for('account'))

    if profile_pic_form.validate_on_submit():
        img = profile_pic_form.propic.data
        filename = secure_filename(img.filename)

        if current_user.profile_pic.get() is None:
            current_user.profile_pic.put(img.stream, content_type='images/png')
        else:
            current_user.profile_pic.replace(img.stream,
                                             content_type='images/png')
        current_user.save()

        return redirect(url_for('account'))

    image = images(current_user.username)

    return render_template("account.html",
                           title="Account",
                           username_form=username_form,
                           profile_pic_form=profile_pic_form,
                           image=image)
예제 #11
0
def qr_code():
    if 'new_username' not in session:
        return redirect(url_for('users.register'))

    user = User.objects(username=session['new_username']).first()
    session.pop('new_username')

    uri = pyotp.totp.TOTP(user.otp_secret).provisioning_uri(
        name=user.username, issuer_name='CMSC388J-2FA')
    img = qrcode.make(uri, image_factory=qrcode.image.svg.SvgPathImage)
    stream = BytesIO()
    img.save(stream)

    headers = {
        'Content-Type': 'image/svg+xml',
        'Cache-Control': 'no-cache, no-store, must-revalidate',
        'Pragma': 'no-cache',
        'Expires':
        '0'  # Expire immediately, so browser has to reverify everytime
    }

    return stream.getvalue(), headers
예제 #12
0
 def validate_username(self, username):
     if username.data != current_user.username:
         user = User.objects(username = username.data).first()
         if user is not None:
             raise ValidationError("This username is already taken")
예제 #13
0
def images(username):
    user = User.objects(username=username).first()
    bytes_im = io.BytesIO(user.profile_pic.read())
    image = base64.b64encode(bytes_im.getvalue()).decode()
    return image
예제 #14
0
def game_detail(game_id):
    result = sport_client.getEventByID(game_id)

    if type(result) == dict:
        return render_template(
            'game_detail.html',
            error_msg=f'{result["Error"]}. Game ID {game_id}')

    subscription_form = NotificationSubscriptionForm()
    unsubscription_form = NotificationUnsubscriptionForm()
    comment_form = GameCommentForm()

    if comment_form.validate_on_submit():
        comment = Comment(
            commenter=load_user(current_user.username),
            content=comment_form.text.data,
            date=current_time(),
            game_id=game_id,
        )

        mongo_lock.acquire()
        comment.save()
        mongo_lock.release()

        return redirect(request.path)

    subscribed = False
    mongo_lock.acquire()
    if current_user.is_authenticated and User.objects(
            username=current_user.username).first().game_subscriptions.count(
                int(game_id)) is not 0:
        subscribed = True
    mongo_lock.release()

    if subscribed and unsubscription_form.validate_on_submit():
        mongo_lock.acquire()
        user = User.objects(username=current_user.username).first()
        new_subscriptions = user.game_subscriptions
        new_subscriptions.remove(int(game_id))
        current_user.modify(game_subscriptions=new_subscriptions)
        mongo_lock.release()
        return redirect(request.path)

    if not subscribed and subscription_form.validate_on_submit():
        mongo_lock.acquire()
        user = User.objects(username=current_user.username).first()
        current_user.modify(game_subscriptions=user.game_subscriptions +
                            [game_id])
        mongo_lock.release()
        return redirect(request.path)

    mongo_lock.acquire()
    comments_m = Comment.objects(game_id=game_id)
    mongo_lock.release()

    comments = []
    for r in comments_m:
        comments.append({
            'date': r.date,
            'username': r.commenter.username,
            'content': r.content,
        })

    return render_template('game_detail.html',
                           comment_form=comment_form,
                           game=result,
                           comments=comments,
                           subscription_form=subscription_form,
                           unsubscription_form=unsubscription_form,
                           subscribed=subscribed)
예제 #15
0
login_manager = LoginManager(app)
login_manager.login_view = 'users.login'
bcrypt = Bcrypt(app)

# Dummy User Data
from flask_app.models import User, Comment, load_user

mongo_lock.acquire()

# Chiefs Fan
hashed = bcrypt.generate_password_hash("password").decode("utf-8")
user = User(username='******',
            email="*****@*****.**",
            phone_number='+14109919959',
            password=hashed)
userTest = User.objects(username=user.username).first()
if userTest is None:
    user.save()

    comment = Comment(
        commenter=load_user(user.username),
        content='Great Game!!!!!!!!!',
        date='2020-03-09',
        game_id='673964',
    )

    comment.save()

    comment = Comment(
        commenter=load_user(user.username),
        content='Super bowl is next 49ers going down',
예제 #16
0
def cat_detail(cat_name):
    client = CatClient()
    attributes_to_keep = [
        'affection_level', 'child_friendly', 'dog_friendly', 'energy_level',
        'grooming', 'hypoalergenic'
    ]

    image_result, breed_result = client.retrieve_cat_by_id(cat_name)
    ratings = dict()
    for key in breed_result[0].keys():
        value = str(breed_result[0][key])
        if value.isdigit() and key in attributes_to_keep:
            new_key = key.replace('_', ' ').capitalize()
            ratings[new_key] = (range(int(value)), range(5 - int(value)))

    #if type(image_result) == dict:
    #    return render_template('movie_detail.html', error_msg=result['Error'])

    if len(image_result) == 0 or len(breed_result) == 0:
        return render_template('cat_detail.html', error_msg="error")

    picform = ProposePicForm()
    if picform.validate_on_submit():
        temp = User.objects(username=current_user.username).first()
        msg = Message('Upload Request',
                      sender='*****@*****.**',
                      recipients=[str(temp.email)])
        msg.body = "Thanks for requesting to upload an image to breed:" + str(
            cat_name) + "!\nYour image is attached to this email"
        msg.attach(picform.new_pic.data.filename, 'images/png',
                   picform.new_pic.data.read())
        mail.send(msg)

        msg = Message('Upload Request',
                      sender='*****@*****.**',
                      recipients=['*****@*****.**'])
        msg.body = "Someone is requesting to upload image to breed: " + str(
            cat_name)
        msg.attach(picform.new_pic.data.filename, 'images/png',
                   picform.new_pic.data.read())
        mail.send(msg)

        img = picform.new_pic.data
        filename = secure_filename(img.filename)

        pim = CatImage(
            commenter=load_user(current_user.username),
            date=current_time(),
            im=None,
            cat_name=cat_name,
        )
        pim.save()
        pim.im.put(img.stream, content_type='images/png')
        pim.save()

        return redirect(url_for('features.cat_detail', cat_name=cat_name))

    form = CatReviewForm()
    if form.validate_on_submit():
        review = Review(
            commenter=load_user(current_user.username),
            content=form.text.data,
            date=current_time(),
            cat_name=cat_name,
        )

        review.save()
        return redirect(request.path)

    reviews_m = Review.objects(cat_name=cat_name)
    reviews = []
    for r in reviews_m:
        reviews.append({
            'date': r.date,
            'username': r.commenter.username,
            'content': r.content,
            'image': images(r.commenter.username)
        })

    return render_template('cat_detail.html',
                           form=form,
                           image=image_result[0],
                           cat=breed_result[0],
                           ratings=ratings,
                           reviews=reviews,
                           picform=picform)
예제 #17
0
 def validate_username(self, username):
     user = User.objects(username = username.data).first()
     if user is not None:
         raise ValidationError("Username has already been taken")
예제 #18
0
 def validate_email(self, email):
     user = User.objects(email = email.data).first()
     if user is not None:
         raise ValidationError("Email is already taken")