示例#1
0
 def to_python(self, value, state):
     try:
         User.query().filter(User.active == True)\
             .filter(User.username == value).one()
     except Exception:
         raise formencode.Invalid(_('This username is not valid'),
                                  value, state)
     return value
示例#2
0
 def validate_python(self, value, state):
     try:
         User.query().filter(User.active == True)\
             .filter(User.username == value).one()
     except Exception:
         msg = M(self, 'invalid_username', state, username=value)
         raise formencode.Invalid(msg, value, state,
             error_dict=dict(username=msg)
         )
def test_account_for_deactivation_generation(test_user):
    accounts = UserModel().get_accounts_in_creation_order(
        current_user=test_user)
    # current user should be #1 in the list
    assert accounts[0] == test_user.user_id
    active_users = User.query().filter(User.active == true()).count()
    assert active_users == len(accounts)
示例#4
0
    def edit(self, id, format='html'):
        """GET /users_groups/id/edit: Form to edit an existing item"""
        # url('edit_users_group', id=ID)

        c.users_group = UsersGroup.get_or_404(id)

        c.users_group.permissions = {}
        c.group_members_obj = [x.user for x in c.users_group.members]
        c.group_members = [(x.user_id, x.username) for x in
                           c.group_members_obj]
        c.available_members = [(x.user_id, x.username) for x in
                               User.query().all()]
        ug_model = UsersGroupModel()
        defaults = c.users_group.get_dict()
        defaults.update({
            'create_repo_perm': ug_model.has_perm(c.users_group,
                                                  'hg.create.repository'),
            'fork_repo_perm': ug_model.has_perm(c.users_group,
                                                'hg.fork.repository'),
        })

        return htmlfill.render(
            render('admin/users_groups/users_group_edit.html'),
            defaults=defaults,
            encoding="UTF-8",
            force_defaults=False
        )
示例#5
0
    def _get_defaults(self, repo_name):
        """
        Get's information about repository, and returns a dict for
        usage in forms

        :param repo_name:
        """

        repo_info = Repository.get_by_repo_name(repo_name)

        if repo_info is None:
            return None

        defaults = repo_info.get_dict()
        group, repo_name = repo_info.groups_and_repo
        defaults["repo_name"] = repo_name
        defaults["repo_group"] = getattr(group[-1] if group else None, "group_id", None)

        # fill owner
        if repo_info.user:
            defaults.update({"user": repo_info.user.username})
        else:
            replacement_user = User.query().filter(User.admin == True).first().username
            defaults.update({"user": replacement_user})

        # fill repository users
        for p in repo_info.repo_to_perm:
            defaults.update({"u_perm_%s" % p.user.username: p.permission.permission_name})

        # fill repository groups
        for p in repo_info.users_group_to_perm:
            defaults.update({"g_perm_%s" % p.users_group.users_group_name: p.permission.permission_name})

        return defaults
def get_users(request, apiuser):
    """
    Lists all users in the |RCE| user database.

    This command can only be run using an |authtoken| with admin rights to
    the specified repository.

    This command takes the following options:

    :param apiuser: This is filled automatically from the |authtoken|.
    :type apiuser: AuthUser

    Example output:

    .. code-block:: bash

        id : <id_given_in_input>
            result: [<user_object>, ...]
        error:  null
    """

    if not has_superadmin_permission(apiuser):
        raise JSONRPCForbidden()

    result = []
    users_list = User.query().order_by(User.username) \
        .filter(User.username != User.DEFAULT_USER) \
        .all()
    for user in users_list:
        result.append(user.get_api_data(include_secrets=True))
    return result
示例#7
0
    def _load_data(self, id):
        c.users_group.permissions = {
            'repositories': {},
            'repositories_groups': {}
        }

        ugroup_repo_perms = UserGroupRepoToPerm.query()\
            .options(joinedload(UserGroupRepoToPerm.permission))\
            .options(joinedload(UserGroupRepoToPerm.repository))\
            .filter(UserGroupRepoToPerm.users_group_id == id)\
            .all()

        for gr in ugroup_repo_perms:
            c.users_group.permissions['repositories'][gr.repository.repo_name]  \
                = gr.permission.permission_name

        ugroup_group_perms = UserGroupRepoGroupToPerm.query()\
            .options(joinedload(UserGroupRepoGroupToPerm.permission))\
            .options(joinedload(UserGroupRepoGroupToPerm.group))\
            .filter(UserGroupRepoGroupToPerm.users_group_id == id)\
            .all()

        for gr in ugroup_group_perms:
            c.users_group.permissions['repositories_groups'][gr.group.group_name] \
                = gr.permission.permission_name

        c.group_members_obj = sorted((x.user for x in c.users_group.members),
                                     key=lambda u: u.username.lower())
        c.group_members = [(x.user_id, x.username)
                           for x in c.group_members_obj]
        c.available_members = sorted(
            ((x.user_id, x.username) for x in User.query().all()),
            key=lambda u: u[1].lower())
示例#8
0
    def _load_data(self, id):
        c.users_group.permissions = {
            'repositories': {},
            'repositories_groups': {}
        }

        ugroup_repo_perms = UsersGroupRepoToPerm.query()\
            .options(joinedload(UsersGroupRepoToPerm.permission))\
            .options(joinedload(UsersGroupRepoToPerm.repository))\
            .filter(UsersGroupRepoToPerm.users_group_id == id)\
            .all()

        for gr in ugroup_repo_perms:
            c.users_group.permissions['repositories'][gr.repository.repo_name]  \
                = gr.permission.permission_name

        ugroup_group_perms = UsersGroupRepoGroupToPerm.query()\
            .options(joinedload(UsersGroupRepoGroupToPerm.permission))\
            .options(joinedload(UsersGroupRepoGroupToPerm.group))\
            .filter(UsersGroupRepoGroupToPerm.users_group_id == id)\
            .all()

        for gr in ugroup_group_perms:
            c.users_group.permissions['repositories_groups'][gr.group.group_name] \
                = gr.permission.permission_name

        c.group_members_obj = [x.user for x in c.users_group.members]
        c.group_members = [(x.user_id, x.username) for x in
                           c.group_members_obj]
        c.available_members = [(x.user_id, x.username) for x in
                               User.query().all()]
