Beispiel #1
0
def check_email(backend, details, user=None, *args, **kwargs):
    """
    Create user. Depends on get_username pipeline.
    This pipeline rise exception if some use has same email.
    So if someone know you email on djbook.ru, he can't use it to create account
    on services supported for login and login on djbook to your account.
    Really I think it is impossible register somewhere with other one email,
    but it works as we like.
    """
    if user:
        return {}

    email = details.get('email')

    if email:
        users = list(backend.strategy.storage.user.get_users_by_email(email))
        if users:
            msg = _('"%(email)s" is already used by other account. If it is your account, '
                    'login and connect it on profile edit page.') % {'email': email}
            raise AuthException(backend, msg)
    else:
        raise AuthException(
            backend, _('Social service does not return email. Use registration form.'))

    return {}
Beispiel #2
0
    def validateSignature(self, ts, sig):
        current_ts = int(time.time())
        signature_life = self.setting('EDUTONE_SIGNATURE_LIFE') or 10
        if ts + signature_life < current_ts or ts > current_ts:
            raise AuthException(self, 'Signature is expired.')

        secretKey = self.setting('EDUTONE_SECRET_KEY')

        hashed = hmac.new(base64.b64decode(secretKey), str(ts), sha1)
        check_signature = binascii.b2a_base64(hashed.digest())[:-1]

        if check_signature != sig:
            raise AuthException(self, 'Invalid sugnature.')
Beispiel #3
0
def check_email(request, backend, details, uid, user=None, *args, **kwargs):
    if backend.name == 'google-oauth2':

        # verifica se é um usuário jah existente pelo google, e que apenas vai fazer o login
        if uid and user:
            print("EU JA EXISTO")
            pass

        # se ele não existe é pq será registrado
        else:
            # pega o e-mail do cara que vai ser registado
            email = details.get('email', '')
            print("TO SENDO CRIADO")
            # procura na db se existe algum email parecido, se existir volta pro login
            count = User.objects.filter(email=email).count()
            if count > 0:
                #messages.success(request, 'Domain Added.')
                #return HttpResponseRedirect(reverse('login'))
                print("LEVANTEI A EXCEPTION")
                raise AuthException(backend, 'Not unique email address.')
            else:
                # siginifca q o user será registrado, logo podemos criar o seu perfil
                perfil = Perfil.objects.create(user=user)
                print("CRIANDO PERFIL")
                perfil.save()
Beispiel #4
0
def associate_by_email(backend, details, user=None, *args, **kwargs):
    """
    Associate current auth with a user with the same email address in the DB.

    This pipeline entry is not 100% secure unless you know that the providers
    enabled enforce email verification on their side, otherwise a user can
    attempt to take over another user account by using the same (not validated)
    email address on some provider.  This pipeline entry is disabled by
    default.
    """
    if user:
        return None

    email = details.get('email')
    if email:
        # Try to associate accounts registered with the same email address,
        # only if it's a single object. AuthException is raised if multiple
        # objects are returned.
        users = list(backend.strategy.storage.user.get_users_by_email(email))
        if len(users) == 0:
            return None
        elif len(users) > 1:
            raise AuthException(
                backend,
                'The given email address is associated with another account'
            )
        else:
            return {'user': users[0],
                    'is_new': False}
Beispiel #5
0
def verify_open(strategy, backend, user=None, **kwargs):
    '''
    Checks whether it is possible to create new user.
    '''

    if not user and not appsettings.REGISTRATION_OPEN:
        raise AuthException(backend, _('New registrations are disabled!'))
Beispiel #6
0
 def openid_request(self, params=None):
     """Return openid request"""
     try:
         return self.consumer().begin(
             url_add_parameters(self.openid_url(), params))
     except DiscoveryFailure as err:
         raise AuthException(self, 'OpenID discovery error: %s' % err)
