def process_authentication_request(self, request):
        logout_request = request.POST.get('logoutRequest', None)
        if logout_request:
            if settings.CAS_LOGOUT_REQUESTS_ENABLED:
                handle_logout_request(request, logout_request)
                raise InvalidAuthentication('CAS logout request processed')
            else:
                raise InvalidAuthentication('CAS logout request ignored, disabled in configuration')

        ticket = request.GET.get('ticket', None)
        if not ticket:
            raise InvalidAuthentication(_('Login failed. CAS ticket is missing.'))

        service = service_url(request)
        username, attributes = validate(ticket, service)
        if not username:
            raise InvalidAuthentication(_('Login failed. CAS ticket is invalid.'))

        try:
            _user = User.objects.get(username=username)
            self._sync_user_attributes(_user, attributes)
        except User.DoesNotExist:
            _user = User(username=username)
            _user.set_unusable_password()
            self._sync_user_attributes(_user, attributes)
            _user.save()
            UserJoinsAction(user=_user, ip=request.META['REMOTE_ADDR']).save()

        request.session[CAS_TICKET_SESSION_ATTR] = ticket
        return _user
Exemple #2
0
    def prepare_authentication_request(self, request, redirect_to):
        if not redirect_to.startswith('http://') or redirect_to.startswith(
                'https://'):
            redirect_to = get_url_host(request) + redirect_to

        user_url = self.get_user_url(request)

        if xri.identifierScheme(user_url) == 'XRI' and getattr(
                settings, 'OPENID_DISALLOW_INAMES', False):
            raise InvalidAuthentication('i-names are not supported')

        consumer = Consumer(request.session, OsqaOpenIDStore())

        try:
            auth_request = consumer.begin(user_url)
        except DiscoveryFailure:
            raise InvalidAuthentication(
                _('Sorry, but your input is not a valid OpenId'))

        sreg = getattr(self, 'sreg_attributes', False)

        if sreg:
            s = SRegRequest()

            for k, attr_dic in sreg.items():
                if k == "policy_url":
                    s.policy_url = attr_dic
                    continue

                for attr_name in attr_dic.keys():
                    s.requestField(field_name=attr_name,
                                   required=(k == "required"))

            auth_request.addExtension(s)

        ax_schema = getattr(self, 'dataype2ax_schema', False)

        if ax_schema and request.session.get('force_email_request', True):
            axr = AXFetchRequest()
            for data_type, schema in ax_schema.items():
                if isinstance(schema, tuple):
                    axr.add(AttrInfo(schema[0], required=True,
                                     alias=schema[1]))
                else:
                    axr.add(AttrInfo(schema, required=True, alias=data_type))

            auth_request.addExtension(axr)

        trust_root = getattr(settings, 'OPENID_TRUST_ROOT',
                             get_url_host(request) + '/')

        return auth_request.redirectURL(trust_root, redirect_to)
Exemple #3
0
    def process_authentication_request(self, request):
        unauthed_token = request.session.get('unauthed_token', None)
        if not unauthed_token:
             raise InvalidAuthentication(_('Error, the oauth token is not on the server'))

        token = oauth2.Token.from_string(unauthed_token)

        if token.key != request.GET.get('oauth_token', 'no-token'):
            raise InvalidAuthentication(_("Something went wrong! Auth tokens do not match"))

        access_token = self.fetch_access_token(token, request.GET.get('oauth_verifier', '')) 

        return access_token.to_string()
    def process_authentication_request(self, request):
        form_auth = ClassicLoginForm(request.POST)

        if form_auth.is_valid():
            return form_auth.get_user()
        else:
            raise InvalidAuthentication(" ".join(form_auth.errors.values()[0]))
