Example #1
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'))
Example #2
0
def share():
    """"This function will create new post in the user timeline and
        user's follower timeline if successfull,
        user can also attach the picture inside the post
    input: user's post content and image file
    return: success: add new post to user and user's follower timeline
            failure: return to timeline page and show error
    """
    if not g.user:
        error = 'You are not signed in'
        flash(error)
        return redirect(url_for('index', error='Share Error'))
    error = None
    filen = None
    if request.method == 'POST':
        if 'inputPost' not in request.form:
            error = 'Please write your thoughts first'
            flash(error)
        elif len(request.form['inputPost']) > 300:
            error = 'Your thought is too long'
            flash(error)
        try:
            if 'uploadImg' in request.files:
                filen = request.files['uploadImg']
                if filen and not allowed_file(filen.filename):
                    error = 'Please upload correct file'
                    flash(error)
        except IOError:
            error = 'File cannot be found'
            flash(error)
        if not error:
            r_server.incr('next_postID')
            postID = r_server.get('next_postID')
            if r_server.hmset(
                    "post:%s" % postID,
                    {
                        'content': request.form['inputPost'].encode('utf8'),
                        'userID': session['user_id'],
                        'datetime': datetime.now(timezone('UTC')).strftime(
                            "%Y-%m-%dT%H:%M:%S")
                    }
            ) and r_server.lpush(
                'posts:%s' % escape(session['user_id']),
                postID
            ) and r_server.zadd(
                'timeline:%s' % escape(
                    session['user_id']
                ),
                postID, postID
            ) and r_server.zadd(
                'timeline:', postID, postID
            ):
                for follower in r_server.lrange(
                    'followed:%s' % escape(
                        session['user_id']), 0, 1000):
                    r_server.zadd(
                        "timeline:%s" % follower, postID, postID
                    )
                try:
                    if filen:
                        fileType = filen.filename.rsplit('.', 1)[1]
                        k = Key(bucket)
                        k.key = S3_KEY_PREFIX+'post/'+postID
                        k.key += '.'+fileType
                        k.set_contents_from_file(filen)
                        k.make_public()
                        r_server.hset("post:%s" % postID,
                                      "imageURL",
                                      k.generate_url(0).split('?', 1)[0])
                        r_server.hset("post:%s" % postID,
                                      "fileType",
                                      fileType)
                except IOError:
                    error = 'File cannot be found'
                    flash(error)
                    r_server.decr('next_postID')
                    return redirect(url_for('index',
                                            error='Upload File Error'))
            else:
                r_server.decr('next_postID')
            return redirect(url_for('index'))
        else:
            error = "Your thought failed to be posted"
            flash(error)
    else:
        error = "your thought is abstract"
        flash(error)
    return redirect(url_for('index', error='Share Error'))
Example #3
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'))