Ejemplo n.º 1
0
    def auth_settings(self):
        try:
            form = AuthSettingsForm()()
            form_result = form.to_python(self.request.params)
            plugins = ','.join(form_result['auth_plugins'])
            setting = SettingsModel().create_or_update_setting(
                'auth_plugins', plugins)
            Session().add(setting)
            Session().commit()

            cache_manager = get_auth_cache_manager()
            cache_manager.clear()
            self.request.session.flash(
                _('Auth settings updated successfully.'), queue='success')
        except formencode.Invalid as errors:
            e = errors.error_dict or {}
            self.request.session.flash(_(
                'Errors exist when saving plugin setting. '
                'Please check the form inputs.'),
                                       queue='error')
            return self.index(defaults=errors.value,
                              errors=e,
                              prefix_error=False)
        except Exception:
            log.exception('Exception in auth_settings')
            self.request.session.flash(
                _('Error occurred during update of auth settings.'),
                queue='error')

        redirect_to = self.request.resource_path(self.context,
                                                 route_name='auth_home')
        return HTTPFound(redirect_to)
Ejemplo n.º 2
0
class AuthnPluginSettingsSchemaBase(colander.MappingSchema):
    """
    This base schema is intended for use in authentication plugins.
    It adds a few default settings (e.g., "enabled"), so that plugin
    authors don't have to maintain a bunch of boilerplate.
    """
    enabled = colander.SchemaNode(
        colander.Bool(),
        default=False,
        description=_('Enable or disable this authentication plugin.'),
        missing=False,
        title=_('Enabled'),
        widget='bool',
    )
    cache_ttl = colander.SchemaNode(
        colander.Int(),
        default=0,
        description=_('Amount of seconds to cache the authentication '
                      'call for this plugin. Useful for long calls like '
                      'LDAP to improve the responsiveness of the '
                      'authentication system (0 means disabled).'),
        missing=0,
        title=_('Auth Cache TTL'),
        validator=colander.Range(min=0, max=None),
        widget='int',
    )
Ejemplo n.º 3
0
    def password_reset(self):
        settings = SettingsModel().get_all_settings()
        captcha_private_key = settings.get('rhodecode_captcha_private_key')
        captcha_active = bool(captcha_private_key)
        captcha_public_key = settings.get('rhodecode_captcha_public_key')

        render_ctx = {
            'captcha_active': captcha_active,
            'captcha_public_key': captcha_public_key,
            'defaults': {},
            'errors': {},
        }

        if self.request.POST:
            password_reset_form = PasswordResetForm()()
            try:
                form_result = password_reset_form.to_python(
                    self.request.params)
                if captcha_active:
                    response = submit(
                        self.request.params.get('recaptcha_challenge_field'),
                        self.request.params.get('recaptcha_response_field'),
                        private_key=captcha_private_key,
                        remoteip=get_ip_addr(self.request.environ))
                    if captcha_active and not response.is_valid:
                        _value = form_result
                        _msg = _('bad captcha')
                        error_dict = {'recaptcha_field': _msg}
                        raise formencode.Invalid(_msg, _value, None,
                                                 error_dict=error_dict)

                # Generate reset URL and send mail.
                user_email = form_result['email']
                user = User.get_by_email(user_email)
                password_reset_url = self.request.route_url(
                    'reset_password_confirmation',
                    _query={'key': user.api_key})
                UserModel().reset_password_link(
                    form_result, password_reset_url)

                # Display success message and redirect.
                self.session.flash(
                    _('Your password reset link was sent'),
                    queue='success')
                return HTTPFound(self.request.route_path('login'))

            except formencode.Invalid as errors:
                render_ctx.update({
                    'defaults': errors.value,
                    'errors': errors.error_dict,
                })

        return render_ctx
Ejemplo n.º 4
0
    def register_post(self):
        captcha_private_key = SettingsModel().get_setting_by_name(
            'rhodecode_captcha_private_key')
        captcha_active = bool(captcha_private_key)
        auto_active = 'hg.register.auto_activate' in User.get_default_user()\
            .AuthUser.permissions['global']

        register_form = RegisterForm()()
        try:
            form_result = register_form.to_python(self.request.params)
            form_result['active'] = auto_active

            if captcha_active:
                response = submit(
                    self.request.params.get('recaptcha_challenge_field'),
                    self.request.params.get('recaptcha_response_field'),
                    private_key=captcha_private_key,
                    remoteip=get_ip_addr(self.request.environ))
                if captcha_active and not response.is_valid:
                    _value = form_result
                    _msg = _('bad captcha')
                    error_dict = {'recaptcha_field': _msg}
                    raise formencode.Invalid(_msg, _value, None,
                                             error_dict=error_dict)

            new_user = UserModel().create_registration(form_result)
            event = UserRegistered(user=new_user, session=self.session)
            self.request.registry.notify(event)
            self.session.flash(
                _('You have successfully registered with RhodeCode'),
                queue='success')
            Session().commit()

            redirect_ro = self.request.route_path('login')
            raise HTTPFound(redirect_ro)

        except formencode.Invalid as errors:
            del errors.value['password']
            del errors.value['password_confirmation']
            return self.register(
                defaults=errors.value, errors=errors.error_dict)

        except UserCreationError as e:
            # container auth or other auth functions that create users on
            # the fly can throw this exception signaling that there's issue
            # with user creation, explanation should be provided in
            # Exception itself
            self.session.flash(e, queue='error')
            return self.register()
