Example #1
0
    def authenticate(self, environ, identity):
        if not ('login' in identity and 'password' in identity):
            return None

        login = identity['login']
        user = User.by_name(login)

        ## HDX HACK ##
        if user is None:
            users = User.by_email(login)
            try:
                user = users[0]
            except:
                user = None
        ## END HDX HACK ##

        if user is None:
            log.debug('Login failed - username %r not found', login)
        elif not user.is_active():
            log.debug('Login as %r failed - user isn\'t active', login)
        elif not user.validate_password(identity['password']):
            log.debug('Login as %r failed - password not valid', login)
        else:
            return user.name

        return None
Example #2
0
    def authenticate(self, environ, identity):
        if not ('login' in identity and 'password' in identity):
            return None

        login = identity['login']
        user = User.by_name(login)

        is_email = plugins.toolkit.config.get('ckan.authenticator.email', '').strip().lower() == 'true'

        if user is None and is_email:
            users = User.by_email(login)
            try:
                user = users[0]
            except:
                user = None

        if user is None:
            log.debug('Login failed - {} not found'.format(login))
        elif not user.is_active():
            log.debug('Login as {} failed - user isn\'t active'.format(login))
        elif not user.validate_password(identity['password']):
            log.debug('Login as {} failed - password not valid'.format(login))
        else:
            return user.name

        return None
Example #3
0
    def authenticate(self, environ, identity):
        if not ('login' in identity and 'password' in identity):
            return None

        login = identity['login']
        user = User.by_name(login)

        if user is None:
            log.debug('Login failed - username %r not found', login)
        elif not user.is_active():
            log.debug('Login as %r failed - user isn\'t active', login)
        elif not user.validate_password(identity['password']):
            log.debug('Login as %r failed - password not valid', login)
        else:
            msg = h.get_billing_api("api/RegisterAndSession/login",
                                    request_type='post',
                                    ckan_user_id=user.id,
                                    ckan_user_name=user.name,
                                    role=authz.is_sysadmin(login))
            decoded = json.loads(msg)
            if decoded['msg'] == 'error':
                log.debug(
                    'Login as %r failed - Create the login session failed',
                    login)
            elif decoded['msg'] == 'success':
                return user.name
            else:
                return user.name
                log.debug(
                    'Login as %r failed - api/RegisterAndSession/login return wrong data',
                    login)
        return None
Example #4
0
    def authenticate(self, environ, identity):
        if not ('login' in identity and 'password' in identity):
            return None

        login = identity['login']
        user = User.by_name(login)

        ## HDX HACK ##
        if user is None:
            users = User.by_email(login)
            try:
                user = users[0]
            except:
                user = None
        ## END HDX HACK ##

        if user is None:
            log.debug('Login failed - username %r not found', login)
        elif not user.is_active():
            log.debug('Login as %r failed - user isn\'t active', login)
        elif not user.validate_password(identity['password']):
            log.debug('Login as %r failed - password not valid', login)
        else:
            return user.name

        return None
