Esempio n. 1
0
def oauth_callback(request, service):
    ctx = RequestContext(request)
    access = OAuthAccess(service)

    access_token = request.GET.get('access_token', None)
    signed_request = request.GET.get('signed_request', None)
    if access_token and signed_request:
        data = access.parse_signed_request(signed_request)
        if data:
            auth_token = OAuth20Token(access_token)
            return access.callback(request, access, auth_token)
        else:
            ctx.update({"error": "Invalid token."})
            return render_to_response("oauth_access/oauth_error.html", ctx)

    unauth_token = request.session.get("%s_unauth_token" % service, None)
    try:
        auth_token = access.check_token(unauth_token, request.GET)
    except MissingToken:
        ctx.update({"error": "token_missing"})
    else:
        if auth_token:
            return access.callback(request, access, auth_token)
        else:
            # @@@ not nice for OAuth 2
            ctx.update({"error": request.GET.get("error", "token_mismatch")})
    return render_to_response("oauth_access/oauth_error.html", ctx)
Esempio n. 2
0
def oauth_login(request, service, redirect_field_name="next", redirect_to_session_key="redirect_to"):
    access = OAuthAccess(service)
    if not service == "facebook":
        token = access.unauthorized_token()
        request.session["%s_unauth_token" % service] = token.to_string()
    else:
        token = None
    if hasattr(request, "session"):
        request.session[redirect_to_session_key] = request.GET.get(redirect_field_name)
    return HttpResponseRedirect(access.authorization_url(token))
Esempio n. 3
0
def oauth_login(request, service,
        redirect_field_name="next", redirect_to_session_key="redirect_to"):
    access = OAuthAccess(service)
    if not service == "facebook":
        token = access.unauthorized_token()
        request.session["%s_unauth_token" % service] = token.to_string()
    else:
        token = None
    if hasattr(request, "session"):
        request.session[redirect_to_session_key] = request.GET.get(redirect_field_name)
    return HttpResponseRedirect(access.authorization_url(token))
Esempio n. 4
0
 def process_signup():
     access = OAuthAccess('facebook')
     return access.callback(
         request,
         access,
         token,
         signup_type,
         True,
         True,
         is_ambassador,
         is_phonegap,
     )
Esempio n. 5
0
def finish_signup(request, service):

    access = OAuthAccess(service)
    data = request.session.get("oauth_signup_data", None)
    ctx = {}

    if data["token"]:
        if request.method == "POST":
            form = SignupForm(request.POST)

            # @@@ pulled from Pinax (a class based view would be awesome here
            # to reduce duplication)
            if form.is_valid():
                success_url = get_default_redirect(request)
                user = form.save(request=request)
                if service == "twitter":
                    identifier = data["user_data"]["screen_name"]
                elif service == "facebook":
                    identifier = data["user_data"]["id"]
                access.persist(user, data["token"], identifier=identifier)
                # del request.session["oauth_signup_data"]
                if settings.ACCOUNT_EMAIL_VERIFICATION:
                    return render_to_response(
                        "account/verification_sent.html", {
                            "email": form.cleaned_data["email"],
                        },
                        context_instance=RequestContext(request))
                else:
                    form.login(request, user)
                    messages.add_message(
                        request, messages.SUCCESS,
                        ugettext("Successfully logged in as %(user)s.") %
                        {"user": user_display(user)})
                    return redirect(success_url)
        else:
            initial = {}
            if service == "twitter":
                username = data["user_data"]["screen_name"]
                if not User.objects.filter(username=username).exists():
                    initial["username"] = data["user_data"]["screen_name"]
                else:
                    ctx["username_taken"] = username
            form = SignupForm(initial=initial)

        ctx.update({
            "service": service,
            "form": form,
        })
        ctx = RequestContext(request, ctx)
        return render_to_response("oauth_access/finish_signup.html", ctx)
    else:
        return HttpResponse("no token!")