示例#9
0
        def to_python(self, value, state):
            perms_update = OrderedSet()
            perms_new = OrderedSet()
            # build a list of permission to update and new permission to create

            # CLEAN OUT ORG VALUE FROM NEW MEMBERS, and group them using
            new_perms_group = defaultdict(dict)
            for k, v in value.copy().iteritems():
                if k.startswith("perm_new_member"):
                    del value[k]
                    _type, part = k.split("perm_new_member_")
                    args = part.split("_")
                    if len(args) == 1:
                        new_perms_group[args[0]]["perm"] = v
                    elif len(args) == 2:
                        _key, pos = args
                        new_perms_group[pos][_key] = v

            # fill new permissions in order of how they were added
            for k in sorted(map(int, new_perms_group.keys())):
                perm_dict = new_perms_group[str(k)]
                new_member = perm_dict.get("name")
                new_perm = perm_dict.get("perm")
                new_type = perm_dict.get("type")
                if new_member and new_perm and new_type:
                    perms_new.add((new_member, new_perm, new_type))

            for k, v in value.iteritems():
                if k.startswith("u_perm_") or k.startswith("g_perm_"):
                    member = k[7:]
                    t = {"u": "user", "g": "users_group"}[k[0]]
                    if member == "default":
                        if value.get("private"):
                            # set none for default when updating to
                            # private repo
                            v = EMPTY_PERM
                    perms_update.add((member, v, t))

            value["perms_updates"] = list(perms_update)
            value["perms_new"] = list(perms_new)

            # update permissions
            for k, v, t in perms_new:
                try:
                    if t is "user":
                        self.user_db = User.query().filter(User.active == True).filter(User.username == k).one()
                    if t is "users_group":
                        self.user_db = (
                            UsersGroup.query()
                            .filter(UsersGroup.users_group_active == True)
                            .filter(UsersGroup.users_group_name == k)
                            .one()
                        )

                except Exception:
                    log.exception("Updated permission failed")
                    msg = M(self, "perm_new_member_type", state)
                    raise formencode.Invalid(msg, value, state, error_dict=dict(perm_new_member_name=msg))
            return value
示例#10
0
文件: forms.py 项目: q210/rhodecode
    def to_python(self, value, state):
        value = value.lower()
        user = User.query().filter(User.email == value).scalar()
        if  user is None:
            raise formencode.Invalid(_("This e-mail address doesn't exist.") ,
                                     value, state)

        return value
示例#11
0
    def index(self, format='html'):
        """GET /users: All items in the collection"""
        # url('users')

        c.users_list = User.query().order_by(User.username)\
                        .filter(User.username != User.DEFAULT_USER)\
                        .all()

        users_data = []
        total_records = len(c.users_list)
        _tmpl_lookup = rhodecode.CONFIG['pylons.app_globals'].mako_lookup
        template = _tmpl_lookup.get_template('data_table/_dt_elements.html')

        grav_tmpl = lambda user_email, size: (template.get_def(
            "user_gravatar").render(user_email, size, _=_, h=h, c=c))

        user_lnk = lambda user_id, username: (template.get_def(
            "user_name").render(user_id, username, _=_, h=h, c=c))

        user_actions = lambda user_id, username: (template.get_def(
            "user_actions").render(user_id, username, _=_, h=h, c=c))

        for user in c.users_list:

            users_data.append({
                "gravatar":
                grav_tmpl(user.email, 24),
                "raw_username":
                user.username,
                "username":
                user_lnk(user.user_id, user.username),
                "firstname":
                user.name,
                "lastname":
                user.lastname,
                "last_login":
                h.fmt_date(user.last_login),
                "last_login_raw":
                datetime_to_time(user.last_login),
                "active":
                h.boolicon(user.active),
                "admin":
                h.boolicon(user.admin),
                "ldap":
                h.boolicon(bool(user.ldap_dn)),
                "action":
                user_actions(user.user_id, user.username),
            })

        c.data = json.dumps({
            "totalRecords": total_records,
            "startIndex": 0,
            "sort": None,
            "dir": "asc",
            "records": users_data
        })

        return render('admin/users/users.html')
示例#12
0
文件: forms.py 项目: q210/rhodecode
 def to_python(self, value, state):
     value = value.lower()
     if old_data.get('email') != value:
         user = User.query().filter(User.email == value).scalar()
         if user:
             raise formencode.Invalid(
                             _("This e-mail address is already taken"),
                             value, state)
     return value
    def __load_data(self, user_group_id):
        c.group_members_obj = [x.user for x in c.user_group.members]
        c.group_members_obj.sort(key=lambda u: u.username.lower())

        c.group_members = [(x.user_id, x.username)
                           for x in c.group_members_obj]

        c.available_members = [(x.user_id, x.username)
                               for x in User.query().all()]
        c.available_members.sort(key=lambda u: u[1].lower())
示例#14
0
 def test_api_get_users(self):
     id_, params = build_data(self.apikey, 'get_users', )
     response = api_call(self.app, params)
     ret_all = []
     _users = User.query().filter(User.username != User.DEFAULT_USER) \
         .order_by(User.username).all()
     for usr in _users:
         ret = usr.get_api_data(include_secrets=True)
         ret_all.append(jsonify(ret))
     expected = ret_all
     assert_ok(id_, expected, given=response.body)
