Example #1
0
 def test_authenticated_user(self):
     environ = make_environ('gustavo')
     p = predicates.is_anonymous()
     self.eval_unmet_predicate(p, environ,
                               'The current user must be anonymous')
Example #2
0
 def test_anonymous_user(self):
     environ = {}
     p = predicates.is_anonymous()
     self.eval_met_predicate(p, environ)
Example #3
0
class RootController(StandardController):
    """
    The root controller for the tracim application.

    All the other controllers and WSGI applications should be mounted on this
    controller. For example::

        panel = ControlPanelController()
        another_app = AnotherWSGIApplication()

    Keep in mind that WSGI applications shouldn't be mounted directly: They
    must be wrapped around with :class:`tg.controllers.WSGIAppController`.
    """

    admin = AdminController()
    help = HelpController()
    calendar = CalendarController()
    calendar_config = CalendarConfigController()

    debug = DebugController()
    error = ErrorController()

    # Rest controllers
    workspaces = UserWorkspaceRestController()
    user = UserRestController()
    previews = PreviewsController()

    content = ContentController()
    events = EventRestController()
    # api
    api = APIController()

    def _render_response(self, tgl, controller, response):
        replace_reset_password_templates(controller.decoration.engines)
        return super()._render_response(tgl, controller, response)

    def _before(self, *args, **kw):
        super(RootController, self)._before(args, kw)
        tmpl_context.project_name = "tracim"

    @expose('tracim.templates.index')
    def index(self, came_from='', *args, **kwargs):
        if request.identity:
            if came_from:
                logger.info(self, 'Will redirect to {}'.format(came_from))
                redirect(url(came_from))
            else:
                redirect(self.url(None, self.home.__name__))

        login_counter = request.environ.get('repoze.who.logins', 0)
        if login_counter > 0:
            flash(_('Wrong credentials'), CST.STATUS_ERROR)
        return dict(page='login',
                    login_counter=str(login_counter),
                    came_from=came_from)

    @require(predicates.is_anonymous())
    @expose('tracim.templates.index')
    def login(self, *args, **kwargs):
        """
        This method is there for backward compatibility only
        This is related to the default TG2 authentication behavior...
        Now the login form is included in home page
        :param args:
        :param kwargs:
        :return:
        """
        came_from = kwargs['came_from'] if 'came_from' in kwargs.keys() else ''
        logger.info(self, 'came_from: {}'.format(kwargs))
        return self.index(came_from, args, *kwargs)

    @expose()
    def post_login(self, came_from=lurl('/home')):
        """
        Redirect the user to the initially requested page on successful
        authentication or redirect her back to the login page if login failed.
        """
        if not request.identity:
            login_counter = request.environ.get('repoze.who.logins', 0) + 1
            redirect(url('/login'),
                     params=dict(came_from=came_from, __logins=login_counter))

        user = CurrentUserGetterApi.get_current_user()

        flash(_('Welcome back, %s!') % user.get_display_name())
        redirect(came_from)

    @expose()
    def post_logout(self, came_from=lurl('/')):
        """
        Redirect the user to the initially requested page on logout and say
        goodbye as well.
        """
        flash(_('Successfully logged out. We hope to see you soon!'))
        redirect(came_from)

    @require(predicates.not_anonymous())
    @expose('tracim.templates.home')
    def home(self):
        user = tmpl_context.current_user

        current_user_content = Context(CTX.CURRENT_USER).toDict(user)
        fake_api = Context(CTX.CURRENT_USER).toDict(
            {'current_user': current_user_content})

        last_active_contents = ContentApi(user).get_last_active(
            None, ContentType.Any, None)
        fake_api.last_actives = Context(CTX.CONTENT_LIST).toDict(
            last_active_contents, 'contents', 'nb')

        unread_contents = ContentApi(user).get_last_unread(
            None, ContentType.Any, None)
        fake_api.last_unread = Context(CTX.CONTENT_LIST).toDict(
            unread_contents, 'contents', 'nb')

        # INFO - D.A. - 2015-05-20
        # For now, we do not have favorties and read/unread status
        # so we only show:
        # - workspaces
        # - last activity
        # - oldest open stuff

        items = ContentApi(user).get_all_without_exception(
            ContentType.Any, None)[:4]
        fake_api.favorites = Context(CTX.CONTENT_LIST).toDict(
            items, 'contents', 'nb')
        return DictLikeClass(fake_api=fake_api)

    @require(predicates.not_anonymous())
    @expose('tracim.templates.search.display')
    def search(self, keywords=''):
        from tracim.lib.content import ContentApi

        user = tmpl_context.current_user
        api = ContentApi(user)

        items = []
        keyword_list = api.get_keywords(keywords)

        result = api.search(keyword_list)
        if result:
            items = result.limit(ContentApi.SEARCH_DEFAULT_RESULT_NB).all()
        api.exclude_unavailable(items)

        current_user_content = Context(CTX.CURRENT_USER).toDict(user)
        fake_api = Context(CTX.CURRENT_USER).toDict(
            {'current_user': current_user_content})

        search_results = Context(CTX.SEARCH).toDict(items, 'results',
                                                    'result_nb')
        search_results.keywords = keyword_list

        return DictLikeClass(fake_api=fake_api, search=search_results)
