示例#1
0
文件: views.py 项目: tiffanyqi/cal2
def clear_auth(request):
    """
    Clears the credentials for the requesting user
    """
    if request.user:
        profile, _ = Profile.get_or_create(user=request.user)
        profile.clear_credentials()
    return HttpResponseRedirect("/")
示例#2
0
def clear_auth(request):
    """
    Clears the credentials for the requesting user
    """
    if request.user:
        profile, _ = Profile.get_or_create(user=request.user)
        profile.clear_credentials()
    return HttpResponseRedirect("/")
示例#3
0
文件: views.py 项目: tiffanyqi/cal2
def google_auth(request):
    """
    Handles Google oauth flow. For details, visit
    https://developers.google.com/api-client-library/python/guide/aaa_oauth#OAuth2WebServerFlow
    https://developers.google.com/api-client-library/python/guide/django
    """

    flow = None
    default_flow = OAuth2WebServerFlow(
        client_id=settings.GOOGLE_CALENDAR_API_CLIENT_ID,
        client_secret=settings.GOOGLE_CALENDAR_API_CLIENT_SECRET,
        scope=['https://www.googleapis.com/auth/calendar', 'profile', 'email'],
        redirect_uri=settings.BASE_URL + '/auth/google')
    default_flow.params['access_type'] = 'offline'
    default_flow.params['include_granted_scopes'] = 'true'
    default_flow.params['prompt'] = 'consent'

    # Try to retrieve an existing flow, or create one if it doesn't exist
    gflow = GoogleFlow.objects.filter(id=request.user).last()

    if gflow and gflow.flow.params.get('prompt') != 'consent':
        # Delete any flows that don't have the prompt parameter set, since that will
        # prevent the credentials from getting a refresh token
        gflow.delete()
        gflow = None

    if not gflow:
        # print "Could not retrieve existing flow"
        gflow = GoogleFlow(id=request.user, flow=default_flow)
        gflow.save()
    flow = gflow.flow

    code = request.GET.get('code', None)
    error = request.GET.get('error', None)

    if error:
        # TODO eventually make this prettier, like redirect to some landing page
        return HttpResponseBadRequest(
            "Authentication failed. Reason: {}".format(error))
    elif code:
        credential = flow.step2_exchange(code)
        # Save the credentials
        storage = Storage(GoogleCredentials, 'user', request.user,
                          'credential')
        storage.put(credential)
        profile, _ = Profile.get_or_create(user=request.user)
        profile.authed = True
        profile.save()

        # TODO improve the latency over here
        request.user.googlecredentials.import_calendars()

        return HttpResponseRedirect("/")
    else:
        auth_uri = flow.step1_get_authorize_url()
        return HttpResponseRedirect(auth_uri)
示例#4
0
 def i_calories(self, user):
     try:
         profile = Profile.objects.get(user=user)
     except:
         t = Profile()
         t.user = user
         t.id = user.id
         t.save()
         profile = t
     return profile.calories
示例#5
0
def google_auth(request):
    """
    Handles Google oauth flow. For details, visit
    https://developers.google.com/api-client-library/python/guide/aaa_oauth#OAuth2WebServerFlow
    https://developers.google.com/api-client-library/python/guide/django
    """

    flow = None
    default_flow = OAuth2WebServerFlow(client_id=settings.GOOGLE_CALENDAR_API_CLIENT_ID,
                                       client_secret=settings.GOOGLE_CALENDAR_API_CLIENT_SECRET,
                                       scope=['https://www.googleapis.com/auth/calendar','profile','email'],
                                       redirect_uri=settings.BASE_URL + '/auth/google')
    default_flow.params['access_type'] = 'offline'
    default_flow.params['include_granted_scopes'] = 'true'

    # Try to retrieve an existing flow, or create one if it doesn't exist
    gflow = GoogleFlow.objects.filter(id=request.user).last()
    if not gflow:
        gflow = GoogleFlow(id=request.user,
                          flow=default_flow)
        gflow.save()
    flow = gflow.flow

    code = request.GET.get('code', None)
    error = request.GET.get('error', None)

    if error:
        # TODO eventually make this prettier, like redirect to some landing page
        return HttpResponseBadRequest("Authentication failed. Reason: {}".format(error))
    elif code:
        credential = flow.step2_exchange(code)
        # Save the credentials
        storage = Storage(GoogleCredentials, 'user', request.user, 'credential')
        storage.put(credential)
        profile, _ = Profile.get_or_create(user=request.user)
        profile.authed = True
        profile.save()

        # TODO improve the latency over here
        request.user.googlecredentials.import_calendars()

        return HttpResponseRedirect("/")
    else:
        auth_uri = flow.step1_get_authorize_url()
        return HttpResponseRedirect(auth_uri)