示例#15
0
def send_email(recipients, subject, body='', html_body=''):
    """
    Sends an email with defined parameters from the .ini files.

    :param recipients: list of recipients, it this is empty the defined email
        address from field 'email_to' is used instead
    :param subject: subject of the mail
    :param body: body of the mail
    :param html_body: html version of body
    """
    log = get_logger(send_email)
    DBS = get_session()

    email_config = config
    subject = "%s %s" % (email_config.get('email_prefix', ''), subject)
    if not recipients:
        # if recipients are not defined we send to email_config + all admins
        admins = [
            u.email for u in User.query().filter(User.admin == True).all()
        ]
        recipients = [email_config.get('email_to')] + admins

    mail_from = email_config.get('app_email_from', 'RhodeCode')
    user = email_config.get('smtp_username')
    passwd = email_config.get('smtp_password')
    mail_server = email_config.get('smtp_server')
    mail_port = email_config.get('smtp_port')
    tls = str2bool(email_config.get('smtp_use_tls'))
    ssl = str2bool(email_config.get('smtp_use_ssl'))
    debug = str2bool(email_config.get('debug'))
    smtp_auth = email_config.get('smtp_auth')

    if not mail_server:
        log.error("SMTP mail server not configured - cannot send mail")
        return False

    try:
        m = SmtpMailer(mail_from,
                       user,
                       passwd,
                       mail_server,
                       smtp_auth,
                       mail_port,
                       ssl,
                       tls,
                       debug=debug)
        m.send(recipients, subject, body, html_body)
    except:
        log.error('Mail sending failed')
        log.error(traceback.format_exc())
        return False
    return True
示例#16
0
def send_email(recipients, subject, body='', html_body='', email_config=None):
    """
    Sends an email with defined parameters from the .ini files.

    :param recipients: list of recipients, it this is empty the defined email
        address from field 'email_to' is used instead
    :param subject: subject of the mail
    :param body: body of the mail
    :param html_body: html version of body
    """
    log = get_logger(send_email)

    email_config = email_config or config
    subject = "%s %s" % (email_config.get('email_prefix', ''), subject)
    if not recipients:
        # if recipients are not defined we send to email_config + all admins
        admins = [
            u.email for u in User.query().filter(User.admin == True).all()
        ]
        recipients = [email_config.get('email_to')] + admins

    mail_server = email_config.get('smtp_server') or None
    if mail_server is None:
        log.error("SMTP server information missing. Sending email failed. "
                  "Make sure that `smtp_server` variable is configured "
                  "inside the .ini file")
        return False

    mail_from = email_config.get('app_email_from', 'RhodeCode')
    user = email_config.get('smtp_username')
    passwd = email_config.get('smtp_password')
    mail_port = email_config.get('smtp_port')
    tls = str2bool(email_config.get('smtp_use_tls'))
    ssl = str2bool(email_config.get('smtp_use_ssl'))
    debug = str2bool(email_config.get('debug'))
    smtp_auth = email_config.get('smtp_auth')

    try:
        m = SmtpMailer(mail_from,
                       user,
                       passwd,
                       mail_server,
                       smtp_auth,
                       mail_port,
                       ssl,
                       tls,
                       debug=debug)
        m.send(recipients, subject, body, html_body)
    except Exception:
        log.exception('Mail sending failed')
        return False
    return True
 def validate_python(self, value, state):
     try:
         user = User.query().filter(User.username == value).one()
     except Exception:
         msg = M(self, 'invalid_username', state, username=value)
         raise formencode.Invalid(
             msg, value, state, error_dict={'username': msg}
         )
     if user and (not allow_disabled and not user.active):
         msg = M(self, 'disabled_username', state, username=value)
         raise formencode.Invalid(
             msg, value, state, error_dict={'username': msg}
         )
示例#18
0
    def get_users(self, apiuser):
        """"
        Get all users

        :param apiuser:
        """

        result = []
        users_list = User.query().order_by(User.username)\
                        .filter(User.username != User.DEFAULT_USER)\
                        .all()
        for user in users_list:
            result.append(user.get_api_data())
        return result
示例#19
0
    def index(self, format='html'):
        """GET /users: All items in the collection"""
        # url('users')

        c.users_list = User.query().order_by(User.username)\
                        .filter(User.username != User.DEFAULT_USER)\
                        .all()

        users_data = []
        total_records = len(c.users_list)
        _tmpl_lookup = rhodecode.CONFIG['pylons.app_globals'].mako_lookup
        template = _tmpl_lookup.get_template('data_table/_dt_elements.html')

        grav_tmpl = lambda user_email, size: (
                template.get_def("user_gravatar")
                .render(user_email, size, _=_, h=h, c=c))

        user_lnk = lambda user_id, username: (
                template.get_def("user_name")
                .render(user_id, username, _=_, h=h, c=c))

        user_actions = lambda user_id, username: (
                template.get_def("user_actions")
                .render(user_id, username, _=_, h=h, c=c))

        for user in c.users_list:

            users_data.append({
                "gravatar": grav_tmpl(user. email, 24),
                "raw_username": user.username,
                "username": user_lnk(user.user_id, user.username),
                "firstname": user.name,
                "lastname": user.lastname,
                "last_login": h.fmt_date(user.last_login),
                "last_login_raw": datetime_to_time(user.last_login),
                "active": h.boolicon(user.active),
                "admin": h.boolicon(user.admin),
                "ldap": h.boolicon(bool(user.ldap_dn)),
                "action": user_actions(user.user_id, user.username),
            })

        c.data = json.dumps({
            "totalRecords": total_records,
            "startIndex": 0,
            "sort": None,
            "dir": "asc",
            "records": users_data
        })

        return render('admin/users/users.html')
示例#20
0
    def get_users(self, apiuser):
        """"
        Get all users

        :param apiuser:
        """

        result = []
        users_list = User.query().order_by(User.username)\
                        .filter(User.username != User.DEFAULT_USER)\
                        .all()
        for user in users_list:
            result.append(user.get_api_data())
        return result
