Ejemplo n.º 1
0
def action_logger(user, action, repo, ipaddr='', sa=None, commit=False):
    """
    Action logger for various actions made by users

    :param user: user that made this action, can be a unique username string or
        object containing user_id attribute
    :param action: action to log, should be on of predefined unique actions for
        easy translations
    :param repo: string name of repository or object containing repo_id,
        that action was made on
    :param ipaddr: optional ip address from what the action was made
    :param sa: optional sqlalchemy session

    """

    if not sa:
        sa = meta.Session()
    # if we don't get explicit IP address try to get one from registered user
    # in tmpl context var
    if not ipaddr:
        ipaddr = getattr(get_current_rhodecode_user(), 'ip_addr', '')

    try:
        if getattr(user, 'user_id', None):
            user_obj = User.get(user.user_id)
        elif isinstance(user, basestring):
            user_obj = User.get_by_username(user)
        else:
            raise Exception('You have to provide a user object or a username')

        if getattr(repo, 'repo_id', None):
            repo_obj = Repository.get(repo.repo_id)
            repo_name = repo_obj.repo_name
        elif isinstance(repo, basestring):
            repo_name = repo.lstrip('/')
            repo_obj = Repository.get_by_repo_name(repo_name)
        else:
            repo_obj = None
            repo_name = ''

        user_log = UserLog()
        user_log.user_id = user_obj.user_id
        user_log.username = user_obj.username
        action = safe_unicode(action)
        user_log.action = action[:1200000]

        user_log.repository = repo_obj
        user_log.repository_name = repo_name

        user_log.action_date = datetime.datetime.now()
        user_log.user_ip = ipaddr
        sa.add(user_log)

        log.info('Logging action:`%s` on repo:`%s` by user:%s ip:%s', action,
                 safe_unicode(repo), user_obj, ipaddr)
        if commit:
            sa.commit()
    except Exception:
        log.error(traceback.format_exc())
        raise
Ejemplo n.º 2
0
def action_logger(user, action, repo, ipaddr='', sa=None, commit=False):
    """
    Action logger for various actions made by users

    :param user: user that made this action, can be a unique username string or
        object containing user_id attribute
    :param action: action to log, should be on of predefined unique actions for
        easy translations
    :param repo: string name of repository or object containing repo_id,
        that action was made on
    :param ipaddr: optional ip address from what the action was made
    :param sa: optional sqlalchemy session

    """

    if not sa:
        sa = meta.Session()
    # if we don't get explicit IP address try to get one from registered user
    # in tmpl context var
    if not ipaddr:
        ipaddr = getattr(get_current_rhodecode_user(), 'ip_addr', '')

    try:
        if hasattr(user, 'user_id'):
            user_obj = User.get(user.user_id)
        elif isinstance(user, basestring):
            user_obj = User.get_by_username(user)
        else:
            raise Exception('You have to provide a user object or a username')

        if hasattr(repo, 'repo_id'):
            repo_obj = Repository.get(repo.repo_id)
            repo_name = repo_obj.repo_name
        elif isinstance(repo, basestring):
            repo_name = repo.lstrip('/')
            repo_obj = Repository.get_by_repo_name(repo_name)
        else:
            repo_obj = None
            repo_name = ''

        user_log = UserLog()
        user_log.user_id = user_obj.user_id
        user_log.username = user_obj.username
        user_log.action = safe_unicode(action)

        user_log.repository = repo_obj
        user_log.repository_name = repo_name

        user_log.action_date = datetime.datetime.now()
        user_log.user_ip = ipaddr
        sa.add(user_log)

        log.info('Logging action:%s on %s by user:%s ip:%s' %
                 (action, safe_unicode(repo), user_obj, ipaddr))
        if commit:
            sa.commit()
    except Exception:
        log.error(traceback.format_exc())
        raise
Ejemplo n.º 3
0
def action_logger(user, action, repo, ipaddr='', sa=None, commit=False):
    """
    Action logger for various actions made by users

    :param user: user that made this action, can be a unique username string or
        object containing user_id attribute
    :param action: action to log, should be on of predefined unique actions for
        easy translations
    :param repo: string name of repository or object containing repo_id,
        that action was made on
    :param ipaddr: optional ip address from what the action was made
    :param sa: optional sqlalchemy session

    """

    if not sa:
        sa = meta.Session

    try:
        if hasattr(user, 'user_id'):
            user_obj = user
        elif isinstance(user, basestring):
            user_obj = User.get_by_username(user)
        else:
            raise Exception('You have to provide user object or username')

        if hasattr(repo, 'repo_id'):
            repo_obj = Repository.get(repo.repo_id)
            repo_name = repo_obj.repo_name
        elif  isinstance(repo, basestring):
            repo_name = repo.lstrip('/')
            repo_obj = Repository.get_by_repo_name(repo_name)
        else:
            raise Exception('You have to provide repository to action logger')

        user_log = UserLog()
        user_log.user_id = user_obj.user_id
        user_log.action = safe_unicode(action)

        user_log.repository_id = repo_obj.repo_id
        user_log.repository_name = repo_name

        user_log.action_date = datetime.datetime.now()
        user_log.user_ip = ipaddr
        sa.add(user_log)

        log.info(
            'Adding user %s, action %s on %s' % (user_obj, action,
                                                 safe_unicode(repo))
        )
        if commit:
            sa.commit()
    except:
        log.error(traceback.format_exc())
        raise