Ejemplo n.º 5
0
class HeadersSettingsSchema(AuthnPluginSettingsSchemaBase):
    header = colander.SchemaNode(
        colander.String(),
        default='REMOTE_USER',
        description=_('Header to extract the user from'),
        preparer=strip_whitespace,
        title=_('Header'),
        widget='string')
    fallback_header = colander.SchemaNode(
        colander.String(),
        default='HTTP_X_FORWARDED_USER',
        description=_('Header to extract the user from when main one fails'),
        preparer=strip_whitespace,
        title=_('Fallback header'),
        widget='string')
    clean_username = colander.SchemaNode(
        colander.Boolean(),
        default=True,
        description=_('Perform cleaning of user, if passed user has @ in '
                      'username then first part before @ is taken. '
                      'If there\'s \\ in the username only the part after '
                      ' \\ is taken'),
        missing=False,
        title=_('Clean username'),
        widget='bool')
Ejemplo n.º 6
0
    def password_reset_confirmation(self):
        if self.request.GET and self.request.GET.get('key'):
            try:
                user = User.get_by_auth_token(self.request.GET.get('key'))
                data = {'email': user.email}
                UserModel().reset_password(data)
                self.session.flash(
                    _('Your password reset was successful, '
                      'a new password has been sent to your email'),
                    queue='success')
            except Exception as e:
                log.error(e)
                return HTTPFound(self.request.route_path('reset_password'))

        return HTTPFound(self.request.route_path('login'))
Ejemplo n.º 7
0
    def settings_post(self):
        """
        View that validates and stores the plugin settings.
        """
        schema = self.plugin.get_settings_schema()
        data = self.request.params

        try:
            valid_data = schema.deserialize(data)
        except colander.Invalid, e:
            # Display error message and display form again.
            self.request.session.flash(_(
                'Errors exist when saving plugin settings. '
                'Please check the form inputs.'),
                                       queue='error')
            defaults = {key: data[key] for key in data if key in schema}
            return self.settings_get(errors=e.asdict(), defaults=defaults)
Ejemplo n.º 8
0
class NavigationRegistry(object):

    _base_entries = [
        NavEntry('global', _('Global'), 'admin_settings_global'),
        NavEntry('vcs', _('VCS'), 'admin_settings_vcs'),
        NavEntry('visual', _('Visual'), 'admin_settings_visual'),
        NavEntry('mapping', _('Remap and Rescan'), 'admin_settings_mapping'),
        NavEntry('issuetracker', _('Issue Tracker'),
                 'admin_settings_issuetracker'),
        NavEntry('email', _('Email'), 'admin_settings_email'),
        NavEntry('hooks', _('Hooks'), 'admin_settings_hooks'),
        NavEntry('search', _('Full Text Search'), 'admin_settings_search'),
        NavEntry('system', _('System Info'), 'admin_settings_system'),
        NavEntry('open_source', _('Open Source Licenses'),
                 'admin_settings_open_source', pyramid=True),
        # TODO: marcink: we disable supervisor now until the supervisor stats
        # page is fixed in the nix configuration
        # NavEntry('supervisor', _('Supervisor'), 'admin_settings_supervisor'),
    ]

    _labs_entry = NavEntry('labs', _('Labs'),
                           'admin_settings_labs')

    def __init__(self, labs_active=False):
        self._registered_entries = collections.OrderedDict([
            (item.key, item) for item in self.__class__._base_entries
        ])

        if labs_active:
            self.add_entry(self._labs_entry)

    def add_entry(self, entry):
        self._registered_entries[entry.key] = entry

    def get_navlist(self, request):
        navlist = [NavListEntry(i.key, i.name, i.generate_url(request))
                   for i in self._registered_entries.values()]
        return navlist
Ejemplo n.º 9
0
 def get_display_name(self):
     return _('Rhodecode Token Auth')
Ejemplo n.º 10
0
class AuthnPluginViewBase(object):
    def __init__(self, context, request):
        self.request = request
        self.context = context
        self.plugin = context.plugin
        self._rhodecode_user = request.user

    @LoginRequired()
    @HasPermissionAllDecorator('hg.admin')
    def settings_get(self, defaults=None, errors=None):
        """
        View that displays the plugin settings as a form.
        """
        defaults = defaults or {}
        errors = errors or {}
        schema = self.plugin.get_settings_schema()

        # Compute default values for the form. Priority is:
        # 1. Passed to this method 2. DB value 3. Schema default
        for node in schema:
            if node.name not in defaults:
                defaults[node.name] = self.plugin.get_setting_by_name(
                    node.name, node.default)

        template_context = {
            'defaults': defaults,
            'errors': errors,
            'plugin': self.context.plugin,
            'resource': self.context,
        }

        return template_context

    @LoginRequired()
    @HasPermissionAllDecorator('hg.admin')
    @auth.CSRFRequired()
    def settings_post(self):
        """
        View that validates and stores the plugin settings.
        """
        schema = self.plugin.get_settings_schema()
        data = self.request.params

        try:
            valid_data = schema.deserialize(data)
        except colander.Invalid, e:
            # Display error message and display form again.
            self.request.session.flash(_(
                'Errors exist when saving plugin settings. '
                'Please check the form inputs.'),
                                       queue='error')
            defaults = {key: data[key] for key in data if key in schema}
            return self.settings_get(errors=e.asdict(), defaults=defaults)

        # Store validated data.
        for name, value in valid_data.items():
            self.plugin.create_or_update_setting(name, value)
        Session.commit()

        # Display success message and redirect.
        self.request.session.flash(_('Auth settings updated successfully.'),
                                   queue='success')
        redirect_to = self.request.resource_path(self.context,
                                                 route_name='auth_home')
        return HTTPFound(redirect_to)
Ejemplo n.º 11
0
 def __init__(self):
     self._store = {}
     self._resource_name_map = {}
     self.display_name = _('Global')
Ejemplo n.º 12
0
 def get_display_name(self):
     return _('Headers')