Exemple #5
0
    def process_authentication_request(self, request):
        try:
            redirect_uri = "%s%s" % (django_settings.APP_URL,
                                     reverse('auth_provider_done',
                                             prefix='/',
                                             kwargs={'provider': 'facebook'}))
            args = dict(client_id=settings.FB_API_KEY,
                        redirect_uri=redirect_uri)

            args[
                "client_secret"] = settings.FB_APP_SECRET  #facebook APP Secret

            args["code"] = request.GET.get("code", None)
            response = cgi.parse_qs(
                urlopen("https://graph.facebook.com/oauth/access_token?" +
                        urlencode(args)).read())
            access_token = response["access_token"][-1]

            user_data = self.get_user_data(access_token)
            assoc_key = user_data["id"]

            # Store the access token in cookie
            request.session["access_token"] = access_token
            request.session["assoc_key"] = assoc_key

            # Return the association key
            return assoc_key
        except Exception, e:
            logging.error("Problem during facebook authentication: %s" % e)
            raise InvalidAuthentication(
                _("Something wrond happened during Facebook authentication, administrators will be notified"
                  ))
Exemple #6
0
    def prepare_authentication_request(self, request, redirect_to):
        if not redirect_to.startswith('http://') or redirect_to.startswith(
                'https://'):
            redirect_to = get_url_host(request) + redirect_to

        user_url = self.get_user_url(request)

        if xri.identifierScheme(user_url) == 'XRI' and getattr(
                settings, 'OPENID_DISALLOW_INAMES', False):
            raise InvalidAuthentication('i-names are not supported')

        consumer = Consumer(request.session, OsqaOpenIDStore())

        try:
            auth_request = consumer.begin(user_url)
        except DiscoveryFailure:
            raise InvalidAuthentication(
                _('Sorry, but your input is not a valid OpenId'))

        #sreg = getattr(settings, 'OPENID_SREG', False)

        #if sreg:
        #    s = SRegRequest()
        #    for sarg in sreg:
        #        if sarg.lower().lstrip() == "policy_url":
        #            s.policy_url = sreg[sarg]
        #        else:
        #            for v in sreg[sarg].split(','):
        #                s.requestField(field_name=v.lower().lstrip(), required=(sarg.lower().lstrip() == "required"))
        #    auth_request.addExtension(s)

        #auth_request.addExtension(SRegRequest(required=['email']))

        if request.session.get('force_email_request', True):
            axr = AXFetchRequest()
            for data_type, schema in self.dataype2ax_schema.items():
                if isinstance(schema, tuple):
                    axr.add(AttrInfo(schema[0], 1, True, schema[1]))
                else:
                    axr.add(AttrInfo(schema, 1, True, data_type))

            auth_request.addExtension(axr)

        trust_root = getattr(settings, 'OPENID_TRUST_ROOT',
                             get_url_host(request) + '/')

        return auth_request.redirectURL(trust_root, redirect_to)
    def process_authentication_request(self, request):
        API_KEY = str(settings.FB_API_KEY)

        # Check if the Facebook cookie has been received.
        if 'fbs_%s' % API_KEY in request.COOKIES:
            fbs_cookie = request.COOKIES['fbs_%s' % API_KEY]
            parsed_fbs = parse_qs(smart_unicode(fbs_cookie))
            self.parsed_fbs = parsed_fbs

            # Check if the session hasn't expired.
            if self.check_session_expiry(request.COOKIES):
                return parsed_fbs['uid'][0]
            else:
                raise InvalidAuthentication(
                    _('Sorry, your Facebook session has expired, please try again'
                      ))
        else:
            raise InvalidAuthentication(
                _('The authentication with Facebook connect failed, cannot find authentication tokens'
                  ))
    def process_authentication_request(self, request):
        """
        Triggered after the Google+ authentication happened. Important
        information from it is extracted, access token and association
        keys are obtained, so that local authentication system could
        process.
        """
        request_state = request.GET['state']
        session_state = request.session['gplus_state']
        if request_state != session_state:
            raise InvalidAuthentication("Request State Did Not Match")
        code = request.GET['code']
        try:
            # Upgrade the authorization code into a credentials object
            oauth_flow = flow_from_clientsecrets(CLIENT_SECRETS_PATH, scope='')
            oauth_flow.redirect_uri = '{0}/account/googleplus/done/'.format(
                django_settings.APP_URL)
            credentials = oauth_flow.step2_exchange(code)
        except FlowExchangeError:
            raise InvalidAuthentication("Could not exchange flows")
        access_token = credentials.access_token
        assoc_key = credentials.id_token['sub']
        request.session["access_token"] = access_token
        request.session["assoc_key"] = assoc_key

        # Convert old Google OpenID to Google+
        openid = credentials.id_token['openid_id']
        already_existing = AuthKeyUserAssociation.objects.filter(
            key=assoc_key, provider="googleplus")
        if already_existing.count() == 0:
            try:
                old = AuthKeyUserAssociation.objects.get(key=openid,
                                                         provider="google")
            except AuthKeyUserAssociation.DoesNotExist:
                pass
            else:
                old.key = assoc_key
                old.provider = "googleplus"
                old.save()

        return assoc_key
    def process_authentication_request(self, request):
        username = request.POST['username'].strip()
        password = request.POST['password']
        uid = str(settings.LDAP_USER_MASK) % username

        #an empty password will cause ldap to try an anonymous bind. This is picked up here
        if not password:
            raise InvalidAuthentication(
                _('Login failed. Please enter valid username and password (both are case-sensitive)'
                  ))

        ldapo = ldap.initialize(str(settings.LDAP_SERVER))
        if (settings.LDAP_USE_TLS):
            ldapo.start_tls_s()
        ldapo.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
        try:
            ldapo.simple_bind_s(str(settings.LDAP_BIND_DN),
                                str(settings.LDAP_BIND_SECRET))
            search = ldapo.search_s(str(settings.LDAP_BASE_DN),
                                    ldap.SCOPE_SUBTREE, uid)
        except ldap.LDAPError:
            #could not bind using credentials specified in ldap config
            raise InvalidAuthentication(
                _('Login failed - LDAP bind error. Please contact your system administrator'
                  ))

        ldapo.unbind_s()

        if not search:
            #could not find user
            raise InvalidAuthentication(
                _('Login failed. Please enter valid username and password (both are case-sensitive)'
                  ))

        #now try to bind as selected user; should raise exception if bind fails
        ldapo = ldap.initialize(str(settings.LDAP_SERVER))
        if (settings.LDAP_USE_TLS):
            ldapo.start_tls_s()
        ldapo.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
        try:
            # F.CRESPEL: use search[0][0] as the DN, so that it works consistently across OpenLDAP/ActiveDirectory
            ###ldapo.simple_bind_s(search[0][1][str(settings.LDAP_DN)][0],password)
            ldapo.simple_bind_s(search[0][0], password)
        except ldap.LDAPError:
            #could not bind as user - password is incorrect
            raise InvalidAuthentication(
                _('Login failed. Please enter valid username and password (both are case-sensitive)'
                  ))
        ldapo.unbind_s()

        try:
            return User.objects.get(username=username)
        except User.DoesNotExist:
            userinfo = search[0][1]
            _user = User(username=userinfo[str(settings.LDAP_UID)][0],
                         email=userinfo[str(settings.LDAP_MAIL)][0],
                         real_name=userinfo[str(settings.LDAP_NAME)][0])
            _user.email_isvalid = True
            _user.set_unusable_password()
            _user.save()
            UserJoinsAction(user=_user, ip=request.META['REMOTE_ADDR']).save()
            return _user