Ejemplo n.º 4
0
    def _get_by_id(self, repo_name):
        """
        Get's a special pattern _<ID> from clone url and tries to replace it
        with a repository_name for support of _<ID> non changable urls

        :param repo_name:
        """
        try:
            data = repo_name.split("/")
            if len(data) >= 2:
                by_id = data[1].split("_")
                if len(by_id) == 2 and by_id[1].isdigit():
                    _repo_name = Repository.get(by_id[1]).repo_name
                    data[1] = _repo_name
        except:
            log.debug("Failed to extract repo_name from id %s" % (traceback.format_exc()))

        return "/".join(data)
Ejemplo n.º 5
0
    def check_repo(environ, match_dict):
        """
        check for valid repository for proper 404 handling

        :param environ:
        :param match_dict:
        """
        from rhodecode.model.db import Repository
        repo_name = match_dict.get('repo_name')

        try:
            by_id = repo_name.split('_')
            if len(by_id) == 2 and by_id[1].isdigit():
                repo_name = Repository.get(by_id[1]).repo_name
                match_dict['repo_name'] = repo_name
        except:
            pass

        return is_valid_repo(repo_name, config['base_path'])
Ejemplo n.º 6
0
    def check_repo(environ, match_dict):
        """
        check for valid repository for proper 404 handling

        :param environ:
        :param match_dict:
        """
        from rhodecode.model.db import Repository
        repo_name = match_dict.get('repo_name')

        try:
            by_id = repo_name.split('_')
            if len(by_id) == 2 and by_id[1].isdigit() and by_id[0] == '':
                repo_name = Repository.get(by_id[1]).repo_name
                match_dict['repo_name'] = repo_name
        except:
            pass

        return is_valid_repo(repo_name, config['base_path'])
Ejemplo n.º 7
0
    def _get_by_id(self, repo_name):
        """
        Get's a special pattern _<ID> from clone url and tries to replace it
        with a repository_name for support of _<ID> non changable urls

        :param repo_name:
        """
        try:
            data = repo_name.split('/')
            if len(data) >= 2:
                by_id = data[1].split('_')
                if len(by_id) == 2 and by_id[1].isdigit():
                    _repo_name = Repository.get(by_id[1]).repo_name
                    data[1] = _repo_name
        except:
            log.debug('Failed to extract repo_name from id %s' % (
                      traceback.format_exc()
                      )
            )

        return '/'.join(data)
Ejemplo n.º 8
0
    def check_repo(environ, match_dict):
        """
        check for valid repository for proper 404 handling

        :param environ:
        :param match_dict:
        """
        from rhodecode.model.db import Repository
        repo_name = match_dict.get('repo_name')

        if match_dict.get('f_path'):
            #fix for multiple initial slashes that causes errors
            match_dict['f_path'] = match_dict['f_path'].lstrip('/')

        try:
            by_id = repo_name.split('_')
            if len(by_id) == 2 and by_id[1].isdigit() and by_id[0] == '':
                repo_name = Repository.get(by_id[1]).repo_name
                match_dict['repo_name'] = repo_name
        except Exception:
            pass

        return is_valid_repo(repo_name, config['base_path'])
Ejemplo n.º 9
0
    def check_repo(environ, match_dict):
        """
        check for valid repository for proper 404 handling

        :param environ:
        :param match_dict:
        """
        from rhodecode.model.db import Repository
        repo_name = match_dict.get('repo_name')

        if match_dict.get('f_path'):
            #fix for multiple initial slashes that causes errors
            match_dict['f_path'] = match_dict['f_path'].lstrip('/')

        try:
            by_id = repo_name.split('_')
            if len(by_id) == 2 and by_id[1].isdigit() and by_id[0] == '':
                repo_name = Repository.get(by_id[1]).repo_name
                match_dict['repo_name'] = repo_name
        except Exception:
            pass

        return is_valid_repo(repo_name, config['base_path'])