Example #5
0
def inventory_resource_show(context, data_dict):
    model = context['model']
    user = User.by_name(context.get('user'))
    resource = get_resource_object(context, data_dict)

    # check authentication against package
    pkg = model.Package.get(resource.package_id)
    if not pkg:
        raise logic.NotFound(
            _('No package found for this resource,'
              ' cannot check auth.'))

    if user is None:
        if pkg.private:
            return {'success': False}
        else:
            return {'success': True}
    else:
        pkg_dict = {'id': pkg.id}
        authorized = authz.is_authorized('package_show', context, pkg_dict) \
            .get('success')

        if not authorized:
            return {
                'success':
                False,
                'msg':
                _('User %s not authorized to read resource %s') %
                (user, resource.id)
            }
        else:
            return {'success': True}
    def authenticate(self, environ, identity):
        """ Mimic most of UsernamePasswordAuthenticator.authenticate
        but add account lockout after 10 failed attempts.
        """
        if 'login' not in identity or 'password' not in identity:
            return None
        user = User.by_name(identity.get('login'))
        if user is None:
            LOG.debug('Login failed - username %r not found',
                      identity.get('login'))
            return None

        qgov_user = Session.query(QGOVUser).filter_by(
            name=identity.get('login')).first()
        if qgov_user.login_attempts >= 10:
            LOG.debug('Login as %r failed - account is locked',
                      identity.get('login'))
        elif user.validate_password(identity.get('password')):
            # reset attempt count to 0
            qgov_user.login_attempts = 0
            Session.commit()
            return user.name
        else:
            LOG.debug('Login as %r failed - password not valid',
                      identity.get('login'))

        qgov_user.login_attempts += 1
        Session.commit()
        return None
    def authenticate(self, environ, identity):
        """ Mimic most of UsernamePasswordAuthenticator.authenticate
        but add account lockout after 10 failed attempts.
        """
        if 'login' not in identity or 'password' not in identity:
            return None
        login_name = identity.get('login')
        user = User.by_name(login_name)
        if user is None:
            LOG.debug('Login failed - username %r not found', login_name)
            return None

        cache_key = '{}.ckanext.qgov.login_attempts.{}'.format(
            g.site_id, login_name)
        redis_conn = connect_to_redis()
        try:
            login_attempts = int(redis_conn.get(cache_key) or 0)
        except ValueError:
            # shouldn't happen but let's play it safe
            login_attempts = 0

        if login_attempts >= 10:
            LOG.debug('Login as %r failed - account is locked', login_name)
        elif user.validate_password(identity.get('password')):
            if login_attempts > 0:
                LOG.debug("Clearing failed login attempts for %s", login_name)
                # reset attempt count to 0
                redis_conn.delete(cache_key)
            return user.name
        else:
            LOG.debug('Login as %r failed - password not valid', login_name)

        redis_conn.set(cache_key, login_attempts + 1, ex=LOGIN_THROTTLE_EXPIRY)
        return None
Example #8
0
    def authenticate(self, environ, identity):
        '''
        Authenticate and extract identity from OAuth2 tokens
        '''
        request = Request(environ)
        log.debug('Repoze OAuth authenticate')
        if 'oauth2.token' in identity:
            oauth = OAuth2Session(
                self.client_id,
                token=identity['oauth2.token'])
            profile_response = oauth.get(self.profile_api_url)
            profile_data = profile_response.json()
            if not profile_data['authenticated']:
                return None

            user_data = profile_data['principal']

            user = User.by_name(user_data['username'])

            if user is None:
                user = User()
                user.name = user_data['username']
                user.email = user_data['email']
                user.fullname = u"{} {}".format(
                    user_data['name'], user_data['surname'])
                user.save()
                user.activate()
                user.save()

            identity.update({'repoze.who.userid': user.name})
            self._redirect_from_callback(request, identity)
            return user.name

        return None
    def authenticate(self, environ, identity):
        if not 'login' in identity or not 'password' in identity:
            return None
        user = User.by_name(identity.get('login'))
        if user is None:
            log.debug('Login failed - username %r not found',
                      identity.get('login'))
            return None

        seedUser = Session.query(SEEDUser).filter_by(
            name=identity.get('login')).first()
        if seedUser.login_attempts >= 10:
            log.debug('Login as %r failed - account is locked',
                      identity.get('login'))
        elif user.validate_password(identity.get('password')):
            # reset attempt count to 0
            seedUser.login_attempts = 0
            Session.commit()
            return user.name
        else:
            log.debug('Login as %r failed - password not valid',
                      identity.get('login'))

        seedUser.login_attempts += 1
        Session.commit()
        return None
Example #10
0
    def authenticate(self, environ, identity):

        request = Request(environ)
        if request.method == 'POST':
            came_from = request.params.get('came_from')
            if came_from == "/user/logged_in":
                if not custom_captcha.check_recaptcha(request):
                    log.debug('Bad Captcha error')
                    return None

        if not ('login' in identity and 'password' in identity):
            return None

        login = identity['login']
        user = User.by_name(login)

        if user is None:
            log.debug('Login failed - username %r not found', login)
        elif not user.is_active():
            log.debug('Login as %r failed - user isn\'t active', login)
        elif not user.validate_password(identity['password']):
            log.debug('Login as %r failed - password not valid', login)
        else:
            return user.name

        return None