Esempio n. 6
0
def finish_signup(request, service):
    
    access = OAuthAccess(service)
    data = request.session.get("oauth_signup_data", None)
    ctx = {}
    
    if data["token"]:
        if request.method == "POST":
            form = SignupForm(request.POST)
            
            # @@@ pulled from Pinax (a class based view would be awesome here
            # to reduce duplication)
            if form.is_valid():
                success_url = get_default_redirect(request)
                user = form.save(request=request)
                if service == "twitter":
                    identifier = data["user_data"]["screen_name"]
                elif service == "facebook":
                    identifier = data["user_data"]["id"]
                access.persist(user, data["token"], identifier=identifier)
                # del request.session["oauth_signup_data"]
                if settings.ACCOUNT_EMAIL_VERIFICATION:
                    return render_to_response("account/verification_sent.html", {
                        "email": form.cleaned_data["email"],
                    }, context_instance=RequestContext(request))
                else:
                    form.login(request, user)
                    messages.add_message(request, messages.SUCCESS,
                        ugettext("Successfully logged in as %(user)s.") % {
                            "user": user_display(user)
                        }
                    )
                    return redirect(success_url)
        else:
            initial = {}
            if service == "twitter":
                username = data["user_data"]["screen_name"]
                if not User.objects.filter(username=username).exists():
                    initial["username"] = data["user_data"]["screen_name"]
                else:
                    ctx["username_taken"] = username
            form = SignupForm(initial=initial)
        
        ctx.update({
            "service": service,
            "form": form,
        })
        ctx = RequestContext(request, ctx)
        return render_to_response("oauth_access/finish_signup.html", ctx)
    else:
        return HttpResponse("no token!")
Esempio n. 7
0
def oauth_callback(request, service):
    ctx = RequestContext(request)
    access = OAuthAccess(service)
    unauth_token = request.session.get("%s_unauth_token" % service, None)
    try:
        auth_token = access.check_token(unauth_token, request.GET)
    except MissingToken:
        ctx.update({"error": "token_missing"})
    else:
        if auth_token:
            return access.callback(request, access, auth_token)
        else:
            # @@@ not nice for OAuth 2
            ctx.update({"error": "token_mismatch"})
    return render_to_response("oauth_access/oauth_error.html", ctx)
Esempio n. 8
0
def oauth_callback(request, service):
    ctx = RequestContext(request)
    access = OAuthAccess(service)
    unauth_token = request.session.get("%s_unauth_token" % service, None)
    try:
        auth_token = access.check_token(unauth_token, request.GET)
    except MissingToken:
        ctx.update({"error": "token_missing"})
    else:
        if auth_token:
            return access.callback(request, access, auth_token)
        else:
            # @@@ not nice for OAuth 2
            ctx.update({"error": "token_mismatch"})
    return render_to_response("oauth_access/oauth_error.html", ctx)
Esempio n. 9
0
def oauth_login(request, service,
        redirect_field_name="next", redirect_to_session_key="redirect_to"):
    access = OAuthAccess(service)
    url_extra = ""
    
    if not service == "facebook":
        token = access.unauthorized_token()
        request.session["%s_unauth_token" % service] = token.to_string()
    else:
        if getattr(request, 'is_touch_device', False):
            url_extra = "&display=touch"
        token = None

    if hasattr(request, "session") and redirect_field_name in request.GET:
        request.session[redirect_to_session_key] = request.GET.get(redirect_field_name)
    return HttpResponseRedirect(access.authorization_url(token)+url_extra)
Esempio n. 10
0
def get_facebook_auth_url(request, url_name, args=None):
	oauth_access = OAuthAccess(service="facebook")
	facebook_redirect_url = request.build_absolute_uri(reverse(url_name, args=args))
	facebook_auth_url = '%s?client_id=%s&redirect_uri=%s&display=page' % (oauth_access.authorize_url,
	                                                                      oauth_access.key,
	                                                                      facebook_redirect_url)
	return facebook_auth_url
Esempio n. 11
0
    def post(self, request, format=None):
        try:
            token = request.POST.get('token')
        except:
            return HttpResponseBadRequest()

        access = OAuthAccess('facebook')
        auth_token = OAuth20Token(token)
        user, error = access.callback(request,
                                      access,
                                      auth_token,
                                      is_ajax=True)
        if user:
            return Response()
        else:
            return Response(error)