Beispiel #7
0
    def user_data(self, access_token, response, *args, **kwargs):
        """Loads user data from service"""
        request_data = [
            'first_name', 'last_name', 'screen_name', 'nickname', 'photo'
        ] + self.setting('EXTRA_DATA', [])

        fields = ','.join(set(request_data))
        data = vk_api(
            self, 'users.get', {
                'access_token': access_token,
                'fields': fields,
                'uids': response.get('user_id')
            })

        if data.get('error'):
            error = data['error']
            msg = error.get('error_msg', 'Unknown error')
            if error.get('error_code') == 5:
                raise AuthTokenRevoked(self, msg)
            else:
                raise AuthException(self, msg)

        if data:
            data = data.get('response')[0]
            data['user_photo'] = data.get('photo')  # Backward compatibility
        return data
Beispiel #8
0
 def process_error(self, data):
     if not data:
         raise AuthException(self, 'OpenID relying party endpoint')
     elif data.status == FAILURE:
         raise AuthFailed(self, data.message)
     elif data.status == CANCEL:
         raise AuthCanceled(self)
     elif data.status != SUCCESS:
         raise AuthUnknownError(self, data.status)
Beispiel #9
0
    def base_url(self):
        env = self.setting('ENVIRONMENT', default='production')

        if env == 'staging':
            return 'https://pass-staging.texasgateway.org'
        elif env == 'production':
            return 'https://pass.texasgateway.org'

        raise AuthException(
            'Invalid Trinity environment was found `{env}`, '
            'valid choices are `production` and `staging`.'.format(env=env, ))
Beispiel #10
0
    def auth_complete(self, *args, **kwargs):
        access_token = None
        response = {}

        if 'signed_request' in self.data:
            key, secret = self.get_key_and_secret()
            response = self.load_signed_request(self.data['signed_request'])
            if 'user_id' not in response and 'oauth_token' not in response:
                raise AuthException(self)

            if response is not None:
                access_token = response.get('access_token') or \
                               response.get('oauth_token') or \
                               self.data.get('access_token')

        if access_token is None:
            if self.data.get('error') == 'access_denied':
                raise AuthCanceled(self)
            else:
                raise AuthException(self)
        return self.do_auth(access_token, response, *args, **kwargs)
Beispiel #11
0
def associate_by_email_and_allowed_org(backend,
                                       details,
                                       user=None,
                                       *args,
                                       **kwargs):
    """
    Associate current auth with a user with the same email address in the DB.
    This pipeline entry is not 100% secure unless you know that the providers
    enabled enforce email verification on their side, otherwise a user can
    attempt to take over another user account by using the same (not validated)
    email address on some provider.  This pipeline entry is disabled by
    default.
    """
    if user:
        return None

    email = details.get('email')
    if email:
        # Try to associate accounts registered with the same email address,
        # only if it's a single object. AuthException is raised if multiple
        # objects are returned. The org must have the google oauth 2 preference
        # enabled
        if backend.name == ConfigurableRedirectGoogleOauth2Backend.name:
            backend_pref = 'org__preference_auth_google_oauth2'
        else:
            LOGGER.error(
                'Unconfigured social oauth [%s] backend for mapping user "%s"'
                % (backend.name, email))
            return None

        users = list(backend.strategy.storage.user.user_model().objects.filter(
            username__iexact=email, is_active=True, **{backend_pref: True}))

        if len(users) == 0:
            LOGGER.error('No social user found for backend %s and email %s' %
                         (backend.name, email))
            return None
        elif len(users) > 1:
            LOGGER.error('Multiple users found for backend %s and email %s' %
                         (backend.name, email))
            raise AuthException(
                backend,
                'The given email address is associated with another account')
        else:
            LOGGER.warn(
                'Mapping %s social user %s to internal username %s and pk %s' %
                (backend.name, email, users[0].username, users[0].id))
            return {'user': users[0]}