示例#21
0
    def update(self, id):
        """PUT /users_groups/id: Update an existing item"""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="PUT" />
        # Or using helpers:
        #    h.form(url('users_group', id=ID),
        #           method='put')
        # url('users_group', id=ID)

        c.users_group = UsersGroup.get(id)
        c.group_members_obj = [x.user for x in c.users_group.members]
        c.group_members = [(x.user_id, x.username) for x in
                           c.group_members_obj]

        c.available_members = [(x.user_id, x.username) for x in
                               User.query().all()]

        available_members = [safe_unicode(x[0]) for x in c.available_members]

        users_group_form = UsersGroupForm(edit=True,
                                          old_data=c.users_group.get_dict(),
                                          available_members=available_members)()

        try:
            form_result = users_group_form.to_python(request.POST)
            UsersGroupModel().update(c.users_group, form_result)
            gr = form_result['users_group_name']
            action_logger(self.rhodecode_user,
                          'admin_updated_users_group:%s' % gr,
                          None, self.ip_addr, self.sa)
            h.flash(_('updated users group %s') % gr, category='success')
            Session().commit()
        except formencode.Invalid, errors:
            ug_model = UsersGroupModel()
            defaults = errors.value
            e = errors.error_dict or {}
            defaults.update({
                'create_repo_perm': ug_model.has_perm(id,
                                                      'hg.create.repository'),
                'fork_repo_perm': ug_model.has_perm(id,
                                                    'hg.fork.repository'),
                '_method': 'put'
            })

            return htmlfill.render(
                render('admin/users_groups/users_group_edit.html'),
                defaults=defaults,
                errors=e,
                prefix_error=False,
                encoding="UTF-8")
示例#22
0
    def _get_defaults(self, repo_name):
        """
        Get's information about repository, and returns a dict for
        usage in forms

        :param repo_name:
        """

        repo_info = Repository.get_by_repo_name(repo_name)

        if repo_info is None:
            return None

        defaults = repo_info.get_dict()
        group, repo_name, repo_name_full = repo_info.groups_and_repo
        defaults['repo_name'] = repo_name
        defaults['repo_group'] = getattr(group[-1] if group else None,
                                         'group_id', None)

        for strip, k in [(0, 'repo_type'), (1, 'repo_enable_downloads'),
                         (1, 'repo_description'), (1, 'repo_enable_locking'),
                         (1, 'repo_landing_rev'), (0, 'clone_uri'),
                         (1, 'repo_private'), (1, 'repo_enable_statistics')]:
            attr = k
            if strip:
                attr = remove_prefix(k, 'repo_')

            defaults[k] = defaults[attr]

        # fill owner
        if repo_info.user:
            defaults.update({'user': repo_info.user.username})
        else:
            replacement_user = User.query().filter(
                User.admin == True).first().username
            defaults.update({'user': replacement_user})

        # fill repository users
        for p in repo_info.repo_to_perm:
            defaults.update(
                {'u_perm_%s' % p.user.username: p.permission.permission_name})

        # fill repository groups
        for p in repo_info.users_group_to_perm:
            defaults.update({
                'g_perm_%s' % p.users_group.users_group_name:
                p.permission.permission_name
            })

        return defaults
示例#23
0
    def get_accounts_in_creation_order(self, current_user=None):
        """
        Get accounts in order of creation for deactivation for license limits

        pick currently logged in user, and append to the list in position 0
        pick all super-admins in order of creation date and add it to the list
        pick all other accounts in order of creation and add it to the list.

        Based on that list, the last accounts can be disabled as they are
        created at the end and don't include any of the super admins as well
        as the current user.

        :param current_user: optionally current user running this operation
        """

        if not current_user:
            current_user = get_current_rhodecode_user()
        active_super_admins = [
            x.user_id for x in User.query()
            .filter(User.user_id != current_user.user_id)
            .filter(User.active == true())
            .filter(User.admin == true())
            .order_by(User.created_on.asc())]

        active_regular_users = [
            x.user_id for x in User.query()
            .filter(User.user_id != current_user.user_id)
            .filter(User.active == true())
            .filter(User.admin == false())
            .order_by(User.created_on.asc())]

        list_of_accounts = [current_user.user_id]
        list_of_accounts += active_super_admins
        list_of_accounts += active_regular_users

        return list_of_accounts
示例#24
0
    def _get_defaults(self, repo_name):
        """
        Get's information about repository, and returns a dict for
        usage in forms

        :param repo_name:
        """

        repo_info = Repository.get_by_repo_name(repo_name)

        if repo_info is None:
            return None

        defaults = repo_info.get_dict()
        group, repo_name, repo_name_full = repo_info.groups_and_repo
        defaults['repo_name'] = repo_name
        defaults['repo_group'] = getattr(group[-1] if group else None,
                                         'group_id', None)

        for strip, k in [(0, 'repo_type'), (1, 'repo_enable_downloads'),
                  (1, 'repo_description'), (1, 'repo_enable_locking'),
                  (1, 'repo_landing_rev'), (0, 'clone_uri'),
                  (1, 'repo_private'), (1, 'repo_enable_statistics')]:
            attr = k
            if strip:
                attr = remove_prefix(k, 'repo_')

            defaults[k] = defaults[attr]

        # fill owner
        if repo_info.user:
            defaults.update({'user': repo_info.user.username})
        else:
            replacement_user = User.query().filter(User.admin ==
                                                   True).first().username
            defaults.update({'user': replacement_user})

        # fill repository users
        for p in repo_info.repo_to_perm:
            defaults.update({'u_perm_%s' % p.user.username:
                             p.permission.permission_name})

        # fill repository groups
        for p in repo_info.users_group_to_perm:
            defaults.update({'g_perm_%s' % p.users_group.users_group_name:
                             p.permission.permission_name})

        return defaults
示例#25
0
        def to_python(self, value, state):
            perms_update = []
            perms_new = []
            # build a list of permission to update and new permission to create
            for k, v in value.items():
                # means new added member to permissions
                if k.startswith('perm_new_member'):
                    new_perm = value.get('perm_new_member', False)
                    new_member = value.get('perm_new_member_name', False)
                    new_type = value.get('perm_new_member_type')

                    if new_member and new_perm:
                        if (new_member, new_perm, new_type) not in perms_new:
                            perms_new.append((new_member, new_perm, new_type))
                elif k.startswith('u_perm_') or k.startswith('g_perm_'):
                    member = k[7:]
                    t = {'u': 'user',
                         'g': 'users_group'
                    }[k[0]]
                    if member == 'default':
                        if value.get('private'):
                            # set none for default when updating to private repo
                            v = EMPTY_PERM
                    perms_update.append((member, v, t))

            value['perms_updates'] = perms_update
            value['perms_new'] = perms_new

            # update permissions
            for k, v, t in perms_new:
                try:
                    if t is 'user':
                        self.user_db = User.query()\
                            .filter(User.active == True)\
                            .filter(User.username == k).one()
                    if t is 'users_group':
                        self.user_db = UsersGroup.query()\
                            .filter(UsersGroup.users_group_active == True)\
                            .filter(UsersGroup.users_group_name == k).one()

                except Exception:
                    msg = self.message('perm_new_member_name',
                                         state=State_obj)
                    raise formencode.Invalid(
                        msg, value, state, error_dict={'perm_new_member_name': msg}
                    )
            return value