Esempio n. 12
0
def load_facebook_user_data(token):
	access = OAuthAccess(service="facebook")
	fb = FacebookCallback()
	response = fb.fetch_user_data(None, access, OAuth20Token(token))
	if response and response.get('error', False):
		msg = response['error'].get('message', '')
		if response['error'].get('type', '') == 'OAuthException':
			raise FacebookAuthError(msg)
		else:
			raise Exception(msg)
Esempio n. 13
0
def oauth_callback(request, service):
    ctx = RequestContext(request)
    access = OAuthAccess(service)
    unauth_token = request.session.get("%s_unauth_token" % service, None)
    try:
        #print "oauth_callback unauth_token = %s" % unauth_token
        #print "oauth_callback request.GET = %s" % request.GET
        auth_token = access.check_token(unauth_token, request.GET)
        #print "oauth_login auth_token = %s" % auth_token
    except MissingToken:
        ctx.update({"error": "token_missing"})
    else:
        if auth_token:
            cback = access.callback(request, access, auth_token)
            return cback.redirect()
        else:
            # @@@ not nice for OAuth 2
            ctx.update({"error": "token_mismatch"})
    
    return render_to_response("oauth_access/oauth_error.html", ctx)
Esempio n. 14
0
def oauth_callback(request, service):
    ctx = RequestContext(request)
    access = OAuthAccess(service)

    access_token = request.GET.get('access_token', None)
    signed_request = request.GET.get('signed_request', None)
    if access_token and signed_request:
        data = access.parse_signed_request(signed_request)
        if data:
            auth_token = OAuth20Token(access_token)
            return access.callback(request, access, auth_token)
        else:
            ctx.update({"error": "Invalid token."})
            return render_to_response("oauth_access/oauth_error.html", ctx)

    unauth_token = request.session.get("%s_unauth_token" % service, None)
    try:
        auth_token = access.check_token(unauth_token, request.GET)
    except MissingToken:
        ctx.update({"error": "token_missing"})
    else:
        if auth_token:
            return access.callback(request, access, auth_token)
        else:
            # @@@ not nice for OAuth 2
            ctx.update({"error": request.GET.get("error", "token_mismatch")})
    return render_to_response("oauth_access/oauth_error.html", ctx)
Esempio n. 15
0
 def get_contacts(self, credentials):
     from oauth_access.access import OAuthAccess
     yahoo_token = credentials["yahoo_token"]
     access = OAuthAccess("yahoo")
     guid = access.make_api_call(
         "json",
         "http://social.yahooapis.com/v1/me/guid?format=json",
         yahoo_token
     )["guid"]["value"]
     address_book = access.make_api_call(
         "json",
         "http://social.yahooapis.com/v1/user/%s/contacts?format=json&count=max&view=tinyusercard" % guid,
         yahoo_token,
     )
     for contact in address_book["contacts"]["contact"]:
         # e-mail (if not found skip contact)
         try:
             email = self.get_field_value(contact, "email")
         except KeyError:
             continue
         # name (first and last comes together)
         try:
             name = self.get_field_value(contact, "name")
         except KeyError:
             name = ""
         if name:
             first_name = name["givenName"]
             last_name = name["familyName"]
             if first_name and last_name:
                 name = "%s %s" % (first_name, last_name)
             elif first_name:
                 name = first_name
             elif last_name:
                 name = last_name
             else:
                 name = ""
         yield {
             "email": email,
             "name": name,
         }
Esempio n. 16
0
 def get_contacts(self, credentials):
     from oauth_access.access import OAuthAccess
     yahoo_token = credentials["yahoo_token"]
     access = OAuthAccess("yahoo")
     guid = access.make_api_call(
         "json", "http://social.yahooapis.com/v1/me/guid?format=json",
         yahoo_token)["guid"]["value"]
     address_book = access.make_api_call(
         "json",
         "http://social.yahooapis.com/v1/user/%s/contacts?format=json&count=max&view=tinyusercard"
         % guid,
         yahoo_token,
     )
     for contact in address_book["contacts"]["contact"]:
         # e-mail (if not found skip contact)
         try:
             email = self.get_field_value(contact, "email")
         except KeyError:
             continue
         # name (first and last comes together)
         try:
             name = self.get_field_value(contact, "name")
         except KeyError:
             name = ""
         if name:
             first_name = name["givenName"]
             last_name = name["familyName"]
             if first_name and last_name:
                 name = "%s %s" % (first_name, last_name)
             elif first_name:
                 name = first_name
             elif last_name:
                 name = last_name
             else:
                 name = ""
         yield {
             "email": email,
             "name": name,
         }