Example #11
0
def get_user(openid):
    username = get_username(openid)
    user = User.by_name(username)
    if user:
        user_dict = toolkit.get_action('user_show')(data_dict={'id': user.id})
        return user_dict
    else:
        return None
Example #12
0
 def authenticate(self, environ, identity):
     if not 'login' in identity or not 'password' in identity:
         return None
     user = User.by_name(identity.get('login'))
     if user is None: 
         return None
     if user.validate_password(identity.get('password')):
         return user.name
     return None
Example #13
0
    def get_ckanuser(self, user):
        user_ckan = User.by_name(user)

        if user_ckan:
            user_dict = toolkit.get_action('user_show')(data_dict={
                'id': user_ckan.id
            })
            return user_dict
        else:
            return None
Example #14
0
 def authenticate(self, environ, identity):
     '''Fetch the user given its username in identity'''
     if 'username' in identity:
         user = User.by_name(identity['username'])
         if user is None:
             return None
         else:
             identity.update({'repoze.who.userid': user.name})
             return user.name
     return None
Example #15
0
 def test_authenticate_step_two(self):
     plugin = self._makeOne()
     environ = {"REQUEST_METHOD": "GET", "QUERY_STRING": "oauth_token=foo", "ckan.who.oauth.challenge": "1"}
     identity = plugin.identify(environ)
     username = identity.get("repoze.who.userid")
     self.assertEqual(username, "boz")
     user = User.by_name("boz")
     self.assertEqual(user.email, "*****@*****.**")
     groups = Session.query(AuthorizationGroup).filter(AuthorizationGroup.users.contains(user))
     self.assertEqual(groups.count(), 1)
Example #16
0
 def authenticate(self, environ, identity):
     if not 'login' in identity or not 'password' in identity:
         return None
     user = User.by_name(identity.get('login'))
     if user is None:
         log.debug('Login failed - username %r not found', identity.get('login'))
         return None
     if user.validate_password(identity.get('password')):
         return user.name
     log.debug('Login as %r failed - password not valid', identity.get('login'))
     return None
Example #17
0
 def authenticate(self, environ, identity):
     if not 'login' in identity or not 'password' in identity:
         return None
     user = User.by_name(identity.get('login'))
     if user is None:
         log.debug('Login failed - username %r not found',
                   identity.get('login'))
         return None
     if user.validate_password(identity.get('password')):
         return user.name
     log.debug('Login as %r failed - password not valid',
               identity.get('login'))
     return None
Example #18
0
def login_handler():
    '''Action called when login in via the LDAP login form'''
    params = toolkit.request.values
    came_from = params.get(u'came_from', None)
    if u'login' in params and u'password' in params:
        login = params[u'login']
        password = params[u'password']
        try:
            ldap_user_dict = find_ldap_user(login)
        except MultipleMatchError as e:
            # Multiple users match. Inform the user and try again.
            return _helpers.login_failed(notice=str(e))
        if ldap_user_dict and _helpers.check_ldap_password(
                ldap_user_dict[u'cn'], password):
            try:
                user_name = _helpers.get_or_create_ldap_user(ldap_user_dict)
            except UserConflictError as e:
                return _helpers.login_failed(error=str(e))
            return _helpers.login_success(user_name, came_from=came_from)
        elif ldap_user_dict:
            # There is an LDAP user, but the auth is wrong. There could be a
            # CKAN user of the same name if the LDAP user had been created
            # later - in which case we have a conflict we can't solve.
            if toolkit.config[u'ckanext.ldap.ckan_fallback']:
                exists = _helpers.ckan_user_exists(login)
                if exists[u'exists'] and not exists[u'is_ldap']:
                    return _helpers.login_failed(error=toolkit._(
                        u'Username conflict. Please contact the site administrator.'
                    ))
            return _helpers.login_failed(
                error=toolkit._(u'Bad username or password.'))
        elif toolkit.config[u'ckanext.ldap.ckan_fallback']:
            # No LDAP user match, see if we have a CKAN user match
            try:
                user_dict = _helpers.get_user_dict(login)
                # We need the model to validate the password
                user = User.by_name(user_dict[u'name'])
            except toolkit.ObjectNotFound:
                user = None
            if user and user.validate_password(password):
                return _helpers.login_success(user.name, came_from=came_from)
            else:
                return _helpers.login_failed(
                    error=toolkit._(u'Bad username or password.'))
        else:
            return _helpers.login_failed(
                error=toolkit._(u'Bad username or password.'))
    return _helpers.login_failed(
        error=toolkit._(u'Please enter a username and password'))