示例#26
0
def send_email(recipients, subject, body="", html_body=""):
    """
    Sends an email with defined parameters from the .ini files.

    :param recipients: list of recipients, it this is empty the defined email
        address from field 'email_to' is used instead
    :param subject: subject of the mail
    :param body: body of the mail
    :param html_body: html version of body
    """
    log = get_logger(send_email)
    DBS = get_session()

    email_config = config
    subject = "%s %s" % (email_config.get("email_prefix", ""), subject)
    if not recipients:
        # if recipients are not defined we send to email_config + all admins
        admins = [u.email for u in User.query().filter(User.admin == True).all()]
        recipients = [email_config.get("email_to")] + admins

    mail_from = email_config.get("app_email_from", "RhodeCode")
    user = email_config.get("smtp_username")
    passwd = email_config.get("smtp_password")
    mail_server = email_config.get("smtp_server")
    mail_port = email_config.get("smtp_port")
    tls = str2bool(email_config.get("smtp_use_tls"))
    ssl = str2bool(email_config.get("smtp_use_ssl"))
    debug = str2bool(email_config.get("debug"))
    smtp_auth = email_config.get("smtp_auth")

    if not mail_server:
        log.error("SMTP mail server not configured - cannot send mail")
        return False

    try:
        m = SmtpMailer(mail_from, user, passwd, mail_server, smtp_auth, mail_port, ssl, tls, debug=debug)
        m.send(recipients, subject, body, html_body)
    except:
        log.error("Mail sending failed")
        log.error(traceback.format_exc())
        return False
    return True
示例#27
0
    def _get_defaults(self, repo_name):
        """
        Get's information about repository, and returns a dict for
        usage in forms

        :param repo_name:
        """

        repo_info = Repository.get_by_repo_name(repo_name)

        if repo_info is None:
            return None

        defaults = repo_info.get_dict()
        group, repo_name = repo_info.groups_and_repo
        defaults['repo_name'] = repo_name
        defaults['repo_group'] = getattr(group[-1] if group else None,
                                         'group_id', None)

        # fill owner
        if repo_info.user:
            defaults.update({'user': repo_info.user.username})
        else:
            replacement_user = User.query().filter(
                User.admin == True).first().username
            defaults.update({'user': replacement_user})

        # fill repository users
        for p in repo_info.repo_to_perm:
            defaults.update(
                {'u_perm_%s' % p.user.username: p.permission.permission_name})

        # fill repository groups
        for p in repo_info.users_group_to_perm:
            defaults.update({
                'g_perm_%s' % p.users_group.users_group_name:
                p.permission.permission_name
            })

        return defaults
示例#28
0
def send_email(recipients, subject, body, html_body=''):
    """
    Sends an email with defined parameters from the .ini files.

    :param recipients: list of recipients, it this is empty the defined email
        address from field 'email_to' is used instead
    :param subject: subject of the mail
    :param body: body of the mail
    :param html_body: html version of body
    """
    log = get_logger(send_email)
    DBS = get_session()

    email_config = config
    subject = "%s %s" % (email_config.get('email_prefix', ''), subject)
    if not recipients:
        # if recipients are not defined we send to email_config + all admins
        admins = [u.email for u in User.query()
                  .filter(User.admin == True).all()]
        recipients = [email_config.get('email_to')] + admins

    mail_from = email_config.get('app_email_from', 'RhodeCode')
    user = email_config.get('smtp_username')
    passwd = email_config.get('smtp_password')
    mail_server = email_config.get('smtp_server')
    mail_port = email_config.get('smtp_port')
    tls = str2bool(email_config.get('smtp_use_tls'))
    ssl = str2bool(email_config.get('smtp_use_ssl'))
    debug = str2bool(config.get('debug'))
    smtp_auth = email_config.get('smtp_auth')

    try:
        m = SmtpMailer(mail_from, user, passwd, mail_server, smtp_auth,
                       mail_port, ssl, tls, debug=debug)
        m.send(recipients, subject, body, html_body)
    except:
        log.error('Mail sending failed')
        log.error(traceback.format_exc())
        return False
    return True
示例#29
0
    def __load_data(self, user_group_id):
        permissions = {
            'repositories': {},
            'repositories_groups': {}
        }
        ugroup_repo_perms = UserGroupRepoToPerm.query()\
            .options(joinedload(UserGroupRepoToPerm.permission))\
            .options(joinedload(UserGroupRepoToPerm.repository))\
            .filter(UserGroupRepoToPerm.users_group_id == user_group_id)\
            .all()

        for gr in ugroup_repo_perms:
            permissions['repositories'][gr.repository.repo_name]  \
                = gr.permission.permission_name

        ugroup_group_perms = UserGroupRepoGroupToPerm.query()\
            .options(joinedload(UserGroupRepoGroupToPerm.permission))\
            .options(joinedload(UserGroupRepoGroupToPerm.group))\
            .filter(UserGroupRepoGroupToPerm.users_group_id == user_group_id)\
            .all()

        for gr in ugroup_group_perms:
            permissions['repositories_groups'][gr.group.group_name] \
                = gr.permission.permission_name
        c.permissions = permissions
        c.group_members_obj = sorted((x.user for x in c.users_group.members),
                                     key=lambda u: u.username.lower())

        c.group_members = [(x.user_id, x.username) for x in c.group_members_obj]
        c.available_members = sorted(((x.user_id, x.username) for x in
                                      User.query().all()),
                                     key=lambda u: u[1].lower())
        repo_model = RepoModel()
        c.users_array = repo_model.get_users_js()
        c.users_groups_array = repo_model.get_users_groups_js()
        c.available_permissions = config['available_permissions']