Example #4
0
 def test_anonymous_user(self):
     environ = {}
     p = predicates.is_anonymous()
     self.eval_met_predicate(p, environ)
Example #5
0
 def test_authenticated_user(self):
     environ = make_environ('gustavo')
     p = predicates.is_anonymous()
     self.eval_unmet_predicate(p, environ,
         'The current user must be anonymous')
Example #6
0
   def index(self):
      """Handle the front-page."""
      if is_anonymous(msg=u'Veuiller vous connecter pour continuer'):
         redirect('/login')

      return dict(title="Portail Asterisk", page='index')
Example #7
0
class ResetRequestController(BaseController):
    allow_only = is_anonymous()

    @expose('contacts.templates.reset_password.reset_response')
    def reset_response(self, title=None, message=None):
        return dict(page='bad_token', title=title, message=message)

    @expose('contacts.templates.reset_password.new_password')
    def new_password(self, token, message=None):
        '''
        Starts the new password procedure if token is valid
        '''
        reset_request = ResetRequest.get_by_token(token)

        # token is wrong or it's expired
        if reset_request is None or reset_request.check_token_age() == False:
            if reset_request is not None:
                DBSession.delete(reset_request)
            title = _("Bad token")
            message = _("The token %s doesn't exist or it's expired") % token
            redirect('/reset_password/reset_response',
                     params={
                         'title': title,
                         'message': message
                     })

        if message is not None and message == 'passwords-not-match':
            flash(_("Passwords provided don't match."), 'error')

        return dict(page='new_password',
                    token=token,
                    email_address=reset_request.user.email_address)

    @expose('contacts.templates.reset_password.reset_password')
    def reset_request(self,
                      failure=None,
                      email_address=None,
                      error_message=None):
        '''
        Starts the reset password procedure
        '''
        if failure is not None:
            if failure == 'user-not-found':
                flash(
                    _("We don't have a user with %s as email address.") %
                    email_address, 'error')
            if failure == 'request-already-present':
                flash(
                    _("A reset request for %s was already present. We sent the email again, check your inbox"
                      ) % email_address, 'info')
            if failure == 'email-error':
                flash_string = _(
                    "Error sending the reset request, try again later.")
                if error_message is not None:
                    flash_string += _("The error was %s") & error_message
                flash(flash_string, 'error')
        if failure is None and email_address is not None:
            flash(
                _("A message with the link for the reset was sent to %s.") %
                email_address, 'info')
        return dict(page='reset_password', email_address=email_address)

    @expose()
    def reset_submission(self, email_address):
        '''
        Manage password reset submission
        '''
        user = User.by_email_address(email_address)
        if not user:
            redirect(
                '/reset_password/reset_request/?failure=user-not-found&email_address='
                + email_address)
        reset_request = ResetRequest.get_by_user(user.user_id)
        already_present = False
        result = False
        message = ''
        if reset_request:
            already_present = True
            result, message = reset_request.send_reset_link()
        else:
            reset_request = ResetRequest(user_id=user.user_id)
            DBSession.add(reset_request)
            DBSession.flush()
            reset_request = ResetRequest.get_by_user(user.user_id)
            result, message = reset_request.send_reset_link()

        if result:
            if already_present:
                redirect(
                    '/reset_password/reset_request/?failure=request-already-present&email_address='
                    + email_address)
            else:
                redirect('/reset_password/reset_request/?email_address=' +
                         email_address)
        else:
            redirect(
                '/reset_password/reset_request/?failure=email-error&error_message='
                + message)

    @expose()
    def save_password(self, password, check_password, email_address):
        user = User.by_email_address(email_address)
        if password == check_password:
            user._set_password(password)
            user.reset_requests[0].activated = True
            title = _("Password updated succesfully")
            message = _("The password for %s updated, proceed to login."
                        ) % email_address
            redirect('/reset_password/reset_response',
                     params={
                         'title': title,
                         'message': message
                     })
        else:
            token = user.reset_requests[0].token
            redirect('/reset_password/new_password',
                     params={
                         'token': token,
                         'message': 'passwords-not-match'
                     })