Example #19
0
def inventory_package_show(context, data_dict):
    model = context['model']
    user = User.by_name(context.get('user'))
    pkg = model.Package.get(data_dict.get('id', None))

    # package_show appears to be needed to download package resources.
    # but we dont want direct package_show call open to anonymous user.
    # only for download url matching /dataset/*/resource/*/download/*
    url_pattern = r"^/dataset/[0-9a-f-]{36}/resource/[0-9a-f-]{36}/download/.*"
    re_pattern = re.compile(url_pattern)
    if user is None:
        if not pkg.private and re_pattern.match(ckan_request.full_path):
            return {'success': True}
        else:
            return {'success': False}
    else:
        return package_show(context, data_dict)
Example #20
0
    def authenticate(self, environ, identity):
        """A username/password authenticator that throttles login request by IP."""
        try:
            login = identity['login']
        except KeyError:
            return None

        environ['paste.registry'].register(pylons.translator, MockTranslator())

        try:
            remote_addr = Request(environ).headers['X-Forwarded-For']
        except KeyError:
            try:
                remote_addr = environ['REMOTE_ADDR']
            except KeyError:
                log.critical(
                    'X-Forwarded-For header/REMOTE_ADDR missing from request.')
                return None

        throttle = LoginThrottle(User.by_name(login), remote_addr)
        if not ('login' in identity and 'password' in identity):
            return None

        # Run through the CKAN auth sequence first, so we can hit the DB
        # in every case and make timing attacks a little more difficult.
        auth_user = super(CKANLoginThrottle,
                          self).authenticate(environ, identity)

        # Check if there is a lock on the requested user, and return None if
        # we have a lock.
        if throttle.check_attempts() is False:
            log.info('User %r (%s) locked out by brute force protection.' %
                     (login, remote_addr))
            throttle.increment(
            )  # Increment so we only send an email the first time around
            return None

        # If the CKAN authenticator as successfully authenticated the request
        # and the user wasn't locked out above, reset the throttle counter and
        # return the user object.
        if auth_user is not None:
            throttle.reset()
            return auth_user

        # Increment the throttle counter if the login failed.
        throttle.increment()
Example #21
0
    def authenticate(self, environ, identity):
        if not ('login' in identity and 'password' in identity):
            return None

        login = identity['login']
        user = User.by_name(login)

        if user is None:
            log.debug('Login failed - username %r not found', login)
        elif not user.is_active():
            log.debug('Login as %r failed - user isn\'t active', login)
        elif not user.validate_password(identity['password']):
            log.debug('Login as %r failed - password not valid', login)
        else:
            signals.successful_login.send(user.name)
            return user.name
        signals.failed_login.send(login)
        return None
Example #22
0
def default_authenticate(identity: 'Mapping[str, Any]') -> Optional["User"]:
    if not ('login' in identity and 'password' in identity):
        return None

    login = identity['login']
    user_obj = User.by_name(login)
    if not user_obj:
        user_obj = User.by_email(login)

    if user_obj is None:
        log.debug('Login failed - username or email %r not found', login)
    elif not user_obj.is_active:
        log.debug('Login as %r failed - user isn\'t active', login)
    elif not user_obj.validate_password(identity['password']):
        log.debug('Login as %r failed - password not valid', login)
    else:
        return user_obj
    signals.failed_login.send(login)
    return None