Exemple #10
0
    def process_authentication_request(self, request):
        consumer = Consumer(request.session, OsqaOpenIDStore())

        query_dict = dict([(smart_unicode(k), smart_unicode(v))
                           for k, v in request.GET.items()])

        #for i in query_dict.items():
        #print "%s : %s" % i

        url = get_url_host(request) + request.path
        openid_response = consumer.complete(query_dict, url)

        if openid_response.status == SUCCESS:

            consumer_data = {}

            sreg_attrs = getattr(self, 'sreg_attributes', False)

            if sreg_attrs:
                sreg_response = SRegResponse.fromSuccessResponse(
                    openid_response)

                if sreg_response:
                    all_attrs = {}
                    [
                        all_attrs.update(d) for k, d in sreg_attrs.items()
                        if k != "policy_url"
                    ]

                    for attr_name, local_name in all_attrs.items():
                        if attr_name in sreg_response:
                            consumer_data[local_name] = sreg_response[
                                attr_name]

            ax_schema = getattr(self, 'dataype2ax_schema', False)

            if ax_schema:
                ax = AXFetchResponse.fromSuccessResponse(
                    openid_response, False)

                if ax:
                    axargs = ax.getExtensionArgs()

                    ax_schema2data_type = dict([(s, t)
                                                for t, s in ax_schema.items()])

                    available_types = dict([(ax_schema2data_type[s],
                                             re.sub('^type\.', '', n))
                                            for n, s in axargs.items()
                                            if s in ax_schema2data_type])

                    for t, s in available_types.items():
                        if not t in consumer_data:
                            if axargs.get("value.%s.1" % s, None):
                                consumer_data[t] = axargs["value.%s.1" % s]

            request.session['auth_consumer_data'] = consumer_data

            return request.GET['openid.identity']
        elif openid_response.status == CANCEL:
            raise InvalidAuthentication(
                _('The OpenId authentication request was canceled'))
        elif openid_response.status == FAILURE:
            raise InvalidAuthentication(
                _('The OpenId authentication failed: ') +
                openid_response.message)
        elif openid_response.status == SETUP_NEEDED:
            raise InvalidAuthentication(_('Setup needed'))
        else:
            raise InvalidAuthentication(
                _('The OpenId authentication failed with an unknown status: ')
                + openid_response.status)