示例#30
0
    def create(self,
               created_by,
               subject,
               body,
               recipients=None,
               type_=Notification.TYPE_MESSAGE,
               with_email=True,
               email_kwargs={}):
        """

        Creates notification of given type

        :param created_by: int, str or User instance. User who created this
            notification
        :param subject:
        :param body:
        :param recipients: list of int, str or User objects, when None
            is given send to all admins
        :param type_: type of notification
        :param with_email: send email with this notification
        :param email_kwargs: additional dict to pass as args to email template
        """
        from rhodecode.lib.celerylib import tasks, run_task

        if recipients and not getattr(recipients, '__iter__', False):
            raise Exception('recipients must be a list of iterable')

        created_by_obj = self.__get_user(created_by)

        if recipients:
            recipients_objs = []
            for u in recipients:
                obj = self.__get_user(u)
                if obj:
                    recipients_objs.append(obj)
            recipients_objs = set(recipients_objs)
            log.debug('sending notifications %s to %s' %
                      (type_, recipients_objs))
        else:
            # empty recipients means to all admins
            recipients_objs = User.query().filter(User.admin == True).all()
            log.debug('sending notifications %s to admins: %s' %
                      (type_, recipients_objs))
        notif = Notification.create(created_by=created_by_obj,
                                    subject=subject,
                                    body=body,
                                    recipients=recipients_objs,
                                    type_=type_)

        if with_email is False:
            return notif

        # send email with notification
        for rec in recipients_objs:
            email_subject = NotificationModel().make_description(notif, False)
            type_ = type_
            email_body = body
            kwargs = {'subject': subject, 'body': h.rst_w_mentions(body)}
            kwargs.update(email_kwargs)
            email_body_html = EmailNotificationModel()\
                                .get_email_tmpl(type_, **kwargs)

            run_task(tasks.send_email, rec.email, email_subject, email_body,
                     email_body_html)

        return notif
示例#31
0
    def create(self, created_by, subject, body, recipients=None,
               type_=Notification.TYPE_MESSAGE, with_email=True,
               email_kwargs={}, email_subject=None):
        """

        Creates notification of given type

        :param created_by: int, str or User instance. User who created this
            notification
        :param subject:
        :param body:
        :param recipients: list of int, str or User objects, when None
            is given send to all admins
        :param type_: type of notification
        :param with_email: send email with this notification
        :param email_kwargs: additional dict to pass as args to email template
        :param email_subject: use given subject as email subject
        """
        from rhodecode.lib.celerylib import tasks, run_task

        if recipients and not getattr(recipients, '__iter__', False):
            raise Exception('recipients must be a list or iterable')

        created_by_obj = self._get_user(created_by)

        if recipients:
            recipients_objs = []
            for u in recipients:
                obj = self._get_user(u)
                if obj:
                    recipients_objs.append(obj)
                else:
                    # TODO: inform user that requested operation couldn't be completed
                    log.error('cannot email unknown user %r', u)
            recipients_objs = set(recipients_objs)
            log.debug('sending notifications %s to %s' % (
                type_, recipients_objs)
            )
        else:
            # empty recipients means to all admins
            recipients_objs = User.query().filter(User.admin == True).all()
            log.debug('sending notifications %s to admins: %s' % (
                type_, recipients_objs)
            )
        # TODO: inform user who are notified
        notif = Notification.create(
            created_by=created_by_obj, subject=subject,
            body=body, recipients=recipients_objs, type_=type_
        )

        if not with_email:
            return notif

        #don't send email to person who created this comment
        rec_objs = set(recipients_objs).difference(set([created_by_obj]))

        # send email with notification to all other participants
        for rec in rec_objs:
            if not email_subject:
                email_subject = NotificationModel()\
                                    .make_description(notif, show_age=False)
            type_ = type_
            email_body = None  # we set body to none, we just send HTML emails
            ## this is passed into template
            kwargs = {'subject': subject, 'body': h.rst_w_mentions(body)}
            kwargs.update(email_kwargs)
            email_body_html = EmailNotificationModel()\
                                .get_email_tmpl(type_, **kwargs)

            run_task(tasks.send_email, rec.email, email_subject, email_body,
                     email_body_html)

        return notif
        def _to_python(self, value, state):
            perm_updates = OrderedSet()
            perm_additions = OrderedSet()
            perm_deletions = OrderedSet()
            # build a list of permission to update/delete and new permission

            # Read the perm_new_member/perm_del_member attributes and group
            # them by they IDs
            new_perms_group = defaultdict(dict)
            del_perms_group = defaultdict(dict)
            for k, v in value.copy().iteritems():
                if k.startswith('perm_del_member'):
                    # delete from org storage so we don't process that later
                    del value[k]
                    # part is `id`, `type`
                    _type, part = k.split('perm_del_member_')
                    args = part.split('_')
                    if len(args) == 2:
                        _key, pos = args
                        del_perms_group[pos][_key] = v
                if k.startswith('perm_new_member'):
                    # delete from org storage so we don't process that later
                    del value[k]
                    # part is `id`, `type`, `perm`
                    _type, part = k.split('perm_new_member_')
                    args = part.split('_')
                    if len(args) == 2:
                        _key, pos = args
                        new_perms_group[pos][_key] = v

            # store the deletes
            for k in sorted(del_perms_group.keys()):
                perm_dict = del_perms_group[k]
                del_member = perm_dict.get('id')
                del_type = perm_dict.get('type')
                if del_member and del_type:
                    perm_deletions.add((del_member, None, del_type))

            # store additions in order of how they were added in web form
            for k in sorted(new_perms_group.keys()):
                perm_dict = new_perms_group[k]
                new_member = perm_dict.get('id')
                new_type = perm_dict.get('type')
                new_perm = perm_dict.get('perm')
                if new_member and new_perm and new_type:
                    perm_additions.add((new_member, new_perm, new_type))

            # get updates of permissions
            # (read the existing radio button states)
            for k, update_value in value.iteritems():
                if k.startswith('u_perm_') or k.startswith('g_perm_'):
                    member = k[7:]
                    update_type = {'u': 'user',
                                   'g': 'users_group'}[k[0]]
                    if member == User.DEFAULT_USER:
                        if str2bool(value.get('repo_private')):
                            # set none for default when updating to
                            # private repo protects agains form manipulation
                            update_value = EMPTY_PERM
                    perm_updates.add((member, update_value, update_type))
            # check the deletes

            value['perm_additions'] = list(perm_additions)
            value['perm_updates'] = list(perm_updates)
            value['perm_deletions'] = list(perm_deletions)

            # validate users they exist and they are active !
            for member_id, _perm, member_type in perm_additions:
                try:
                    if member_type == 'user':
                        self.user_db = User.query()\
                            .filter(User.active == true())\
                            .filter(User.user_id == member_id).one()
                    if member_type == 'users_group':
                        self.user_db = UserGroup.query()\
                            .filter(UserGroup.users_group_active == true())\
                            .filter(UserGroup.users_group_id == member_id)\
                            .one()

                except Exception:
                    log.exception('Updated permission failed: org_exc:')
                    msg = M(self, 'perm_new_member_type', state)
                    raise formencode.Invalid(
                        msg, value, state, error_dict={
                            'perm_new_member_name': msg}
                    )
            return value