Example #23
0
 def authenticate(self, environ, identity):
     if 'repoze.who.plugins.openid.userid' in identity:
         openid = identity.get('repoze.who.plugins.openid.userid')
         user = User.by_openid(openid)
         if user is None:
             # TODO: Implement a mask to ask for an alternative user 
             # name instead of just using the OpenID identifier. 
             name = identity.get('repoze.who.plugins.openid.nickname')
             if not User.check_name_available(name):
                 name = openid
             if User.by_name(name):
                 name = openid
             user = User(openid=openid, name=name,
                     fullname=identity.get('repoze.who.plugins.openid.fullname'),
                     email=identity.get('repoze.who.plugins.openid.email'))
             Session.add(user)
             Session.commit()
             Session.remove()
         return user.name
     return None
Example #24
0
 def authenticate(self, environ, identity):
     '''
     Authenticate and extract identity from OAuth2 tokens
     '''
     request = Request(environ)
     log.debug('Repoze OAuth authenticate')
     if 'oauth2.token' in identity:
         oauth = OAuth2Session(self.client_id,
                               token=identity['oauth2.token'])
         profile_response = oauth.get(self.profile_api_url)
         user_data = profile_response.json()
         username = user_data[self.profile_api_user_field]
         user = User.by_name(username)
         if user is None:
             return None
         else:
             identity.update({'repoze.who.userid': user.name})
             self._redirect_from_callback(request, identity)
             return user.name
     return None
Example #25
0
    def authenticate(self, environ, identity):
        if not ('login' in identity and 'password' in identity):
            return None

        login = identity['login']
        user = User.by_name(login)
        if user is None:
            user_accounts = User.by_email(login)
            user = user_accounts[0] if len(user_accounts) > 0 else None

        if user is None:
            log.debug(
                'Login failed - username or email address %r is not associated with an account',
                login)
        elif not user.is_active():
            log.debug('Login as %r failed - user isn\'t active', login)
        elif not user.validate_password(identity['password']):
            log.debug('Login as %r failed - password not valid', login)
        else:
            return user.name

        return None
Example #26
0
    def authenticate(self, environ, identity):
        """A username/password authenticator that throttles login request by user name."""
        try:
            user_name = identity['login']
        except KeyError:
            return None

        environ['paste.registry'].register(pylons.translator, MockTranslator())

        if not ('login' in identity and 'password' in identity):
            return None

        # Run through the CKAN auth sequence first, so we can hit the DB
        # in every case and make timing attacks a little more difficult.
        auth_user_name = super(CKANLoginThrottle,
                               self).authenticate(environ, identity)

        login_throttle_key = get_login_throttle_key(Request(environ),
                                                    user_name)
        if login_throttle_key is None:
            return None

        throttle = LoginThrottle(User.by_name(user_name), login_throttle_key)
        # Check if there is a lock on the requested user, and return None if
        # we have a lock.
        if throttle.is_locked():
            return None

        if auth_user_name is None:
            # Increment the throttle counter if the login failed.
            throttle.increment()

        # if the CKAN authenticator has successfully authenticated the request and the user wasn't locked out above,
        # then check the TOTP parameter to see if it is valid
        if auth_user_name is not None:
            totp_success = self.authenticate_totp(environ, auth_user_name)
            if totp_success:  # if TOTP was successful -- reset the log in throttle
                throttle.reset()
                return totp_success
    def authenticate(self, environ, identity):
        if not 'login' in identity or not 'password' in identity:
            return None
        user = User.by_name(identity.get('login'))
        if user is None:
            log.debug('Login failed - username %r not found', identity.get('login'))
            return None

        qgovUser = Session.query(QGOVUser).filter_by(name = identity.get('login')).first()
        if qgovUser.login_attempts >= 10:
            log.debug('Login as %r failed - account is locked', identity.get('login'))
        elif user.validate_password(identity.get('password')):
            # reset attempt count to 0
            qgovUser.login_attempts = 0
            Session.commit()
            return user.name
        else:
            log.debug('Login as %r failed - password not valid', identity.get('login'))

        qgovUser.login_attempts += 1
        Session.commit()
        return None