示例#1
0
文件: views.py 项目: taras1k/twevent
def twitter_authenticated(request):
    oauth_token = request.session.get('oauth_token',None)
    oauth_token_secret = request.session.get('oauth_token_secret', None)
    if oauth_token == None and oauth_token_secret == None:
        return  HttpResponseRedirect('/')

    # Step 1. Use the request token in the session to build a new client.
    token = oauth.Token(oauth_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':
        return  HttpResponseRedirect('/')
    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'])
        user = User.objects.get(username=access_token['user_id'])
    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['user_id'], '*****@*****.**' % access_token['screen_name'],
            access_token['oauth_token_secret'])
        # Save our permanent token and secret for later.
        profile = Profile()
        profile.user = user
        profile.twitter_username = access_token['screen_name']
        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.
    if not user.check_password(access_token['oauth_token_secret']):
        user.set_password(access_token['oauth_token_secret'])
        user.save()
        profile = Profile.objects.get(user = user)
        profile.oauth_token = access_token['oauth_token']
        profile.oauth_secret = access_token['oauth_token_secret']
        profile.save()

    user = authenticate(username=access_token['user_id'], password=access_token['oauth_token_secret'])
    login(request, user)

    return HttpResponseRedirect('/')
示例#2
0
def create_profile(user, oauth_token, secret_token):
    profile = Profile()
    profile.user = user
    profile.oauth_token = oauth_token
    profile.oauth_secret = secret_token
    profile.save()
    return