Ejemplo n.º 10
0
    def create(self,
               text,
               repo_id,
               user_id,
               revision,
               f_path=None,
               line_no=None):
        """
        Creates new comment for changeset

        :param text:
        :param repo_id:
        :param user_id:
        :param revision:
        :param f_path:
        :param line_no:
        """

        if text:
            repo = Repository.get(repo_id)
            cs = repo.scm_instance.get_changeset(revision)
            desc = "%s - %s" % (cs.short_id, h.shorter(cs.message, 256))
            author_email = cs.author_email
            comment = ChangesetComment()
            comment.repo = repo
            comment.user_id = user_id
            comment.revision = revision
            comment.text = text
            comment.f_path = f_path
            comment.line_no = line_no

            self.sa.add(comment)
            self.sa.flush()
            # make notification
            line = ''
            if line_no:
                line = _('on line %s') % line_no
            subj = safe_unicode(
                h.link_to('Re commit: %(commit_desc)s %(line)s' % \
                          {'commit_desc': desc, 'line': line},
                          h.url('changeset_home', repo_name=repo.repo_name,
                                revision=revision,
                                anchor='comment-%s' % comment.comment_id,
                                qualified=True,
                          )
                )
            )

            body = text

            # get the current participants of this changeset
            recipients = ChangesetComment.get_users(revision=revision)

            # add changeset author if it's in rhodecode system
            recipients += [User.get_by_email(author_email)]

            NotificationModel().create(
                created_by=user_id,
                subject=subj,
                body=body,
                recipients=recipients,
                type_=Notification.TYPE_CHANGESET_COMMENT)

            mention_recipients = set(self._extract_mentions(body))\
                                    .difference(recipients)
            if mention_recipients:
                subj = _('[Mention]') + ' ' + subj
                NotificationModel().create(
                    created_by=user_id,
                    subject=subj,
                    body=body,
                    recipients=mention_recipients,
                    type_=Notification.TYPE_CHANGESET_COMMENT)

            return comment
Ejemplo n.º 11
0
    def create(self, form_data, cur_user, just_db=False, fork=False):
        from rhodecode.model.scm import ScmModel

        try:
            if fork:
                fork_parent_id = form_data['fork_parent_id']

            # repo name is just a name of repository
            # while repo_name_full is a full qualified name that is combined
            # with name and path of group
            repo_name = form_data['repo_name']
            repo_name_full = form_data['repo_name_full']

            new_repo = Repository()
            new_repo.enable_statistics = False

            for k, v in form_data.items():
                if k == 'repo_name':
                    v = repo_name_full
                if k == 'repo_group':
                    k = 'group_id'
                if k == 'description':
                    v = v or repo_name

                setattr(new_repo, k, v)

            if fork:
                parent_repo = Repository.get(fork_parent_id)
                new_repo.fork = parent_repo

            new_repo.user_id = cur_user.user_id
            self.sa.add(new_repo)

            def _create_default_perms():
                # create default permission
                repo_to_perm = UserRepoToPerm()
                default = 'repository.read'
                for p in User.get_by_username('default').user_perms:
                    if p.permission.permission_name.startswith('repository.'):
                        default = p.permission.permission_name
                        break

                default_perm = 'repository.none' if form_data[
                    'private'] else default

                repo_to_perm.permission_id = self.sa.query(Permission)\
                        .filter(Permission.permission_name == default_perm)\
                        .one().permission_id

                repo_to_perm.repository = new_repo
                repo_to_perm.user_id = User.get_by_username('default').user_id

                self.sa.add(repo_to_perm)

            if fork:
                if form_data.get('copy_permissions'):
                    repo = Repository.get(fork_parent_id)
                    user_perms = UserRepoToPerm.query()\
                        .filter(UserRepoToPerm.repository == repo).all()
                    group_perms = UsersGroupRepoToPerm.query()\
                        .filter(UsersGroupRepoToPerm.repository == repo).all()

                    for perm in user_perms:
                        UserRepoToPerm.create(perm.user, new_repo,
                                              perm.permission)

                    for perm in group_perms:
                        UsersGroupRepoToPerm.create(perm.users_group, new_repo,
                                                    perm.permission)
                else:
                    _create_default_perms()
            else:
                _create_default_perms()

            if not just_db:
                self.__create_repo(repo_name, form_data['repo_type'],
                                   form_data['repo_group'],
                                   form_data['clone_uri'])
                log_create_repository(new_repo.get_dict(),
                                      created_by=cur_user.username)

            # now automatically start following this repository as owner
            ScmModel(self.sa).toggle_following_repo(new_repo.repo_id,
                                                    cur_user.user_id)
            return new_repo
        except:
            log.error(traceback.format_exc())
            raise
