예제 #1
0
파일: api.py 프로젝트: pythonthings/eventum
def events_this_week():
    """
    Get a json object containing information about all the events for the
    current week (Sunday to Sunday).

    **Route:** ``/admin/api/events/this_week

    **Methods:** ``GET``
    """

    today = date.today()
    last_sunday = datetime.combine(
        today - timedelta(days=(today.isoweekday() % 7)), datetime.min.time())
    next_tuesday = last_sunday + timedelta(days=9)
    events = Event.objects(start_date__gte=last_sunday,
                           start_date__lt=next_tuesday).order_by('start_date')
    event_dicts = [event.to_jsonifiable() for event in events]

    return json_success(event_dicts)
예제 #2
0
파일: api.py 프로젝트: coreatcu/new-website
def events_this_week():
    """
    Get a json object containing information about all the events for the
    current week (Sunday to Sunday).

    **Route:** ``/admin/api/events/this_week

    **Methods:** ``GET``
    """

    today = date.today()
    last_sunday = datetime.combine(
        today - timedelta(days=(today.isoweekday() % 7)),
        datetime.min.time())
    next_sunday = last_sunday + timedelta(days=7)
    events = Event.objects(start_date__gte=last_sunday,
                           start_date__lt=next_sunday).order_by('start_date')
    event_dicts = [event.to_jsonifiable() for event in events]

    return json_success(event_dicts)
예제 #3
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(
            current_app.config['EVENTUM_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})
예제 #4
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(
            current_app.config['EVENTUM_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})