Esempio n. 1
0
    def save_board(board_slug):
        board = Board.query.filter_by(slug=board_slug).first()
        if not board:
            abort(404)

        form = EditBoardForm()
        if form.validate_on_submit():
            board.title = form.title.data
            board.slug = form.slug.data
            db.session.commit()
            return json_success({
                'slug': board.slug,
                'title': board.title,
            })

        error_data = {
            'errors': form.errors,
            'revert': {
                'slug': board.slug,
                'title': board.title
            }
        }

        return json_error_message('Failed to save board',
                                  error_data=error_data)
Esempio n. 2
0
def disconnect():
    """Revoke current user's token and reset their session.

    **Route:** ``/admin/disconnect``

    **Methods:** ``GET, POST``
    """
    # Only disconnect a connected user.
    credentials = AccessTokenCredentials(session.get('credentials'),
                                         request.headers.get('User-Agent'))
    if credentials is None:
        return json_error_message('Current user not connected.', 401)

    # Execute HTTP GET request to revoke current token.
    access_token = credentials.access_token
    url = ('https://accounts.google.com/o/oauth2/revoke?token={}'.format(
        str(access_token)))
    h = httplib2.Http()
    result = h.request(url, 'GET')[0]

    session.pop('gplus_id', None)
    g.user = None

    if result['status'] == '200':
        # Reset the user's session.
        del session['credentials']

    else:
        # For whatever reason, the given token was invalid.
        app.logger.error('Failed to revoke token for given user.')

    # use code=303 to avoid POSTing to the next page.
    return redirect(url_for('.login'), code=303)
Esempio n. 3
0
def disconnect():
    """Revoke current user's token and reset their session.

    **Route:** ``/admin/disconnect``

    **Methods:** ``GET, POST``
    """
    # Only disconnect a connected user.
    credentials = AccessTokenCredentials(
        session.get('credentials'), request.headers.get('User-Agent'))
    if credentials is None:
        return json_error_message('Current user not connected.', 401)

    # Execute HTTP GET request to revoke current token.
    access_token = credentials.access_token
    url = ('https://accounts.google.com/o/oauth2/revoke?token={}'
           .format(str(access_token)))
    h = httplib2.Http()
    result = h.request(url, 'GET')[0]

    session.pop('gplus_id', None)
    g.user = None

    if result['status'] == '200':
        # Reset the user's session.
        del session['credentials']

    else:
        # For whatever reason, the given token was invalid.
        app.logger.error('Failed to revoke token for given user.')

    # use code=303 to avoid POSTing to the next page.
    return redirect(url_for('.login'), code=303)
Esempio n. 4
0
    def save_board(board_slug):
        board = Board.query.filter_by(slug=board_slug).first()
        if not board:
            abort(404)

        form = EditBoardForm()
        if form.validate_on_submit():
            board.title = form.title.data
            board.slug = form.slug.data
            db.session.commit()
            return json_success({
                'slug': board.slug,
                'title': board.title,
            })

        error_data = {
            'errors': form.errors,
            'revert': {
                'slug': board.slug,
                'title': board.title
            }
        }

        return json_error_message('Failed to save board',
                                  error_data=error_data)
Esempio n. 5
0
    def delete_color():
        form = DeleteColorForm()
        if form.validate_on_submit():
            color = Color.query.filter_by(id=form.id.data).first()
            if not color:
                abort(404)
            db.session.delete(color)
            db.session.commit()
            return json_success({'deleted': color.id})

        return json_error_message('Failed to delete color',
                                  error_data=form.errors)
Esempio n. 6
0
    def delete_image():
        form = DeleteImageForm()
        if form.validate_on_submit():
            image = Image.query.filter_by(id=form.id.data).first()
            if not image:
                abort(404)
            db.session.delete(image)
            db.session.commit()
            return json_success({'deleted': image.id})

        return json_error_message('Failed to delete image',
                                  error_data=form.errors)
Esempio n. 7
0
    def add_text(board_slug):
        print 'add_text: ', board_slug
        board = Board.query.filter_by(slug=board_slug).first()
        if not board:
            abort(404)

        form = TextForm()
        if form.validate_on_submit():
            response_data = process_text(board, form.text.data)
            db.session.commit()
            return json_success(response_data)

        return json_error_message('Failed to create color',
                                  error_data=form.errors)
Esempio n. 8
0
    def add_text(board_slug):
        print 'add_text: ', board_slug
        board = Board.query.filter_by(slug=board_slug).first()
        if not board:
            abort(404)

        form = TextForm()
        if form.validate_on_submit():
            response_data = process_text(board, form.text.data)
            db.session.commit()
            return json_success(response_data)

        return json_error_message('Failed to create color',
                                  error_data=form.errors)
Esempio n. 9
0
    def delete_color():
        form = DeleteColorForm()
        if form.validate_on_submit():
            color = Color.query.filter_by(id=form.id.data).first()
            if not color:
                abort(404)
            db.session.delete(color)
            db.session.commit()
            return json_success({
                'deleted': color.id
            })

        return json_error_message('Failed to delete color',
                                  error_data=form.errors)
Esempio n. 10
0
    def delete_image():
        form = DeleteImageForm()
        if form.validate_on_submit():
            image = Image.query.filter_by(id=form.id.data).first()
            if not image:
                abort(404)
            db.session.delete(image)
            db.session.commit()
            return json_success({
                'deleted': image.id
            })

        return json_error_message('Failed to delete image',
                                  error_data=form.errors)
