How to use the timesketch.models.user.User function in timesketch

To help you get started, we’ve selected a few timesketch examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github google / timesketch / timesketch / lib / testlib.py View on Github external
def _create_user(self, username, set_password=False):
        """Create a user in the database.

        Args:
            username: Username (string)
            set_password: Boolean value to decide if a password should be set
        Returns:
            A user (instance of timesketch.models.user.User)
        """
        user = User.get_or_create(username=username)
        if set_password:
            user.set_password(plaintext='test', rounds=4)
        self._commit_to_database(user)
        return user
github google / timesketch / tsctl.py View on Github external
def run(self, name, index, username):
        """Create the SearchIndex."""
        es = ElasticSearchDataStore(
            host=current_app.config['ELASTIC_HOST'],
            port=current_app.config['ELASTIC_PORT'])
        user = User.query.filter_by(username=username).first()
        if not user:
            sys.stderr.write('User does not exist\n')
            sys.exit(1)
        if not es.client.indices.exists(index=index):
            sys.stderr.write('Index does not exist in the datastore\n')
            sys.exit(1)
        if SearchIndex.query.filter_by(name=name, index_name=index).first():
            sys.stderr.write(
                'Index with this name already exist in Timesketch\n')
            sys.exit(1)
        searchindex = SearchIndex(
            name=name, description=name, user=user, index_name=index)
        searchindex.grant_permission(None, 'read')
        db_session.add(searchindex)
        db_session.commit()
        sys.stdout.write('Search index {0:s} created\n'.format(name))
github google / timesketch / timesketch / tsctl.py View on Github external
except IOError as e:
                sys.stdout.write('Unable to open file: {0!s}\n'.format(e))
                sys.exit(1)

            for search_template in search_templates:
                name = search_template['name']
                query_string = search_template['query_string']
                query_dsl = search_template['query_dsl']

                # Skip search template if already exits.
                if SearchTemplate.query.filter_by(name=name).first():
                    continue

                imported_template = SearchTemplate(
                    name=name,
                    user=User(None),
                    query_string=query_string,
                    query_dsl=query_dsl)

                # Add supported_os labels.
                for supported_os in search_template['supported_os']:
                    label_name = 'supported_os:{0:s}'.format(supported_os)
                    label = SearchTemplate.Label.get_or_create(
                        label=label_name, user=None)
                    imported_template.labels.append(label)

                # Set flag to identify local vs import templates.
                remote_flag = SearchTemplate.Label.get_or_create(
                    label='remote_template', user=None)
                imported_template.labels.append(remote_flag)

                db_session.add(imported_template)
github google / timesketch / timesketch / tsctl.py View on Github external
def run(self, username, password):
        """Creates the user."""
        if not password:
            password = self.get_password_from_prompt()
        if not isinstance(password, six.text_type):
            password = codecs.decode(password, 'utf-8')
        if not isinstance(username, six.text_type):
            username = codecs.decode(username, 'utf-8')
        user = User.get_or_create(username=username)
        user.set_password(plaintext=password)
        db_session.add(user)
        db_session.commit()
        sys.stdout.write('User {0:s} created/updated\n'.format(username))
github google / timesketch / tsctl.py View on Github external
def run(self, username, password):
        """Creates the user."""
        if not password:
            password = self.get_password_from_prompt()
        user = User(username=username, name=username)
        user.set_password(plaintext=password)
        try:
            db_session.add(user)
            db_session.commit()
            sys.stdout.write('User {0:s} created\n'.format(username))
        except IntegrityError:
            sys.stderr.write(
                'The username ({0:s}) is already taken, '
                'try another one.\n'.format(username))
github google / timesketch / timesketch / views / auth.py View on Github external
validated_jwt = validate_jwt(
            encoded_jwt, public_key, algorithm, expected_audience,
            expected_issuer, expected_domain)
    except (JwtValidationError, JwtKeyError) as e:
        current_app.logger.error('{}'.format(e))
        return abort(HTTP_STATUS_CODE_UNAUTHORIZED)

    validated_email = validated_jwt.get('email')
    user_whitelist = current_app.config.get('GOOGLE_OIDC_USER_WHITELIST')

    # Check if the authenticating user is on the whitelist.
    if user_whitelist:
        if validated_email not in user_whitelist:
            return abort(HTTP_STATUS_CODE_UNAUTHORIZED)

    user = User.get_or_create(username=validated_email, name=validated_email)
    login_user(user)

    # Log the user in and setup the session.
    if current_user.is_authenticated:
        return redirect(request.args.get('next') or '/')

    return abort(HTTP_STATUS_CODE_BAD_REQUEST)