Ejemplo n.º 12
0
    def create(self, form_data, cur_user, just_db=False, fork=False):
        from rhodecode.model.scm import ScmModel

        try:
            if fork:
                fork_parent_id = form_data["fork_parent_id"]

            # repo name is just a name of repository
            # while repo_name_full is a full qualified name that is combined
            # with name and path of group
            repo_name = form_data["repo_name"]
            repo_name_full = form_data["repo_name_full"]

            new_repo = Repository()
            new_repo.enable_statistics = False

            for k, v in form_data.items():
                if k == "repo_name":
                    v = repo_name_full
                if k == "repo_group":
                    k = "group_id"
                if k == "description":
                    v = v or repo_name

                setattr(new_repo, k, v)

            if fork:
                parent_repo = Repository.get(fork_parent_id)
                new_repo.fork = parent_repo

            new_repo.user_id = cur_user.user_id
            self.sa.add(new_repo)

            def _create_default_perms():
                # create default permission
                repo_to_perm = UserRepoToPerm()
                default = "repository.read"
                for p in User.get_by_username("default").user_perms:
                    if p.permission.permission_name.startswith("repository."):
                        default = p.permission.permission_name
                        break

                default_perm = "repository.none" if form_data["private"] else default

                repo_to_perm.permission_id = (
                    self.sa.query(Permission).filter(Permission.permission_name == default_perm).one().permission_id
                )

                repo_to_perm.repository = new_repo
                repo_to_perm.user_id = User.get_by_username("default").user_id

                self.sa.add(repo_to_perm)

            if fork:
                if form_data.get("copy_permissions"):
                    repo = Repository.get(fork_parent_id)
                    user_perms = UserRepoToPerm.query().filter(UserRepoToPerm.repository == repo).all()
                    group_perms = UsersGroupRepoToPerm.query().filter(UsersGroupRepoToPerm.repository == repo).all()

                    for perm in user_perms:
                        UserRepoToPerm.create(perm.user, new_repo, perm.permission)

                    for perm in group_perms:
                        UsersGroupRepoToPerm.create(perm.users_group, new_repo, perm.permission)
                else:
                    _create_default_perms()
            else:
                _create_default_perms()

            if not just_db:
                self.__create_repo(repo_name, form_data["repo_type"], form_data["repo_group"], form_data["clone_uri"])
                log_create_repository(new_repo.get_dict(), created_by=cur_user.username)

            # now automatically start following this repository as owner
            ScmModel(self.sa).toggle_following_repo(new_repo.repo_id, cur_user.user_id)
            return new_repo
        except:
            log.error(traceback.format_exc())
            raise
Ejemplo n.º 13
0
    def create(self, text, repo_id, user_id, revision, f_path=None,
               line_no=None):
        """
        Creates new comment for changeset

        :param text:
        :param repo_id:
        :param user_id:
        :param revision:
        :param f_path:
        :param line_no:
        """

        if text:
            repo = Repository.get(repo_id)
            cs = repo.scm_instance.get_changeset(revision)
            desc = "%s - %s" % (cs.short_id, h.shorter(cs.message, 256))
            author_email = cs.author_email
            comment = ChangesetComment()
            comment.repo = repo
            comment.user_id = user_id
            comment.revision = revision
            comment.text = text
            comment.f_path = f_path
            comment.line_no = line_no

            self.sa.add(comment)
            self.sa.flush()
            # make notification
            line = ''
            if line_no:
                line = _('on line %s') % line_no
            subj = safe_unicode(
                h.link_to('Re commit: %(commit_desc)s %(line)s' % \
                          {'commit_desc': desc, 'line': line},
                          h.url('changeset_home', repo_name=repo.repo_name,
                                revision=revision,
                                anchor='comment-%s' % comment.comment_id,
                                qualified=True,
                          )
                )
            )

            body = text

            # get the current participants of this changeset
            recipients = ChangesetComment.get_users(revision=revision)

            # add changeset author if it's in rhodecode system
            recipients += [User.get_by_email(author_email)]

            NotificationModel().create(
              created_by=user_id, subject=subj, body=body,
              recipients=recipients, type_=Notification.TYPE_CHANGESET_COMMENT
            )

            mention_recipients = set(self._extract_mentions(body))\
                                    .difference(recipients)
            if mention_recipients:
                subj = _('[Mention]') + ' ' + subj
                NotificationModel().create(
                    created_by=user_id, subject=subj, body=body,
                    recipients=mention_recipients,
                    type_=Notification.TYPE_CHANGESET_COMMENT
                )

            return comment