Esempio n. 11
0
    def add_image(board_slug):
        print 'add_image: ', board_slug
        board = Board.query.filter_by(slug=board_slug).first()
        if not board:
            abort(404)

        form = ImageForm()
        if form.validate_on_submit():
            image = Image(filename=form.filename.data)
            db.session.add(image)
            board.images.append(image)
            db.session.commit()
            return json_success(
                {'image': {
                    'filename': image.filename,
                    'id': image.id
                }})

        return json_error_message('Failed to create image',
                                  error_data=form.errors)
Esempio n. 12
0
    def add_image(board_slug):
        print 'add_image: ', board_slug
        board = Board.query.filter_by(slug=board_slug).first()
        if not board:
            abort(404)

        form = ImageForm()
        if form.validate_on_submit():
            image = Image(filename=form.filename.data)
            db.session.add(image)
            board.images.append(image)
            db.session.commit()
            return json_success({
                'image': {
                    'filename': image.filename,
                    'id': image.id
                }
            })

        return json_error_message('Failed to create image',
                                  error_data=form.errors)
Esempio n. 13
0
def store_token():
    """Do the oauth flow for Google plus sign in, storing the access token
    in the session, and redircting to create an account if appropriate.

    Because this method will be called from a ``$.ajax()`` request in
    JavaScript, we can't return ``redirect()``, so instead this method returns
    the URL that the user should be redirected to, and the redirect happens in
    html:

    .. code:: javascript

        success: function(response) {
            window.location.href = response.data.redirect_url;
        }

    **Route:** ``/admin/store-token``

    **Methods:** ``POST``
    """
    if request.args.get('state', '') != session.get('state'):
        return json_error_message('Invalid state parameter.', 401)

    del session['state']
    code = request.data

    try:
        # Upgrade the authorization code into a credentials object
        oauth_flow = flow_from_clientsecrets(config['CLIENT_SECRETS_PATH'],
                                             scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        return json_error_message('Failed to upgrade the authorization code.',
                                  401)

    gplus_id = credentials.id_token['sub']

    # Store the access token in the session for later use.
    session['credentials'] = credentials.access_token
    session['gplus_id'] = gplus_id

    if User.objects(gplus_id=gplus_id).count() == 0:
        # A new user model must be made

        # Get the user's name and email to populate the form
        http = httplib2.Http()
        http = credentials.authorize(http)
        people_document = gplus_service.people().get(userId='me').execute(
            http=http)

        # The user must be whitelisted in order to create an account.
        email = people_document['emails'][0]['value']
        if Whitelist.objects(email=email).count() != 1:
            return json_error_message('User has not been whitelisted.', 401, {
                'whitelisted': False,
                'email': email
            })

        return json_success({
            'redirect_url':
            url_for('.create_profile',
                    next=request.args.get('next'),
                    name=people_document['displayName'],
                    email=email,
                    image_url=people_document['image']['url'])
        })

    user = User.objects().get(gplus_id=gplus_id)
    user.register_login()
    user.save()

    # The user already exists.  Redirect to the next url or
    # the root of the application ('/')
    if request.args.get('next'):
        return json_success({'redirect_url': request.args.get('next')})
    return json_success({'redirect_url': request.url_root})
Esempio n. 14
0
def store_token():
    """Do the oauth flow for Google plus sign in, storing the access token
    in the session, and redircting to create an account if appropriate.

    Because this method will be called from a ``$.ajax()`` request in
    JavaScript, we can't return ``redirect()``, so instead this method returns
    the URL that the user should be redirected to, and the redirect happens in
    html:

    .. code:: javascript

        success: function(response) {
            window.location.href = response.data.redirect_url;
        }

    **Route:** ``/admin/store-token``

    **Methods:** ``POST``
    """
    if request.args.get('state', '') != session.get('state'):
        return json_error_message('Invalid state parameter.', 401)

    del session['state']
    code = request.data

    try:
        # Upgrade the authorization code into a credentials object
        oauth_flow = flow_from_clientsecrets(config['CLIENT_SECRETS_PATH'],
                                             scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        return json_error_message('Failed to upgrade the authorization code.',
                                  401)

    gplus_id = credentials.id_token['sub']

    # Store the access token in the session for later use.
    session['credentials'] = credentials.access_token
    session['gplus_id'] = gplus_id

    if User.objects(gplus_id=gplus_id).count() == 0:
        # A new user model must be made

        # Get the user's name and email to populate the form
        http = httplib2.Http()
        http = credentials.authorize(http)
        people_document = gplus_service.people().get(
            userId='me').execute(http=http)

        # The user must be whitelisted in order to create an account.
        email = people_document['emails'][0]['value']
        if Whitelist.objects(email=email).count() != 1:
            return json_error_message('User has not been whitelisted.',
                                      401,
                                      {'whitelisted': False, 'email': email})

        return json_success({
            'redirect_url': url_for('.create_profile',
                                    next=request.args.get('next'),
                                    name=people_document['displayName'],
                                    email=email,
                                    image_url=people_document['image']['url'])
        })

    user = User.objects().get(gplus_id=gplus_id)
    user.register_login()
    user.save()

    # The user already exists.  Redirect to the next url or
    # the root of the application ('/')
    if request.args.get('next'):
        return json_success({'redirect_url': request.args.get('next')})
    return json_success({'redirect_url': request.url_root})