示例#6
0
def twitter_authenticated(request):
    # Step 1. Use the request token in the session to build a new client.
    token = oauth.Token(request.session['request_token']['oauth_token'],
                        request.session['request_token']['oauth_token_secret'])
    client = oauth.Client(consumer, token)

    # Step 2. Request the authorized access token from Twitter.
    resp, content = client.request(access_token_url, "GET")
    if resp['status'] != '200':
        print content
        raise Exception("Invalid response from Twitter.")

    """
    This is what you'll get back from Twitter. Note that it includes the
    user's user_id and screen_name.
    {
        'oauth_token_secret': 'IcJXPiJh8be3BjDWW50uCY31chyhsMHEhqJVsphC3M',
        'user_id': '120889797',
        'oauth_token': '120889797-H5zNnM3qE0iFoTTpNEHIz3noL9FKzXiOxwtnyVOD',
        'screen_name': 'heyismysiteup'
    }
    """
    access_token = dict(cgi.parse_qsl(content))

    # Step 3. Lookup the user or create them if they don't exist.
    try:
        user = User.objects.get(username=access_token['screen_name'])
    except User.DoesNotExist:
        # When creating the user I just use their [email protected]
        # for their email and the oauth_token_secret for their password.
        # These two things will likely never be used. Alternatively, you
        # can prompt them for their email here. Either way, the password
        # should never be used.
        user = User.objects.create_user(access_token['screen_name'],
                                        '*****@*****.**' % access_token['screen_name'],
                                        access_token['oauth_token_secret'])

        # Save our permanent token and secret for later.
        profile = Profile()
        profile.user = user
        profile.oauth_token = access_token['oauth_token']
        profile.oauth_secret = access_token['oauth_token_secret']
        profile.save()

    # Authenticate the user and log them in using Django's pre-built
    # functions for these things.
    user = authenticate(username=access_token['screen_name'],
                        password=access_token['oauth_token_secret'])
    login(request, user)

    return HttpResponseRedirect('/')
示例#7
0
def sync(request, format=None):
    if not request.user:
        return Response("Not logged in")

    profile = Profile.get_or_create(request.user)[0]

    if request.query_params.get('sync_all'):
        profile.create_calendars(only_primary=False)
        calendars = GCalendar.objects.filter(user=request.user)
    else:
        profile.create_calendars(only_primary=True)
        calendars = [profile.main_calendar]

    for calendar in calendars:
        if request.query_params.get('full_sync'):
            calendar.sync(full_sync=True)
        else:
            calendar.sync()

    return HttpResponseRedirect("/sync?no_sync=true")
示例#8
0
def sync(request, format=None):

    if not request.user:
        return Response("Not logged in")

    profile = Profile.get_or_create(request.user)[0]

    if request.query_params.get('sync_all'):
        profile.create_calendars(only_primary=False)
        calendars = GCalendar.objects.filter(user=request.user)
    else:
        profile.create_calendars(only_primary=True)
        calendars = [profile.main_calendar]

    for calendar in calendars:
        if request.query_params.get('full_sync'):
            calendar.sync(full_sync=True)
        else:
            calendar.sync()

    return HttpResponseRedirect("/")