示例#33
0
        def to_python(self, value, state):
            perms_update = OrderedSet()
            perms_new = OrderedSet()
            # build a list of permission to update and new permission to create

            #CLEAN OUT ORG VALUE FROM NEW MEMBERS, and group them using
            new_perms_group = defaultdict(dict)
            for k, v in value.copy().iteritems():
                if k.startswith('perm_new_member'):
                    del value[k]
                    _type, part = k.split('perm_new_member_')
                    args = part.split('_')
                    if len(args) == 1:
                        new_perms_group[args[0]]['perm'] = v
                    elif len(args) == 2:
                        _key, pos = args
                        new_perms_group[pos][_key] = v

            # fill new permissions in order of how they were added
            for k in sorted(map(int, new_perms_group.keys())):
                perm_dict = new_perms_group[str(k)]
                new_member = perm_dict.get('name')
                new_perm = perm_dict.get('perm')
                new_type = perm_dict.get('type')
                if new_member and new_perm and new_type:
                    perms_new.add((new_member, new_perm, new_type))

            for k, v in value.iteritems():
                if k.startswith('u_perm_') or k.startswith('g_perm_'):
                    member = k[7:]
                    t = {'u': 'user',
                         'g': 'users_group'
                    }[k[0]]
                    if member == 'default':
                        if str2bool(value.get('repo_private')):
                            # set none for default when updating to
                            # private repo protects agains form manipulation
                            v = EMPTY_PERM
                    perms_update.add((member, v, t))

            value['perms_updates'] = list(perms_update)
            value['perms_new'] = list(perms_new)

            # update permissions
            for k, v, t in perms_new:
                try:
                    if t is 'user':
                        self.user_db = User.query()\
                            .filter(User.active == True)\
                            .filter(User.username == k).one()
                    if t is 'users_group':
                        self.user_db = UserGroup.query()\
                            .filter(UserGroup.users_group_active == True)\
                            .filter(UserGroup.users_group_name == k).one()

                except Exception:
                    log.exception('Updated permission failed')
                    msg = M(self, 'perm_new_member_type', state)
                    raise formencode.Invalid(msg, value, state,
                        error_dict=dict(perm_new_member_name=msg)
                    )
            return value
示例#34
0
 def get_active_user_count(self, cache=False):
     return User.query().filter(
         User.active == True).filter(
             User.username != User.DEFAULT_USER).count()
示例#35
0
    def create(self, created_by, subject, body, recipients=None,
               type_=Notification.TYPE_MESSAGE, with_email=True,
               email_kwargs={}):
        """

        Creates notification of given type

        :param created_by: int, str or User instance. User who created this
            notification
        :param subject:
        :param body:
        :param recipients: list of int, str or User objects, when None
            is given send to all admins
        :param type_: type of notification
        :param with_email: send email with this notification
        :param email_kwargs: additional dict to pass as args to email template
        """
        from rhodecode.lib.celerylib import tasks, run_task

        if recipients and not getattr(recipients, '__iter__', False):
            raise Exception('recipients must be a list of iterable')

        created_by_obj = self.__get_user(created_by)

        if recipients:
            recipients_objs = []
            for u in recipients:
                obj = self.__get_user(u)
                if obj:
                    recipients_objs.append(obj)
            recipients_objs = set(recipients_objs)
            log.debug('sending notifications %s to %s' % (
                type_, recipients_objs)
            )
        else:
            # empty recipients means to all admins
            recipients_objs = User.query().filter(User.admin == True).all()
            log.debug('sending notifications %s to admins: %s' % (
                type_, recipients_objs)
            )
        notif = Notification.create(
            created_by=created_by_obj, subject=subject,
            body=body, recipients=recipients_objs, type_=type_
        )

        if with_email is False:
            return notif

        # send email with notification
        for rec in recipients_objs:
            email_subject = NotificationModel().make_description(notif, False)
            type_ = type_
            email_body = body
            kwargs = {'subject': subject, 'body': h.rst_w_mentions(body)}
            kwargs.update(email_kwargs)
            email_body_html = EmailNotificationModel()\
                                .get_email_tmpl(type_, **kwargs)

            run_task(tasks.send_email, rec.email, email_subject, email_body,
                     email_body_html)

        return notif
