Exemplo n.º 1
0
def search():
    """ This function is to search other available user
        according to the user's text input
        if user doesn't input anything, it will return all available user
    input: user search input
    return: list of all available user
    """
    if not g.user:
        flash("You are not signed in")
        return redirect(url_for('index'))
    matching = []
    if request.method == 'POST':
        for key in r_server.hkeys('users'):
            if key:
                currentUser = r_server.hgetall('user:%s' %
                                               r_server.hget('users', key))
            if currentUser:
                if request.form['inputSearch'].lower() in currentUser.get(
                        'firstName'
                ).lower() or request.form[
                    'inputSearch'].lower() in currentUser.get(
                    'lastName'
                ).lower() or request.form[
                    'inputSearch'].lower() in currentUser.get(
                    'email'
                ).lower():
                    if currentUser.get('email') not in g.user.get('email'):
                        matching.append(currentUser)
        return render_template('search.html', matching=matching)
    else:
        error = "Unable to search"
        flash(error)
    return redirect(url_for('index', error='Search Error'))
Exemplo n.º 2
0
def deletePost():
    """ This function can be used to delete user's post,
        but user must have be the one who posted it
    input: post_ID
    return: success: delete post from the database
            failure: user doesn't have authority to delete the post
    """
    if not g.user:
        flash('You are not signed in')
        return redirect(url_for('index', error='Deletion Error'))
    error = None
    if request.method == 'POST':
        if 'inputPostID' not in request.form:
            error = "ID is unavailable"
            flash(error)
        elif request.form['inputPostID'] in r_server.lrange(
                'posts:%s' % escape(session['user_id']), 0, 1000):
            postID = request.form["inputPostID"]
            if r_server.hget('post:%s' % postID, 'fileType'):
                k = Key(bucket)
                k.key = S3_KEY_PREFIX+'post/'+postID
                k.key += '.'+r_server.hget('post:%s' % postID, 'fileType')
                bucket.delete_key(k)
            if r_server.lrem(
                    'posts:%s' % escape(session['user_id']),
                    int(postID), 0
            ) and r_server.delete(
                'post:%s' % postID
            ) and r_server.zrem(
                'timeline:%s' % escape(session['user_id']),
                postID
            ) and r_server.zrem('timeline:', postID):
                for follower in r_server.lrange(
                        'followed:%s' % escape(session['user_id']), 0, 1000):
                    r_server.zrem("timeline:%s" % follower, postID)
                flash('deletion successfull')
                return redirect(url_for('index'))
            else:
                flash('deletion failed')
                return redirect(url_for('index', error='delete error'))
        else:
            error = "you are not allowed to delete the post"
            flash(error)
    else:
        error = "you are not allowed to delete the post"
        flash(error)
    return redirect(url_for('index', error='Deletion Error'))
Exemplo n.º 3
0
def loginplus():
    """ This function allow user to log in to Tera without registering
        this function will take user's data from the authenticated google
        plus user
    return: already registered email: login to the web application
            unregistered email: save the user's data into Redis and login
    """
    if 'credentials' not in session:
        flash('credential not in session')
        return redirect(url_for('oauth2callback'))
    credentials = client.OAuth2Credentials.from_json(session['credentials'])
    if credentials.access_token_expired:
        flash('credential expired')
        return redirect(url_for('oauth2callback'))
    else:
        flash('service built')
        http_auth = credentials.authorize(httplib2.Http())
        service = discovery.build('plus', 'v1', http_auth)
    try:
        person = service.people().get(userId='me').execute()
        user_id = r_server.hget('users', person['emails'][0]['value'].lower())
        if user_id:
            session['user_id'] = user_id
            flash('You sign in through google plus')
            return redirect(url_for('index'))
        else:
            r_server.incr('next_userID')
            user_id = r_server.get('next_userID')
            if r_server.hmset(
                    "user:%s" % user_id,
                    {
                        "firstName": person['name']['givenName'].capitalize(),
                        "lastName": person['name']['familyName'].capitalize(),
                        "email": person['emails'][0]['value'].lower(),
                        "userID": user_id
                    }
            ) and r_server.hset(
                "users", person['emails'][0]['value'].lower(),
                user_id
            ):
                session['user_id'] = user_id
                flash('You are registered using google plus')
                return redirect(url_for('index'))
            else:
                error = "sign up failure"
                flash(error)
                r_server.decr('next_userID')
    except client.AccessTokenRefreshError:
        error = 'The credentials have been revoked or expired, please re-run'
        error += 'the application to re-authorize.'
        flash(error)
    return redirect(url_for('index', error='Google Plus Login'))
