def authenticate():
    eyes = [1, 10, 2, 3, 4, 5, 6, 7, 9]
    noses = [2, 3, 4, 5, 6, 7, 8, 9]
    mouths = [1, 10, 11, 3, 5, 6, 7, 9]
    # Get POST data
    username = request.json.get('username')
    password = request.json.get('password')
    picture_url = request.json.get('picture_url')
    description = request.json.get('description')
    if picture_url is None:
        picture_url = "https://api.adorable.io/avatars/face/eyes{0}/nose{1}/mouth{2}/{3}".format(
            eyes[randint(0,
                         len(eyes) - 1)], noses[randint(0,
                                                        len(noses) - 1)],
            mouths[randint(0,
                           len(mouths) - 1)], 'FF6600')

    if username is None or password is None or description is None:
        abort(400)  # Missing arguments
    if User.query.filter_by(username=username).first() is not None:
        abort(400)  # User already exists

    # Create a new User object and pass the POST data in the constructor. Hash the password
    user = User(username=username,
                picture_url=picture_url,
                description=description)
    user.hash_password(password)

    # Add the user object to the database
    db.session.add(user)
    db.session.commit()

    # @TODO in the future: {'Location': url_for('get_user', id = user.id, _external = True)}
    return jsonify({'username': user.username})
Exemple #2
0
def signup():
    if request.method == 'POST':
        user = request.form['name']
        email = request.form['email']
        password = request.form['pass']
        confirm = request.form['confirmpass']
        # confirm_code = generate_code()

        # check if user already exists
        if session.query(User).filter(User.email == email).count() > 0:
            flash("User already exists. Please login")
            return redirect(url_for('login'))

        elif password != confirm:
            flash("Passwords don't match")
            return redirect(url_for('signup'))

        newUser = User(name=user, email=email)
        newUser.hash_password(password)

        session.add(newUser)
        session.commit()

        login_user(newUser, force=True)
        newUser.is_authenticated = True

        flash("Welcome " + user + ". You have successfully signed up")

        # msg = MIMEMultipart()
        # msg['From'] = '*****@*****.**'
        # msg['To'] = email
        # msg['Subject'] = 'Email confirmation'
        # body = render_template('email.html', name=user, code=confirm_code)
        # msg.attach(MIMEText(body, 'html'))
        #
        # try:
        #     server.starttls()
        # except:
        #     while True:8
        #         try:
        #             server.connect()
        #             break
        #         except:
        #             pass
        #     server.starttls()
        #
        # server.login('*****@*****.**', 'fake_password')
        # text = msg.as_string()
        # try:
        #     server.sendmail('*****@*****.**', email, text)
        # except:
        #     flash("Invalid email")
        #     return jsonify(success=False, error="email")
        #
        # server.quit()

        return redirect(url_for('view_profile', user_id=newUser.id))
    else:
        return render_template('signup.html')
def sign_up():
    username = request.json.get('username')
    password = request.json.get('password')
    picture_url = request.json.get('picture_url')
    description = request.json.get('description')

    if description is None:
        description = ''

    if picture_url is None:
        picture_url = get_picture_url()

    if username is None:
        return jsonify({
            'result': 'failure',
            'error': '400',
            'message': 'Username field is empty'
        }), 400

    if password is None:
        return jsonify({
            'result': 'failure',
            'error': '400',
            'message': 'Password field is empty'
        })

    if User.query.filter_by(username=username).first() is not None:
        return jsonify({
            'result': 'failure',
            'error': '409',
            'message': 'User already exists'
        }), 409

    user = User(username=username,
                picture_url=picture_url,
                description=description)
    user.hash_password(password)

    db.session.add(user)
    db.session.commit()

    return jsonify({
        'result': 'success',
        'user': {
            'id': user.id,
            'username': username,
            'picture_url': picture_url,
            'description': description,
            'ranking': 1
        }
    }), 201  # created
Exemple #4
0
def seed():
    """Seeds the database with dummy data"""
    print("Seeding the database")

    # ------------------- #
    # --- RANDOM DATA --- #
    # ------------------- #

    random_data = {

        # Descriptions
        'descriptions': [
            'Nullam sit amet ex volutpat, accumsan ex eu, ullamcorper libero. Nunc libero sapien, volutpat at ex a, vulputate viverra sem. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean quis efficitur arcu',
            'Nullam molestie dapibus libero volutpat viverra. Etiam sit amet nulla leo.',
            'Etiam velit tortor, venenatis a leo commodo, feugiat scelerisque erat. Curabitur sed dui ac urna congue vestibulum vitae ut enim. Quisque at tellus finibus orci pretium laoreet.',
            'Quisque vulputate eros nisi, ut fermentum tellus lobortis eget',
            'Etiam vel mi vitae magna congue malesuada.'
        ],

        # Users
        'users': [],

        # Users
        'games':
        ['Tic-Tac-Toe', 'Guess the word', 'Whack-A-Mole', 'Pong', 'Othello'],
        'game_ids': [],
    }

    # ------------------ #
    # --- SEED USERS --- #
    # ------------------ #

    # Loop 25 times
    for i in range(125, 150):

        # Generate random description
        random_description = random_data['descriptions'][random.randint(
            0,
            len(random_data['descriptions']) - 1)]

        # Create a random User
        user = User(username='******'.format(i),
                    picture_url='via.placeholder.com/100x100',
                    description=random_description)
        # Use the hash_password() method on the User object (Model)
        user.hash_password('password{0}'.format(i))

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

        # Add the user to the users list
        random_data['users'].append(user)

    # ------------------ #
    # --- SEED GAMES --- #
    # ------------------ #

    # Loop random_data['games'] size times
    for i in range(0, len(random_data['games'])):

        # Generate random description
        random_description = random_data['descriptions'][random.randint(
            0,
            len(random_data['descriptions']) - 1)]

        # Create a random Game
        game = Game(name=random_data['games'][i],
                    description=random_description)

        # Add the game to the database
        db.session.add(game)
        db.session.commit()

        # Add the user to the users list
        random_data['game_ids'].append(game.id)

    # ------------------------ #
    # --- SEED FRIENDSHIPS --- #
    # ------------------------ #

    # Loop 50 times
    for i in range(0, 50):

        # The same user can never befriend itself so if id1 and id2 are the same, keep looping
        same_id = True
        while same_id:
            # Generate random user id's
            random_user_id1 = random_data['users'][random.randint(
                0,
                len(random_data['users']) - 1)].id
            random_user_id2 = random_data['users'][random.randint(
                0,
                len(random_data['users']) - 1)].id

            # If the id's are different OR if the random_user_id1 is empty
            if random_user_id1 != random_user_id2 or random_user_id1 == None:
                same_id = False

        # Create a random Friendship
        friendship = Friendship(user_id_1=random_user_id1,
                                user_id_2=random_user_id2)

        # Add the friendship to the database
        db.session.add(friendship)
        db.session.commit()

    # ------------------------- #
    # --- SEED ACHIEVEMENTS --- #
    # ------------------------- #

    for i in range(0, 50):

        # Generate a random game id & description
        random_description = random_data['descriptions'][random.randint(
            0,
            len(random_data['descriptions']) - 1)]
        random_game_id = random_data['game_ids'][random.randint(
            0,
            len(random_data['game_ids']) - 1)]

        # Create a random Achievement
        achievement = Achievement(name='Achievement {0}'.format(i),
                                  description=random_description,
                                  game_id=random_game_id)

        # Add the friendship to the database
        db.session.add(achievement)
        db.session.commit()

    print("Done seeding the database")