Example #1
0
def auth_return(request):
    if not xsrfutil.validate_token(settings.SECRET_KEY, request.REQUEST['state'],
                                 request.user):
        return  HttpResponseBadRequest()
    
    user = request.user
    
    #Store the credentials
    credential = FLOW.step2_exchange(request.REQUEST)
    storage = Storage(GcalCredentials, 'id', user, 'credential')
    storage.put(credential)
    
    #Create a UserInfo entry (or overwrite existing?)
    userinfo = GcalUserInfo(user=user, api_latest_update=None, latest_update_date=None, yoursync_calendar_id=None)
    userinfo.save()
    
    return HttpResponseRedirect(reverse('gcal:index'))
def get_or_create_calendar(service, user):
    calendar_name = "YourSync"
    
    created = False
    do_create = False
        
    gcal_user_info = user.gcaluserinfo
    if gcal_user_info:
        if gcal_user_info.yoursync_calendar_id:
            calendar_id = gcal_user_info.yoursync_calendar_id
        else:
            do_create = True
    else:
        do_create = True
        
    if do_create:    
        #Create Yoursync calendar for the user if it doesn't already have it
        calendar_list = service.calendarList().list(minAccessRole='owner').execute()
        
        calendar_dict = next((c for c in calendar_list['items'] if c['summary'].lower() == calendar_name.lower()), None)   #Check if user has a yoursync calendar
        
        if not calendar_dict:
            #Create Calendar for user on service if it doesn't exist
                        
            #Get timezone setting if user has it
            settings_list = service.settings().list().execute()
            timezone_dict = next((s for s in settings_list['items'] if s['id'].lower() == 'timezone'), None)
            
            #Create Yoursync calendar (with user timezone if available)
            if timezone_dict:
                new_calendar = {'summary': calendar_name, 'timeZone': timezone_dict['value']}
            else:
                new_calendar = {'summary': calendar_name}
                
            calendar_dict = service.calendars().insert(body=new_calendar).execute()
            calendar_id = calendar_dict['id']
            created = True
        else:
            calendar_id = calendar_dict['id']
            
        calendar_id_storage = GcalUserInfo(user=user, yoursync_calendar_id=calendar_id, api_latest_update=None, latest_update_date=None)
        calendar_id_storage.save()
        
    return calendar_id, created