github google / timesketch / timesketch / lib / tasks.py View on Github external
if not analyzer_names:
        analyzer_names = current_app.config.get('AUTO_SKETCH_ANALYZERS', [])
        if not analyzer_kwargs:
            analyzer_kwargs = current_app.config.get(
                'AUTO_SKETCH_ANALYZERS_KWARGS', {})

    # Exit early if no sketch analyzers are configured to run.
    if not analyzer_names:
        return None

    if not analyzer_kwargs:
        analyzer_kwargs = current_app.config.get('ANALYZERS_DEFAULT_KWARGS', {})

    if user_id:
        user = User.query.get(user_id)
    else:
        user = None

    sketch = Sketch.query.get(sketch_id)
    analysis_session = AnalysisSession(user, sketch)

    analyzers = manager.AnalysisManager.get_analyzers(analyzer_names)
    for analyzer_name, analyzer_cls in analyzers:
        if not analyzer_cls.IS_SKETCH_ANALYZER:
            continue

        kwargs = analyzer_kwargs.get(analyzer_name, {})
        searchindex = SearchIndex.query.get(searchindex_id)
        timeline = Timeline.query.filter_by(
            sketch=sketch, searchindex=searchindex).first()
github google / timesketch / timesketch / views / auth.py View on Github external
if current_app.config.get('GOOGLE_IAP_ENABLED', False):
        encoded_jwt = request.environ.get(
            'HTTP_X_GOOG_IAP_JWT_ASSERTION', None)
        if encoded_jwt:
            expected_audience = current_app.config.get('GOOGLE_IAP_AUDIENCE')
            expected_issuer = current_app.config.get('GOOGLE_IAP_ISSUER')
            algorithm = current_app.config.get('GOOGLE_IAP_ALGORITHM')
            url = current_app.config.get('GOOGLE_IAP_PUBLIC_KEY_URL')
            try:
                public_key = get_public_key_for_jwt(encoded_jwt, url)
                validated_jwt = validate_jwt(
                    encoded_jwt, public_key, algorithm, expected_audience,
                    expected_issuer)
                email = validated_jwt.get('email')
                if email:
                    user = User.get_or_create(username=email, name=email)
                    login_user(user)

            except (ImportError, NameError, UnboundLocalError):  # pylint: disable=try-except-raise
                raise

            except (JwtValidationError, JwtKeyError, Exception) as e:  # pylint: disable=broad-except
                current_app.logger.error('{}'.format(e))

    # SSO login based on environment variable, e.g. REMOTE_USER.
    if current_app.config.get('SSO_ENABLED', False):
        remote_user_env = current_app.config.get('SSO_USER_ENV_VARIABLE',
                                                 'REMOTE_USER')
        sso_group_env = current_app.config.get('SSO_GROUP_ENV_VARIABLE', None)

        remote_user = request.environ.get(remote_user_env, None)
        if remote_user:
github log2timeline / plaso / plaso / output / timesketch_out.py View on Github external
}
        }
    }

    # Get Elasticsearch host and port from Timesketch configuration.
    with self._timesketch.app_context():
      self._host = current_app.config['ELASTIC_HOST']
      self._port = current_app.config['ELASTIC_PORT']

    self._Connect()

    self._CreateIndexIfNotExists(self._index_name, mappings)

    user = None
    if self._timeline_owner:
      user = timesketch_user.User.query.filter_by(
          username=self._timeline_owner).first()
      if not user:
        raise RuntimeError(
            'Unknown Timesketch user: {0:s}'.format(self._timeline_owner))
    else:
      logger.warning('Timeline will be visible to all Timesketch users')

    with self._timesketch.app_context():
      search_index = timesketch_sketch.SearchIndex.get_or_create(
          name=self._timeline_name, description=self._timeline_name, user=user,
          index_name=self._index_name)

      # Grant the user read permission on the mapping object and set status.
      # If user is None the timeline becomes visible to all users.
      search_index.grant_permission(user=user, permission='read')
github google / timesketch / timesketch / models / user.py View on Github external
def __init__(self, username, name=None):
        """Initialize the User object.

        Args:
            username: Username for the user
            name: Name of the user
        """
        super(User, self).__init__()
        self.username = username
        self.name = name
        if not name:
            self.name = username