示例#36
0
    def create(self,
               created_by,
               notification_subject,
               notification_body,
               notification_type=Notification.TYPE_MESSAGE,
               recipients=None,
               mention_recipients=None,
               with_email=True,
               email_kwargs=None):
        """

        Creates notification of given type

        :param created_by: int, str or User instance. User who created this
            notification
        :param notification_subject: subject of notification itself
        :param notification_body: body of notification text
        :param notification_type: type of notification, based on that we
            pick templates

        :param recipients: list of int, str or User objects, when None
            is given send to all admins
        :param mention_recipients: list of int, str or User objects,
            that were mentioned
        :param with_email: send email with this notification
        :param email_kwargs: dict with arguments to generate email
        """

        from rhodecode.lib.celerylib import tasks, run_task

        if recipients and not getattr(recipients, '__iter__', False):
            raise Exception('recipients must be an iterable object')

        created_by_obj = self._get_user(created_by)
        # default MAIN body if not given
        email_kwargs = email_kwargs or {'body': notification_body}
        mention_recipients = mention_recipients or set()

        if not created_by_obj:
            raise Exception('unknown user %s' % created_by)

        if recipients is None:
            # recipients is None means to all admins
            recipients_objs = User.query().filter(User.admin == true()).all()
            log.debug('sending notifications %s to admins: %s',
                      notification_type, recipients_objs)
        else:
            recipients_objs = []
            for u in recipients:
                obj = self._get_user(u)
                if obj:
                    recipients_objs.append(obj)
                else:  # we didn't find this user, log the error and carry on
                    log.error('cannot notify unknown user %r', u)

            recipients_objs = set(recipients_objs)
            if not recipients_objs:
                raise Exception('no valid recipients specified')

            log.debug('sending notifications %s to %s', notification_type,
                      recipients_objs)

        # add mentioned users into recipients
        final_recipients = set(recipients_objs).union(mention_recipients)
        notification = Notification.create(created_by=created_by_obj,
                                           subject=notification_subject,
                                           body=notification_body,
                                           recipients=final_recipients,
                                           type_=notification_type)

        if not with_email:  # skip sending email, and just create notification
            return notification

        # don't send email to person who created this comment
        rec_objs = set(recipients_objs).difference(set([created_by_obj]))

        # now notify all recipients in question

        for recipient in rec_objs.union(mention_recipients):
            # inject current recipient
            email_kwargs['recipient'] = recipient
            email_kwargs['mention'] = recipient in mention_recipients
            (subject, headers, email_body,
             email_body_plaintext) = EmailNotificationModel().render_email(
                 notification_type, **email_kwargs)

            log.debug('Creating notification email task for user:`%s`',
                      recipient)
            task = run_task(tasks.send_email, recipient.email, subject,
                            email_body_plaintext, email_body)
            log.debug('Created email task: %s', task)

        return notification
示例#37
0
    def index(self):
        """GET /users: All items in the collection"""
        # url('users')

        from rhodecode.lib.utils import PartialRenderer
        _render = PartialRenderer('data_table/_dt_elements.html')

        def grav_tmpl(user_email, size):
            return _render("user_gravatar", user_email, size)

        def username(user_id, username):
            return _render("user_name", user_id, username)

        def user_actions(user_id, username):
            return _render("user_actions", user_id, username)

        # json generate
        c.users_list = User.query()\
            .filter(User.username != User.DEFAULT_USER) \
            .all()

        users_data = []
        for user in c.users_list:
            users_data.append({
                "gravatar":
                grav_tmpl(user.email, 20),
                "username":
                h.link_to(user.username,
                          h.url('user_profile', username=user.username)),
                "username_raw":
                user.username,
                "email":
                user.email,
                "first_name":
                h.escape(user.name),
                "last_name":
                h.escape(user.lastname),
                "last_login":
                h.format_date(user.last_login),
                "last_login_raw":
                datetime_to_time(user.last_login),
                "last_activity":
                h.format_date(
                    h.time_to_datetime(user.user_data.get('last_activity',
                                                          0))),
                "last_activity_raw":
                user.user_data.get('last_activity', 0),
                "active":
                h.bool2icon(user.active),
                "active_raw":
                user.active,
                "admin":
                h.bool2icon(user.admin),
                "admin_raw":
                user.admin,
                "extern_type":
                user.extern_type,
                "extern_name":
                user.extern_name,
                "action":
                user_actions(user.user_id, user.username),
            })

        c.data = json.dumps(users_data)
        return render('admin/users/users.html')
示例#38
0
    def create(self,
               created_by,
               subject,
               body,
               recipients=None,
               type_=Notification.TYPE_MESSAGE,
               with_email=True,
               email_kwargs={},
               email_subject=None):
        """

        Creates notification of given type

        :param created_by: int, str or User instance. User who created this
            notification
        :param subject:
        :param body:
        :param recipients: list of int, str or User objects, when None
            is given send to all admins
        :param type_: type of notification
        :param with_email: send email with this notification
        :param email_kwargs: additional dict to pass as args to email template
        :param email_subject: use given subject as email subject
        """
        from rhodecode.lib.celerylib import tasks, run_task

        if recipients and not getattr(recipients, '__iter__', False):
            raise Exception('recipients must be a list or iterable')

        created_by_obj = self._get_user(created_by)

        if recipients:
            recipients_objs = []
            for u in recipients:
                obj = self._get_user(u)
                if obj:
                    recipients_objs.append(obj)
                else:
                    # TODO: inform user that requested operation couldn't be completed
                    log.error('cannot email unknown user %r', u)
            recipients_objs = set(recipients_objs)
            log.debug('sending notifications %s to %s' %
                      (type_, recipients_objs))
        else:
            # empty recipients means to all admins
            recipients_objs = User.query().filter(User.admin == True).all()
            log.debug('sending notifications %s to admins: %s' %
                      (type_, recipients_objs))
        # TODO: inform user who are notified
        notif = Notification.create(created_by=created_by_obj,
                                    subject=subject,
                                    body=body,
                                    recipients=recipients_objs,
                                    type_=type_)

        if not with_email:
            return notif

        #don't send email to person who created this comment
        rec_objs = set(recipients_objs).difference(set([created_by_obj]))

        # send email with notification to all other participants
        for rec in rec_objs:
            if not email_subject:
                email_subject = NotificationModel()\
                                    .make_description(notif, show_age=False)
            type_ = type_
            email_body = None  # we set body to none, we just send HTML emails
            ## this is passed into template
            kwargs = {'subject': subject, 'body': h.rst_w_mentions(body)}
            kwargs.update(email_kwargs)
            email_body_html = EmailNotificationModel()\
                                .get_email_tmpl(type_, **kwargs)

            run_task(tasks.send_email, rec.email, email_subject, email_body,
                     email_body_html)

        return notif