Beispiel #1
0
def oauth2callback(request):
    
    if request.GET.get('error', ''):
        return redirect('login')
    
    try:
        f = FlowModel.objects.get(id=request.session.session_key)
        credential = f.flow.step2_exchange(request.REQUEST)
    except FlowModel.DoesNotExist:
        return error400(request, 'We could not sign you in, make sure you are not using an outdated link/bookmark.')
    except FlowExchangeError:
        f.delete()
        return error400(request, 'We could not sign you in, make sure you are not using an outdated link/bookmark.')
    
    #storage = Storage(CredentialsModel, 'id', request.user, 'credential')
    #storage.put(credential)
    
    # Remove the flow model
    f.delete()
    
    # Get the infos
    http = httplib2.Http()
    http = credential.authorize(http)
    service = build("oauth2", "v2", http=http)
                       
    infos = service.userinfo().get().execute()
    
    # If not verified email, do not authenticate
    if not infos.get('verified_email', False):
        return redirect('login')
    
    signup = {}
    if infos.get('given_name'): signup['firstname'] = infos.get('given_name') 
    signup['username'] = infos.get('email') 
    signup['email'] = infos.get('email') 
    
    signup['icon'] = infos.get('picture', '')
    
    # If the user does not exist: create it
    try:
        user = User.objects.get(username=signup['email'])
        
        p = user.get_profile()
        if signup['icon'] and p and not p.icon:
            p.icon = signup['icon']
            p.save()
        
    except User.DoesNotExist:
        user = None
    
    if not user :
        # Random 8 characters password
        signup['password'] = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8))
        
        errors = create_account(SignupForm(signup))
        if errors: 
            return error500(request, 'There was an error signing you in, please try again later.')
           
        user = User.objects.get(username=signup['email'])
    
    # It is necessary to set the backend (done by 'authenticate' under normal circumstances)
    user.backend = 'django.contrib.auth.backends.ModelBackend'
    
    # login
    auth.login(request, user)

    return HttpResponseRedirect("/")