Exemple #11
0
class OpenIdAbstractAuthConsumer(AuthenticationConsumer):

    dataype2ax_schema = {
        #'username': '******',
        'email': 'http://axschema.org/contact/email',
        #'web': 'http://axschema.org/contact/web/default',
        #'firstname': 'http://axschema.org/namePerson/first',
        #'lastname': 'http://axschema.org/namePerson/last',
        #'birthdate': 'http://axschema.org/birthDate',
    }

    def get_user_url(self, request):
        try:
            return request.POST['openid_identifier']
        except:
            raise NotImplementedError()

    def prepare_authentication_request(self, request, redirect_to):
        if not redirect_to.startswith('http://') or redirect_to.startswith(
                'https://'):
            redirect_to = get_url_host(request) + redirect_to

        user_url = self.get_user_url(request)

        if xri.identifierScheme(user_url) == 'XRI' and getattr(
                settings, 'OPENID_DISALLOW_INAMES', False):
            raise InvalidAuthentication('i-names are not supported')

        consumer = Consumer(request.session, OsqaOpenIDStore())

        try:
            auth_request = consumer.begin(user_url)
        except DiscoveryFailure:
            raise InvalidAuthentication(
                _('Sorry, but your input is not a valid OpenId'))

        #sreg = getattr(settings, 'OPENID_SREG', False)

        #if sreg:
        #    s = SRegRequest()
        #    for sarg in sreg:
        #        if sarg.lower().lstrip() == "policy_url":
        #            s.policy_url = sreg[sarg]
        #        else:
        #            for v in sreg[sarg].split(','):
        #                s.requestField(field_name=v.lower().lstrip(), required=(sarg.lower().lstrip() == "required"))
        #    auth_request.addExtension(s)

        #auth_request.addExtension(SRegRequest(required=['email']))

        if request.session.get('force_email_request', True):
            axr = AXFetchRequest()
            for data_type, schema in self.dataype2ax_schema.items():
                if isinstance(schema, tuple):
                    axr.add(AttrInfo(schema[0], 1, True, schema[1]))
                else:
                    axr.add(AttrInfo(schema, 1, True, data_type))

            auth_request.addExtension(axr)

        trust_root = getattr(settings, 'OPENID_TRUST_ROOT',
                             get_url_host(request) + '/')

        return auth_request.redirectURL(trust_root, redirect_to)

    def process_authentication_request(self, request):
        consumer = Consumer(request.session, OsqaOpenIDStore())

        query_dict = dict([(k.encode('utf8'), v.encode('utf8'))
                           for k, v in request.GET.items()])

        #for i in query_dict.items():
        #print "%s : %s" % i

        url = get_url_host(request) + request.path
        openid_response = consumer.complete(query_dict, url)

        if openid_response.status == SUCCESS:
            if request.session.get('force_email_request', True):
                try:
                    ax = AXFetchResponse.fromSuccessResponse(openid_response)

                    axargs = ax.getExtensionArgs()

                    ax_schema2data_type = dict([
                        (s, t) for t, s in self.dataype2ax_schema.items()
                    ])

                    available_types = dict([(ax_schema2data_type[s],
                                             re.sub('^type\.', '', n))
                                            for n, s in axargs.items()
                                            if s in ax_schema2data_type])

                    available_data = dict([(t, axargs["value.%s.1" % s])
                                           for t, s in available_types.items()
                                           ])

                    request.session['auth_consumer_data'] = {
                        'email': available_data.get('email', None),
                    }

                except Exception, e:
                    pass
                    #import sys, traceback
                    #traceback.print_exc(file=sys.stdout)

            return request.GET['openid.identity']
        elif openid_response.status == CANCEL:
            raise InvalidAuthentication(
                _('The OpenId authentication request was canceled'))