Exemplo n.º 4
0
def signin():
    """ This sign function allow user to use registered account to sign in
    input: post of user's email and password
    return: success: back to index function to render timeline.html
            failure: go back to sign in page in index.html and show
                     errors
    """
    if g.user:
        flash('you are already signed in')
        return redirect(url_for('index'))
    error = None
    user_id = None
    if request.method == 'POST':
        if not request.form['logEmail'] or '@' not in request.form['logEmail']:
            error = 'invalid email address'
            flash(error)
        else:
            user_id = r_server.hget('users', request.form['logEmail'].lower())
        if not request.form['logPassword']:
            error = 'invalid password'
            flash(error)
        if not user_id:
            error = 'invalid email'
            flash(error)
        else:
            if not pbkdf2_sha256.verify(
                    request.form['logPassword'], r_server.hget(
                        'user:%s' % user_id,
                        "password"
                    )
            ):
                error = 'invalid password'
                flash(error)
            if not error:
                session['user_id'] = user_id
                flash('successfully signed in')
                return redirect(url_for("index"))
    return redirect(url_for('index', error='Sign in'))
Exemplo n.º 5
0
def signup():
    """ This function will accept post form data about the user and
        increase next_userID for user if he is successfully registered
    input: user's first name, last name, email, and password
    return: success: user is registered, signed in, and redirected to index
                     to render timeline.html
            failure: user go back to the index.html with all of the error
                     shown to enable user to easily fix the problem

    """
    if g.user:
        return redirect(url_for('index'))
    error = None
    if request.method == 'POST':
        if not request.form['inputFirstName']:
            error = 'You have to enter your first name'
            flash(error)
        if not request.form['inputLastName']:
            error = 'You have to enter your last name'
            flash(error)
        if not request.form['suEmail'] or '@' not in request.form['suEmail']:
            error = 'You have to enter a valid email address'
            flash(error)
        if not request.form['suPassword']:
            error = 'You have to enter a password'
            flash(error)
        elif len(
            request.form['suPassword']
        ) < 8 or len(
            request.form['suPassword']
        ) > 36:
            error = 'Your password must be between 8-36 character'
            flash(error)
        if r_server.hget('users', request.form['suEmail']) is not None:
            error = 'The email already exist'
            flash(error)
        if not error:
            r_server.incr('next_userID')
            user_id = r_server.get('next_userID')
            password = pbkdf2_sha256.encrypt(request.form['suPassword'],
                                             rounds=200000, salt_size=16)
            if r_server.hmset(
                    "user:%s" % user_id,
                    {
                        "firstName":
                        request.form['inputFirstName'].encode('utf8'),
                        "lastName":
                        request.form['inputLastName'].encode('utf8'),
                        "email": request.form['suEmail'].lower(),
                        "password": password, "userID": user_id
                    }
            ) and r_server.hset(
                "users", request.form['suEmail'].lower(),
                user_id
            ):
                session['user_id'] = user_id
                flash('successfully signed up')
                return redirect(url_for('index'))
            else:
                error = "sign up failure"
                flash(error)
                r_server.decr('next_userID')
    else:
        error = "please fill the sign up form correctly first"
        flash(error)
    return redirect(url_for('index', error='Sign up'))