Beispiel #12
0
 def auth_complete(self, *args, **kwargs):
     """Complete auth process"""
     response = self.consumer().complete(
         dict(self.data.items()),
         self.strategy.absolute_uri(self.redirect_uri))
     if not response:
         raise AuthException(self, 'OpenID relying party endpoint')
     elif response.status == SUCCESS:
         kwargs.update({'response': response, 'backend': self})
         return self.strategy.authenticate(*args, **kwargs)
     elif response.status == FAILURE:
         raise AuthFailed(self, response.message)
     elif response.status == CANCEL:
         raise AuthCanceled(self)
     else:
         raise AuthUnknownError(self, response.status)
Beispiel #13
0
 def auth_complete(self, *args, **kwargs):
     """Completes loging process, must return user instance"""
     logger.debug("auth_complete: %s %s", self.data, kwargs)
     api_key = self.data.get('api_key')
     if not api_key:
         raise AuthMissingParameter(self, 'api_key')
     django_user = kwargs.get('user')
     if not django_user:
         raise AuthException(
             self, 'Could not get authenticated user, please login first')
     user_data = {
         'username': django_user.username,
         'email': django_user.email,
         'name': django_user.first_name + ' ' + django_user.last_name,
         'api_key': api_key.strip()
     }
     kwargs.update({'response': user_data, 'backend': self})
     return self.strategy.authenticate(*args, **kwargs)
Beispiel #14
0
def initialize_engine_object(engine, endpoint, apikey=None, username=None, password=None, request=None):
    """
    Initialize a DatasetEngine object from a string that points at the engine class.
    """
    # Constants
    HYDROSHARE_OAUTH_PROVIDER_NAME = 'hydroshare'

    # Derive import parts from engine string
    engine_split = engine.split('.')
    module_string = '.'.join(engine_split[:-1])
    engine_class_string = engine_split[-1]

    # Import
    module = __import__(module_string, fromlist=[engine_class_string])
    EngineClass = getattr(module, engine_class_string)

    # Get Token for HydroShare interactions
    if EngineClass is HydroShareDatasetEngine:
        user = request.user

        try:
            # social = user.social_auth.get(provider='google-oauth2')
            social = user.social_auth.get(provider=HYDROSHARE_OAUTH_PROVIDER_NAME)
            apikey = social.extra_data['access_token']
        except ObjectDoesNotExist:
            # User is not associated with that provider
            # Need to prompt for association
            raise AuthException("HydroShare authentication required. To automate the authentication prompt decorate "
                                "your controller function with the @ensure_oauth('hydroshare') decorator.")
        except AttributeError:
            # Anonymous User...
            raise
        except AuthAlreadyAssociated:
            raise
        except:
            raise

    # Create Engine Object
    engine_instance = EngineClass(endpoint=endpoint,
                                  apikey=apikey,
                                  username=username,
                                  password=password)
    return engine_instance
Beispiel #15
0
def complete_login(backend,
                   user,
                   response,
                   details,
                   is_new=False,
                   *args,
                   **kwargs):
    if not user:
        raise AuthException(backend, "The user doesn't exist")

    if is_new and backend.name == "facebook":
        url = 'http://graph.facebook.com/{0}/picture'.format(response['id'])
        try:
            response = request('GET', url, params={'type': 'large'})
            response.raise_for_status()
        except HTTPError:
            pass
        user.photo.save(u'{}.jpg'.format(user.uid),
                        ContentFile(response.content))
        user.save(update_fields=["photo"])
def get_username(strategy, details, user=None, *args, **kwargs):
    if 'username' not in strategy.setting('USER_FIELDS', USER_FIELDS):
        return
    storage = strategy.storage

    if not user:
        email_as_username = strategy.setting('USERNAME_IS_FULL_EMAIL', False)

        # We only use email as username
        if email_as_username and details.get('email'):
            username = details['email']
        else:
            raise AuthException(strategy.backend,
                                'No email given from provider')

        final_username = username

    else:
        final_username = storage.user.get_username(user)
    return {'username': final_username}