Esempio n. 17
0
 def get_contacts(self, credentials):
     from oauth_access.access import OAuthAccess
     linkedin_token = credentials["linkedin_token"]
     access = OAuthAccess("linkedin")
     tree = access.make_api_call(
         "xml",
         "http://api.linkedin.com/v1/people/~/connections:(first-name,last-name)",
         linkedin_token,
     )
     persons = list(tree.iter("person"))
     for person in persons:
         name = ''
         first_name = person.find('first-name')
         if first_name is not None and first_name.text:
             name = first_name.text
         last_name = person.find('last-name')
         if last_name is not None and last_name.text:
             if name:
                 name += ' '
             name += last_name.text
         yield {
             "email": "",
             "name": name,
         }
Esempio n. 18
0
 def signup(self,
            type='client',
            is_ambassador=False,
            user_data_changed=None):
     user_data = {
         'first_name': 'test',
         'last_name': 'test',
         'email': self.email,
         'id': '1'
     }
     if user_data_changed is not None:
         user_data.update(user_data_changed)
     FacebookCallback().handle_no_user(self.request,
                                       OAuthAccess(service='facebook'),
                                       user_data, type, is_ambassador)
Esempio n. 19
0
 def get_contacts(self, credentials):
     from oauth_access.access import OAuthAccess
     linkedin_token = credentials["linkedin_token"]
     access = OAuthAccess("linkedin")
     tree = access.make_api_call(
         "xml",
         "http://api.linkedin.com/v1/people/~/connections:(first-name,last-name)",
         linkedin_token,
     )
     persons = list(tree.iter("person"))
     for person in persons:
         name = ''
         first_name = person.find('first-name')
         if first_name is not None and first_name.text:
             name = first_name.text
         last_name = person.find('last-name')
         if last_name is not None and last_name.text:
             if name:
                 name += ' '
             name += last_name.text
         yield {
             "email": "",
             "name": name,
         }
Esempio n. 20
0
def oauth_callback(request, service):
    def get_oauth_error():
        if type(auth_token) in [unicode, str]:
            return auth_token

    ctx = RequestContext(request)
    access = OAuthAccess(service)

    access_token = request.GET.get('access_token', None)
    signed_request = request.GET.get('signed_request', None)
    if access_token and signed_request:
        if signed_request == 'n/a':
            data = True
        else:
            data = access.parse_signed_request(signed_request)
        if data:
            auth_token = OAuth20Token(access_token)
            return access.callback(request, access, auth_token)
        else:
            ctx.update({"error": "Invalid token."})
            return render_to_response("oauth_access/oauth_error.html", ctx)

    unauth_token = request.session.get("%s_unauth_token" % service, None)
    try:
        if service == 'stripe':
            if request.GET.get('error', False):
                ctx.update({'error': request.GET['error_description']})
                return render_to_response("oauth_access/oauth_error.html", ctx)

            auth_token, publishable_key = access.check_token(unauth_token,
                request.GET)
        else:
            auth_token = access.check_token(unauth_token, request.GET)
    except MissingToken:
        ctx.update({"error": "token_missing"})
    else:
        auth_token_error = get_oauth_error()
        if auth_token_error is None:
            if service == 'stripe':
                return access.callback(request, access, auth_token,
                    publishable_key)
            else:
                return access.callback(request, access, auth_token)
        else:
            # @@@ not nice for OAuth 2
            if service == 'stripe':
                ctx.update({"error": auth_token_error})
            else:
                ctx.update({"error": request.GET.get("error", "token_mismatch")})
    return render_to_response("oauth_access/oauth_error.html", ctx)
Esempio n. 21
0
def finish_signup(request, service):
    access = OAuthAccess(service)
    return access.callback.finish_signup(request, service)
Esempio n. 22
0
    def setUp(self):
        self.request = HttpRequest()
        self.request.user = AnonymousUser()
        self.request.session = SessionStore()

        self.oauth_access = OAuthAccess(service='facebook')