Exemple #12
0
                    request.session['auth_consumer_data'] = {
                        'email': available_data.get('email', None),
                    }

                except Exception, e:
                    pass
                    #import sys, traceback
                    #traceback.print_exc(file=sys.stdout)

            return request.GET['openid.identity']
        elif openid_response.status == CANCEL:
            raise InvalidAuthentication(
                _('The OpenId authentication request was canceled'))
        elif openid_response.status == FAILURE:
            raise InvalidAuthentication(
                _('The OpenId authentication failed: ') +
                openid_response.message)
        elif openid_response.status == SETUP_NEEDED:
            raise InvalidAuthentication(_('Setup needed'))
        else:
            raise InvalidAuthentication(
                _('The OpenId authentication failed with an unknown status: ')
                + openid_response.status)

    def get_user_data(self, key):
        return {}


def get_url_host(request):
    if request.is_secure():
        protocol = 'https'
Exemple #13
0
class OpenIdAbstractAuthConsumer(AuthenticationConsumer):
    def get_user_url(self, request):
        try:
            return request.POST['openid_identifier']
        except:
            raise NotImplementedError()

    def prepare_authentication_request(self, request, redirect_to):
        if not redirect_to.startswith('http://') or redirect_to.startswith(
                'https://'):
            redirect_to = get_url_host(request) + redirect_to

        user_url = self.get_user_url(request)

        if xri.identifierScheme(user_url) == 'XRI' and getattr(
                settings, 'OPENID_DISALLOW_INAMES', False):
            raise InvalidAuthentication('i-names are not supported')

        consumer = Consumer(request.session, OsqaOpenIDStore())

        try:
            auth_request = consumer.begin(user_url)
        except DiscoveryFailure:
            raise InvalidAuthentication(
                _('Sorry, but your input is not a valid OpenId'))

        #sreg = getattr(settings, 'OPENID_SREG', False)

        #if sreg:
        #    s = SRegRequest()
        #    for sarg in sreg:
        #        if sarg.lower().lstrip() == "policy_url":
        #            s.policy_url = sreg[sarg]
        #        else:
        #            for v in sreg[sarg].split(','):
        #                s.requestField(field_name=v.lower().lstrip(), required=(sarg.lower().lstrip() == "required"))
        #    auth_request.addExtension(s)

        #auth_request.addExtension(SRegRequest(required=['email']))

        if request.session.get('force_email_request', True):
            axr = AXFetchRequest()
            axr.add(
                AttrInfo("http://axschema.org/contact/email", 1, True,
                         "email"))
            auth_request.addExtension(axr)

        trust_root = getattr(settings, 'OPENID_TRUST_ROOT',
                             get_url_host(request) + '/')

        return auth_request.redirectURL(trust_root, redirect_to)

    def process_authentication_request(self, request):
        consumer = Consumer(request.session, OsqaOpenIDStore())

        query_dict = dict([(k.encode('utf8'), v.encode('utf8'))
                           for k, v in request.GET.items()])

        #for i in query_dict.items():
        #    print "%s : %s" % i

        url = get_url_host(request) + request.path
        openid_response = consumer.complete(query_dict, url)

        if openid_response.status == SUCCESS:
            if request.session.get('force_email_request', True):
                try:
                    ax = AXFetchResponse.fromSuccessResponse(openid_response)
                    email = ax.getExtensionArgs()['value.ext0.1']
                    request.session['auth_email_request'] = email
                except Exception, e:
                    pass

            return request.GET['openid.identity']
        elif openid_response.status == CANCEL:
            raise InvalidAuthentication(
                _('The OpenId authentication request was canceled'))