Beispiel #17
0
def reject_used_email(backend, details, user=None, *args, **kwargs):
    """
    Used in SOCIAL_AUTH_PIPELINE, this function checks if the user which is about to be
    created uses an email already existing in our system
    (Which breaks the authentication flow as duplicate emails are not allowed).
    """
    if user:
        return None

    email = details.get('email')
    if email:
        # Try to associate accounts registered with the same email address,
        # only if it's a single object. AuthException is raised if multiple
        # objects are returned.
        users = list(backend.strategy.storage.user.get_users_by_email(email))
        if len(users) == 0:
            return None
        else:
            raise AuthException(
                backend,
                'The given email address is associated with another account')
def associate_by_email(backend, details, user=None, *args, **kwargs):
    backend_fullname = backend.__module__ + "." + backend.__class__.__name__
    if not backend_fullname in settings.SOCIALAUTH_PIPELINE_TRUSTED_BACKENDS:
        return None
    if user:
        return None

    email = details.get('email')
    if email:
        # Try to associate accounts registered with the same email address,
        # only if it's a single object. AuthException is raised if multiple
        # objects are returned.
        users = list(backend.strategy.storage.user.get_users_by_email(email))
        if len(users) == 0:
            return None
        elif len(users) > 1:
            raise AuthException(
                backend,
                'The given email address is associated with another account')
        else:
            return {'user': users[0]}
    def get_user_id(self, details, response):
        user_id = super(EmailAuth, self).get_user_id(details, response)

        if user_id and not self.setting('USER_ID_CASE_SENSITIVE', False):
            # Emails shouldn't be case sensitive, lets check if we have a
            # user_id. If yes, try to finde the correct-cased value.

            user_model = self.strategy.storage.user.user_model()

            try:
                user_id = getattr(
                    user_model.objects.get(
                        **{'{0}__iexact'.format(self.ID_KEY): user_id}),
                    self.ID_KEY)
            except user_model.DoesNotExist:
                pass

        if user_id:
            try:
                validate_email(user_id)
            except ValidationError as ex:
                raise AuthException(self.strategy.backend, ex.message)

        return user_id
Beispiel #20
0
    def auth_complete(self, *args, **kwargs):
        django_user = kwargs.get('user')
        if not django_user:
            raise AuthException(
                self, 'Could not get authenticated user, please login first')
        jira_server = self.data.get('jira_server')
        if jira_server:
            logger.debug("Starting Jira Oauth flow for user %s",
                         django_user.username)
            request_token_url = '{}/plugins/servlet/oauth/request-token'.format(
                jira_server)
            consumer_key = self.data.get('consumer_key')
            ua = UserAttributes.objects.get(user=django_user)
            ua.jira_server = jira_server
            ua.jira_consumer_key = consumer_key
            oauth = OAuth1Session(consumer_key,
                                  signature_type='auth_header',
                                  signature_method=SIGNATURE_RSA,
                                  rsa_key=self.read_key())
            request_token = oauth.fetch_request_token(request_token_url)
            logger.debug("Request token is: %s", request_token)
            authorize_url = '{}/plugins/servlet/oauth/authorize?oauth_token={}'.format(
                jira_server, request_token['oauth_token'])
            ua.jira_oauth_verifier = request_token['oauth_token_secret']
            ua.jira_oauth_token = request_token['oauth_token']
            ua.save()
            logger.debug("Authorize url is: %s", authorize_url)
            return self.strategy.redirect(authorize_url)
        else:
            # assume redirect from JIRA server
            logger.debug("Completing Jira OAuth flow for user %s",
                         django_user.username)

            ua = UserAttributes.objects.get(user=django_user)
            oauth = OAuth1Session(client_key=ua.jira_consumer_key,
                                  signature_type='auth_header',
                                  signature_method=SIGNATURE_RSA,
                                  rsa_key=self.read_key(),
                                  verifier=ua.jira_oauth_verifier)
            access_token_url = '{}/plugins/servlet/oauth/access-token?oauth_token={}'.format(
                ua.jira_server, ua.jira_oauth_token)
            access_token = oauth.fetch_access_token(access_token_url)
            logger.debug("Access token=%s", access_token)
            user_data = {
                'username':
                django_user.username,
                'email':
                django_user.email,
                'name':
                django_user.first_name + ' ' + django_user.last_name,
                'oauth_token':
                access_token.get('oauth_token'),
                'oauth_expires_in':
                access_token.get('oauth_expires_in'),
                'oauth_authorization_expires_in':
                access_token.get('oauth_authorization_expires_in'),
                'oauth_token_secret':
                access_token.get('oauth_token_secret'),
                'oauth_session_handle':
                access_token.get('oauth_session_handle')
            }
            kwargs.update({'response': user_data, 'backend': self})
            return self.strategy.authenticate(*args, **kwargs)
Beispiel #21
0
 def fake_auth_complete_error(_inst, *_args, **_kwargs):
     """ Mock the backend's auth_complete() method """
     raise AuthException("Mock login failed")
Beispiel #22
0
 def auth_complete(self, *args, **kwargs):
     """Completes login process, must return user instance."""
     if not users.get_current_user():
         raise AuthException('Authentication error')
     kwargs.update({'response': '', 'backend': self})
     return self.strategy.authenticate(*args, **kwargs)
Beispiel #23
0
def validated_user_details(strategy,
                           backend,
                           details,
                           user=None,
                           *args,
                           **kwargs):
    """Merge actions

    Make different merge actions based on user type.
    """
    social = kwargs.get('social')
    email = details.get('email')
    if user and user.groups.filter(name='Temporary').exists():
        if social:
            logout(strategy.request)
            social.user.backend = 'django.contrib.auth.backends.ModelBackend'
            login(strategy.request, social.user)
            union_merge(user, social.user)
            user.delete()
            return {'user': social.user}
        else:
            new_user = None
            if email:
                users = list(
                    backend.strategy.storage.user.get_users_by_email(email))
                if len(users) == 0:
                    pass
                elif len(users) > 1:
                    raise AuthException(
                        backend,
                        'The given email address is associated with another account'
                    )
                else:
                    new_user = users[0]
            if not new_user:
                try:
                    user.username = details.get('username')
                    user.first_name = ''
                    user.save()
                except IntegrityError:
                    _id = int(time.mktime(datetime.now().timetuple()))
                    user.username = details.get('username') + str(_id)
                    user.save()
            else:
                logout(strategy.request)
                new_user.backend = 'django.contrib.auth.backends.ModelBackend'
                login(strategy.request, new_user)
                union_merge(user, new_user)
                user.delete()
                return {'user': new_user}
    elif user and social and social.user != user:
        confirm = strategy.request.POST.get('confirm')
        if confirm and confirm == 'no':
            raise AuthException(backend, 'You interrupted merge process.')
        elif (not user.get_full_name() == social.user.get_full_name()
              and not strategy.request.POST.get('confirm')
              and not user.email == social.user.email):
            return render_to_response(
                'ct/person.html', {
                    'available_backends':
                    load_backends(settings.AUTHENTICATION_BACKENDS),
                    'request':
                    strategy.request,
                    'next':
                    strategy.request.POST.get('next') or '',
                    'target_name':
                    social.user.get_full_name(),
                    'own_name':
                    user.get_full_name(),
                    'person':
                    user,
                    'merge_confirm':
                    True
                }, RequestContext(strategy.request))
        elif (user.get_full_name() == social.user.get_full_name()
              or confirm and confirm == 'yes'
              or user.email == social.user.email):
            union_merge(social.user, user)
            social_merge(social.user, user)
            social.user.delete()
            social.user = user
            return {'user': user, 'social': social}
Beispiel #24
0
class AuthExceptionTest(BaseExceptionTestCase):
    exception = AuthException('foobar', 'message')
    expected_message = 'message'