def challenge(self, environ, status, app_headers, forget_headers):

        # This challenge consists of logging out
        if environ.has_key('rwpc.logout'):
            log.warn("Headers before logout: " + str(app_headers))
            app_headers = [(a, b) for a, b in app_headers \
                           if a.lower() != 'location' ]
            log.warn("Headers after logout: " + str(app_headers))

            logout_url = '{cas_url}logout?service={service_url}'.format(
                cas_url=self.cas_url,
                service_url=urllib.quote(environ['rwpc.logout']))

            # FIXME: should Location replace the key rwpc.logout?
            headers = [('Location', logout_url)]
            headers = headers + app_headers + forget_headers

            log.warn("Logout headers: " + str(headers))

            return HTTPFound(headers=headers)

        # Perform a real challenge by redirecting the user to CAS
        else:
            login_url = '{cas_url}login?service={service_url}'.format(
                cas_url=self.cas_url,
                service_url=urllib.quote(self._serviceURL(environ)))

            log.warn('Login URL: ' + login_url)

            headers = [('Location', login_url)]
            cookies = [(h,v) for (h,v) in app_headers \
                       if h.lower() == 'set-cookie']
            headers = headers + forget_headers + cookies

            return HTTPFound(headers=headers)
Example #2
0
    def create_new_iteration(self, old_pull_request, new_rev, title,
                             description, reviewers):
        owner = User.get(request.authuser.user_id)
        new_org_rev = self._get_ref_rev(old_pull_request.org_repo, 'rev',
                                        new_rev)
        new_other_rev = self._get_ref_rev(old_pull_request.other_repo,
                                          old_pull_request.other_ref_parts[0],
                                          old_pull_request.other_ref_parts[1])
        try:
            cmd = CreatePullRequestIterationAction(old_pull_request,
                                                   new_org_rev, new_other_rev,
                                                   title, description, owner,
                                                   reviewers)
        except CreatePullRequestAction.ValidationError as e:
            h.flash(e, category='error', logf=log.error)
            raise HTTPNotFound

        try:
            pull_request = cmd.execute()
            Session().commit()
        except Exception:
            h.flash(_('Error occurred while creating pull request'),
                    category='error')
            log.error(traceback.format_exc())
            raise HTTPFound(location=old_pull_request.url())

        h.flash(_('New pull request iteration created'), category='success')
        raise HTTPFound(location=pull_request.url())
Example #3
0
 def challenge(self, environ, status, app_headers, forget_headers):
     """challenge"""
     req = Request(environ)
     if req.path in [self.logout_handler_path, self.post_logout_url]:
         headers = app_headers + forget_headers
         return HTTPFound(headers=headers)
     else:
         came_from = get_came_from(environ)
         logger.debug("[saml2.challenge] RelayState >> '%s'", came_from)
         login = Login(self.server)
         try:
             login.initAuthnRequest()
             login.buildAuthnRequestMsg()
             logger.debug(
                 "[saml2.challenge] RequestID: %r", login.request.iD
             )
             headers = [('Location', login.msgUrl)]
             logger.debug(
                 "[saml2.challenge] Redirected to: %s", login.msgUrl
             )
             cookies = [
                 (_hdr, _val) for (_hdr, _val) in app_headers
                 if _hdr.lower() == 'set-cookie'
             ]
             headers = headers + forget_headers + cookies
             return HTTPFound(headers=headers)
         except Error as msg:
             logger.debug("[saml2.challenge] error: %s", msg)
             raise
Example #4
0
    def delete(self, group_name):
        gr = c.repo_group = RepoGroup.guess_instance(group_name)
        repos = gr.repositories.all()
        if repos:
            h.flash(_('This group contains %s repositories and cannot be '
                      'deleted') % len(repos),
                    category='warning')
            raise HTTPFound(location=url('repos_groups'))

        children = gr.children.all()
        if children:
            h.flash(
                _('This group contains %s subgroups and cannot be deleted' %
                  (len(children))),
                category='warning')
            raise HTTPFound(location=url('repos_groups'))

        try:
            RepoGroupModel().delete(group_name)
            Session().commit()
            h.flash(_('Removed repository group %s') % group_name,
                    category='success')
            #TODO: in future action_logger(, '', '', '')
        except Exception:
            log.error(traceback.format_exc())
            h.flash(
                _('Error occurred during deletion of repository group %s') %
                group_name,
                category='error')

        if gr.parent_group:
            raise HTTPFound(location=url(
                'repos_group_home', group_name=gr.parent_group.group_name))
        raise HTTPFound(location=url('repos_groups'))
Example #5
0
    def update_perms(self, group_name):
        """
        Update permissions for given repository group

        :param group_name:
        """

        c.repo_group = RepoGroup.guess_instance(group_name)
        valid_recursive_choices = ['none', 'repos', 'groups', 'all']
        form_result = RepoGroupPermsForm(valid_recursive_choices)().to_python(
            request.POST)
        if not request.authuser.is_admin:
            if self._revoke_perms_on_yourself(form_result):
                msg = _('Cannot revoke permission for yourself as admin')
                h.flash(msg, category='warning')
                raise HTTPFound(location=url('edit_repo_group_perms',
                                             group_name=group_name))
        recursive = form_result['recursive']
        # iterate over all members(if in recursive mode) of this groups and
        # set the permissions !
        # this can be potentially heavy operation
        RepoGroupModel()._update_permissions(c.repo_group,
                                             form_result['perms_new'],
                                             form_result['perms_updates'],
                                             recursive)
        #TODO: implement this
        #action_logger(request.authuser, 'admin_changed_repo_permissions',
        #              repo_name, request.ip_addr)
        Session().commit()
        h.flash(_('Repository group permissions updated'), category='success')
        raise HTTPFound(
            location=url('edit_repo_group_perms', group_name=group_name))
Example #6
0
def view_login_redirect(request):
    
    user_id = authenticated_userid(request)
    if user_id:
        return HTTPFound(location = request.application_url)
    else:
        return HTTPFound(location = request.application_url + '/login?failed=1')  
Example #7
0
def pastebin_manage_view(context, request):
    params = request.params
    message = params.get('message', u'')

    if params.has_key('form.submitted'):
        form = marshal(request.environ, request.body_file)
        checkboxes = form.get('delete', [])
        for checkbox in checkboxes:
            del context[checkbox]
        message = '%s pastes deleted' % len(checkboxes)
        url = resource_url(context, request, 'manage',
                           query={'message':message})
        response = HTTPFound(location=url)
        response.headers['Location'] = url
        return response

    pastebin_url = resource_url(context, request)
    pastes = utils.get_pastes(context, request, sys.maxint)

    return dict(
        api = utils.API(context, request),
        pastes = pastes,
        message = message,
        pastebin_url = pastebin_url,
        )
Example #8
0
def pastebin_view(context, request):
    params = request.params
    author_name = utils.preferred_author(context, request)
    language = u''
    paste = u''
    message = u''
    pastebin_url = resource_url(context, request)
    can_manage = has_permission('manage', context, request)

    if params.has_key('form.submitted'):
        if params.get('text'): # trap spambots
            return HTTPFound(location=resource_url(context, request))
        paste = params.get('paste_', '')
        author_name = params.get('author_name_', '')
        language = params.get('language_', '')
        schema = PasteAddSchema()
        message = None
        try:
            schema.to_python(request.params)
        except formencode.validators.Invalid, why:
            message = str(why)
        else:
            pobj = PasteEntry(author_name, paste, language)
            pasteid = context.add_item(pobj)
            url = '%s%s' % (pastebin_url, pasteid)
            response = HTTPFound(location=url)
            response.set_cookie(utils.COOKIE_AUTHOR, author_name,
                                max_age=864000)
            response.set_cookie(utils.COOKIE_LANGUAGE, language)
            return response
Example #9
0
    def create(self):
        self.__load_defaults()
        try:
            # CanWriteGroup validators checks permissions of this POST
            form_result = RepoForm(repo_groups=c.repo_groups,
                                   landing_revs=c.landing_revs_choices)() \
                            .to_python(dict(request.POST))
        except formencode.Invalid as errors:
            log.info(errors)
            return htmlfill.render(render('admin/repos/repo_add.html'),
                                   defaults=errors.value,
                                   errors=errors.error_dict or {},
                                   prefix_error=False,
                                   force_defaults=False,
                                   encoding="UTF-8")

        try:
            # create is done sometimes async on celery, db transaction
            # management is handled there.
            task = RepoModel().create(form_result, request.authuser.user_id)
            task_id = task.task_id
        except Exception:
            log.error(traceback.format_exc())
            msg = (_('Error creating repository %s') %
                   form_result.get('repo_name'))
            h.flash(msg, category='error')
            raise HTTPFound(location=url('home'))

        raise HTTPFound(location=h.url('repo_creating_home',
                                       repo_name=form_result['repo_name_full'],
                                       task_id=task_id))
Example #10
0
def delete_photo_view(request, photo):
    request.app_context.catalog.unindex(photo)
    trash = find_trash(photo)
    trash_id = trash.trash(photo)
    response = HTTPFound(location=model_url(request, photo.__parent__))
    response.set_cookie('undo', 'trash:%s|Photo+deleted.' % trash_id)
    return response
Example #11
0
def journal_add_view(context, request):

    if IJournalEntry.providedBy(context):
        entry = context
        project = context.__parent__.__parent__
        add_form = False
    else:
        entry = JournalEntry()
        project = context
        add_form = True

    errors = {}
    defaults = {}

    if 'form.submitted' in request.POST:
        try:
            # FormEncode validation
            defaults = dict(request.POST)
            defaults['indicators'] = request.POST.get('indicators')
            form_result = entry_schema.to_python(request.POST)
        except formencode.validators.Invalid, why:
            errors = why.error_dict
        else:

            session = DBSession()

            # Handle image upload
            if form_result['image'] is not None:
                entry.image = File('image.jpg', form_result['image'].read())

            elif form_result['image_action'] == 'delete' and entry.image:
                session.delete(entry.image)

            entry.date = datetime.now()
            entry.text = form_result['text']
            entry.user = authenticated_user(request)

            # Check whether indicator belongs to this project.
            indicator_query = session.query(Indicator)
            indicator_query = indicator_query.filter(Project.id == project.id)
            indicator_query = indicator_query.join(Project.objectives)
            indicator_query = indicator_query.join(Objective.competences)
            indicator_query = indicator_query.join(Competence.indicator_sets)
            indicator_query = indicator_query.join(IndicatorSet.indicators)
            if form_result['indicators']:
                indicator_query = indicator_query.filter(
                    Indicator.id.in_(form_result['indicators']))
                indicators = indicator_query.all()
                entry.indicators = indicators

            if add_form:
                project.journal_entries.append(entry)

            if ITeacher.providedBy(authenticated_user(request)):
                return HTTPFound(location=model_url(
                    get_root(request)['projects'][project.id], request))
            return HTTPFound(
                location=model_url(authenticated_user(request), request))
Example #12
0
    def delete(self, repo_name, revision, f_path):
        repo = c.db_repo
        if repo.enable_locking and repo.locked[0]:
            h.flash(_('This repository has been locked by %s on %s')
                % (h.person_by_id(repo.locked[0]),
                   h.fmt_date(h.time_to_datetime(repo.locked[1]))),
                'warning')
            raise HTTPFound(location=h.url('files_home',
                                  repo_name=repo_name, revision='tip'))

        # check if revision is a branch identifier- basically we cannot
        # create multiple heads via file editing
        _branches = repo.scm_instance.branches
        # check if revision is a branch name or branch hash
        if revision not in _branches.keys() + _branches.values():
            h.flash(_('You can only delete files with revision '
                      'being a valid branch'), category='warning')
            raise HTTPFound(location=h.url('files_home',
                                  repo_name=repo_name, revision='tip',
                                  f_path=f_path))

        r_post = request.POST

        c.cs = self.__get_cs(revision)
        c.file = self.__get_filenode(c.cs, f_path)

        c.default_message = _('Deleted file %s via Kallithea') % (f_path)
        c.f_path = f_path
        node_path = f_path
        author = request.authuser.full_contact

        if r_post:
            message = r_post.get('message') or c.default_message

            try:
                nodes = {
                    node_path: {
                        'content': ''
                    }
                }
                self.scm_model.delete_nodes(
                    user=request.authuser.user_id, repo=c.db_repo,
                    message=message,
                    nodes=nodes,
                    parent_cs=c.cs,
                    author=author,
                )

                h.flash(_('Successfully deleted file %s') % f_path,
                        category='success')
            except Exception:
                log.error(traceback.format_exc())
                h.flash(_('Error occurred during commit'), category='error')
            raise HTTPFound(location=url('changeset_home',
                                repo_name=c.repo_name, revision='tip'))

        return render('files/files_delete.html')
Example #13
0
def members_view(context, request):

    session = DBSession()
    all_students = session.query(Student).all()
    all_students = [
        student for student in all_students if not student in context.students
    ]
    all_teachers = session.query(Teacher).all()
    all_teachers = [
        teacher for teacher in all_teachers if not teacher in context.teachers
    ]

    if 'form.submitted' in request.POST:
        student_id = request.POST.get('student_id', None)
        if student_id:
            student = session.query(Student).filter_by(id=student_id).first()
            if student:
                context.students.append(student)
        teacher_id = request.POST.get('teacher_id', None)
        if teacher_id:
            teacher = session.query(Teacher).filter_by(id=teacher_id).first()
            if teacher:
                context.teachers.append(teacher)

        return HTTPFound(location=model_url(context, request, 'members.html'))
    # This should be a post request, but it has to be finished today ...
    elif 'remove_student' in request.GET:
        student_id = request.GET.get('remove_student', None)
        if student_id:
            student = context.students.filter_by(id=student_id).first()
            if student:
                context.students.remove(student)
        return HTTPFound(location=model_url(context, request, 'members.html'))
    elif 'remove_teacher' in request.GET:
        teacher_id = request.GET.get('remove_teacher', None)
        if teacher_id:
            teacher = context.teachers.filter_by(id=teacher_id).first()
            if teacher:
                context.teachers.remove(teacher)
        return HTTPFound(location=model_url(context, request, 'members.html'))

    root = get_root(request)
    students = []
    for student in context.students:
        students.append(root['users'][student.id])

    teachers = []
    for teacher in context.teachers:
        teachers.append(root['users'][teacher.id])

    return dict(api=TemplateAPI(request),
                context=context,
                students=students,
                all_students=all_students,
                teachers=teachers,
                all_teachers=all_teachers)
Example #14
0
def url_view(request, URL=URL):
    """model for test hooks"""
    matchdict = request.matchdict
    try:
        context = URL.m.find({'short_url' : matchdict['short_url']}).one()
        resp = HTTPFound(location=context.url)
        resp.expires=expire_one_year()
    except StopIteration:
        resp = HTTPNotFound(body="<h1>404 Not Found</h1> Nobody here but us fish...glug glug.")
    return resp
Example #15
0
    def _logout(self, request, credential):
        if hasattr(self.credential_broker, 'logout'):
            self.credential_broker.logout(credential)

        redirect_to = request.params.get('redirect_to', None)
        if redirect_to is None:
            redirect_to = request.application_url
        response = HTTPFound(location=redirect_to)
        response.delete_cookie(self.cookie_name)
        return response
Example #16
0
    def delete_ip(self, id):
        ip_id = request.POST.get('del_ip_id')
        user_model = UserModel()
        user_model.delete_extra_ip(id, ip_id)
        Session().commit()
        h.flash(_("Removed IP address from user whitelist"), category='success')

        if 'default_user' in request.POST:
            raise HTTPFound(location=url('admin_permissions_ips'))
        raise HTTPFound(location=url('edit_user_ips', id=id))
Example #17
0
def application_view(context, request):

    user = authenticated_user(request)
    if user:
        if ITeacher.providedBy(user):
            return HTTPFound(
                location=model_url(context, request, 'dashboard.html'))
        return HTTPFound(location=model_url(user, request))

    return HTTPFound(location=model_url(context, request, 'login.html'))
Example #18
0
def Comment(context, request):
    if request.method == "POST":
        try:
            data = form.CSRFForm(NoteSchema()).validate(request)
        except formish.FormError:
            return HTTPFound(
                location=route_url("invoice_view", request, id=context.id))

        context.notes.append(InvoiceNote(comment=data["comment"]))

    return HTTPFound(
        location=route_url("invoice_view", request, id=context.id))
Example #19
0
def redirect(where):
    exc = HTTPFound(location=where)
    try:
        exc.identity = response.identity
    except:
        pass

    if response.flash_obj:
        decoded_flash = pickle.dumps(response.flash_obj)
        exc.set_cookie('flash_obj', base64.b64encode(decoded_flash))

    raise exc
    def _main(self, request):
        if request.path == '/__main__':
            tmpl = os.path.join(_HERE, 'templates', 'main.mako')
            with open(tmpl) as f:
                tmpl = Template(f.read())

            return tmpl.render(appviews=self.appviews,
                               libraries=self.libraries)

        if request.path == '/__main__/add' and request.method == 'POST':

            def _name2path(name):
                # MORE CHARS
                path = name.lower()
                path = path.replace(' ', '')
                return '/' + path

            data = {}
            name = data['name'] = request.POST['name']
            data['root'] = _name2path(data['name'])
            data['description'] = request.POST['description']
            rbr = _DEFAULT_APP % data
            code = _DEFAULT_CODE
            location = os.path.join(_APPS, name)
            os.mkdir(location)
            appview = AppView(wsgiapp=self,
                              location=location,
                              rbr=rbr,
                              code=code,
                              name=name)
            appview.generate()
            self.appviews.append((appview.get_root(), appview))
            self.appviews.sort(by_len)
            # XXX
            url = 'http://%s%s/__editor__' % (request.environ['HTTP_HOST'],
                                              appview.get_root())
            return HTTPFound(location=url)

        if request.path == '/__main__/addlib' and request.method == 'POST':
            # loading a new lib
            name = request.POST['name']
            file_ = request.POST['file']
            if hasattr(file_, 'file'):
                code = file_.file.read()
            else:
                code = ''
            self.libraries.append(VirtualModule(name, code))
            # XXX
            url = 'http://%s/__lib__/%s' % (request.environ['HTTP_HOST'], name)
            return HTTPFound(location=url)

        return self._404()
Example #21
0
def undo_view(request, code):
    if not code.startswith('trash:'):
        return None

    # XXX Need security here.  Probably need to add api to trash to be able
    # to retrieve context(s) involved for purposes of security checking, before
    # performing undo operation.
    trash_id = code[6:]
    trash = find_trash(request.context)
    restored = trash.restore(trash_id, request.app_context.catalog)
    response = HTTPFound(location=model_url(request, restored))
    response.set_cookie('undo', '')
    return response
Example #22
0
def logged_in_view(context, request):

    user = authenticated_user(request)

    # Direct to the url of the "home" menu item which is user type specific.
    home_entry = get_current_registry().queryMultiAdapter((user, request),
                                                          IGlobalMenuEntry,
                                                          name="home")
    if home_entry:
        return HTTPFound(location=home_entry.url)
    else:
        return HTTPFound(location=model_url(
            context, request, 'login.html', query={'login_failed': '1'}))
Example #23
0
    def index(self):
        c.came_from = request.GET.get('came_from', '')
        if c.came_from:
            if not self._validate_came_from(c.came_from):
                log.error('Invalid came_from (not server-relative): %r',
                          c.came_from)
                raise HTTPBadRequest()
        else:
            c.came_from = url('home')

        if request.POST:
            # import Login Form validator class
            login_form = LoginForm()()
            try:
                # login_form will check username/password using ValidAuth and report failure to the user
                c.form_result = login_form.to_python(dict(request.POST))
                username = c.form_result['username']
                user = User.get_by_username_or_email(username)
                assert user is not None  # the same user get just passed in the form validation
            except formencode.Invalid as errors:
                defaults = errors.value
                # remove password from filling in form again
                defaults.pop('password', None)
                return htmlfill.render(render('/login.html'),
                                       defaults=errors.value,
                                       errors=errors.error_dict or {},
                                       prefix_error=False,
                                       encoding="UTF-8",
                                       force_defaults=False)
            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
                h.flash(e, 'error')
            else:
                # login_form already validated the password - now set the session cookie accordingly
                auth_user = log_in_user(user,
                                        c.form_result['remember'],
                                        is_external_auth=False,
                                        ip_addr=request.ip_addr)
                if auth_user:
                    raise HTTPFound(location=c.came_from)
                h.flash(_('Authentication failed.'), 'error')
        else:
            # redirect if already logged in
            if not request.authuser.is_anonymous:
                raise HTTPFound(location=c.came_from)
            # continue to show login to default user

        return render('/login.html')
Example #24
0
    def get_concrete_response(self):
        try:
            result = self.get_data_response()
        except NoViewMethod as exc:
            return HTTPUnsupportedMediaType(body=render_error_page(
                415, exc, mimetype=self.mimetype),
                                            content_type="text/html")
        except InvalidInput as exc:
            ## if the model raises a InvalidInput, retry the request as
            ## a GET request for the same program, and set the code to 400.
            request = make_duplicate_request(self.request)
            request.method = 'GET'
            c = HTTPController(request,
                               self.manifest,
                               self.model_mock,
                               errors=exc)
            response = c.get_response()
            response.status_int = 400
            return response
        except NotAuthorized as exc:
            return HTTPForbidden(body=render_error_page(
                403, exc, mimetype=self.mimetype),
                                 content_type="text/html")
        except (DataNotFound, ProgramNotFound) as exc:
            return HTTPNotFound(body=render_error_page(404,
                                                       exc,
                                                       mimetype=self.mimetype),
                                content_type="text/html")

        if type(result['body']) == Redirection:
            response = HTTPFound(location=result['body'].path)
        else:
            lazy = None
            body = result['body']

            if type(body) == tuple:
                lazy = body
                body = ''

            if hasattr(body, 'read'):
                body = body.read()

            response = Response(
                status=200,
                body=body,
                content_type=result['mimetype'],
            )

            response.lazy_data = lazy

        return response
Example #25
0
    def get_concrete_response(self):
        try:
            result = self.get_data_response()
        except NoViewMethod as exc:
            return HTTPUnsupportedMediaType(
                body=render_error_page(415, exc, mimetype=self.mimetype),
                content_type="text/html"
            )
        except InvalidInput as exc:
            ## if the model raises a InvalidInput, retry the request as
            ## a GET request for the same program, and set the code to 400.
            request = make_duplicate_request(self.request)
            request.method = 'GET'
            c = HTTPController(request, self.manifest, self.model_mock, errors=exc)
            response = c.get_response()
            response.status_int = 400
            return response
        except NotAuthorized as exc:
            return HTTPForbidden(
                body=render_error_page(403, exc, mimetype=self.mimetype),
                content_type="text/html"
            )
        except (DataNotFound, ProgramNotFound) as exc:
            return HTTPNotFound(
                body=render_error_page(404, exc, mimetype=self.mimetype),
                content_type="text/html"
            )

        if type(result['body']) == Redirection:
            response = HTTPFound(location=result['body'].path)
        else:
            lazy = None
            body = result['body']

            if type(body) == tuple:
                lazy = body
                body = ''

            if hasattr(body, 'read'):
                body = body.read()

            response = Response(
                status=200,
                body=body,
                content_type=result['mimetype'],
            )

            response.lazy_data = lazy

        return response
Example #26
0
 def wrapped(*args, **kwargs):
     if not operator.is_active(key):
         if not redirect_to:
             raise HTTPNotFound('Switch \'%s\' is not active' % key)
         else:
             raise HTTPFound(location=redirect_to)
     return func(*args, **kwargs)
Example #27
0
def directory_view(context, request):
    path_info = request.environ['PATH_INFO']
    if not path_info.endswith('/'):
        response = HTTPFound(location=path_info + '/')
        return response

    defaults = ('index.html', 'index.stx', 'index.pt')
    for name in defaults:
        try:
            index = context[name]
        except KeyError:
            continue
        return file_view(index, request)
    response = Response('No default view for %s' % context.path)
    response.content_type = 'text/plain'
    return response
Example #28
0
    def create(self):
        require.user.create()
        if self.email_is_blacklisted(self.form_result['email']):
            return ret_abort(_("Sorry, but we don't accept registrations with "
                               "this email address."), category='error',
                             code=403)

        # SPAM protection recaptcha
        captacha_enabled = config.get('recaptcha.public_key', "")
        if captacha_enabled:
            recaptcha_response = h.recaptcha.submit()
            if not recaptcha_response.is_valid:
                c.recaptcha = h.recaptcha.displayhtml(
                    use_ssl=True,
                    error=recaptcha_response.error_code)
                redirect("/register")
        # SPAM protection hidden input
        input_css = self.form_result.get("input_css")
        input_js = self.form_result.get("input_js")
        if input_css or input_js:
            redirect("/")

        #create user
        user = model.User.create(self.form_result.get("user_name"),
                                 self.form_result.get("email").lower(),
                                 password=self.form_result.get("password"),
                                 locale=c.locale)
        model.meta.Session.commit()

        event.emit(event.T_USER_CREATE, user)
        libmail.send_activation_link(user)

        if c.instance:
            membership = user.instance_membership(c.instance)
            if membership is None:
                membership = model.Membership(user, c.instance,
                                              c.instance.default_group)
                model.meta.Session.expunge(membership)
                model.meta.Session.add(membership)
                model.meta.Session.commit()

        # authenticate the new registered member using the repoze.who
        # api. This is done here and not with an redirect to the login
        # to omit the generic welcome message
        who_api = get_api(request.environ)
        login = self.form_result.get("user_name").encode('utf-8')
        credentials = {
            'login': login,
            'password': self.form_result.get("password").encode('utf-8')}
        authenticated, headers = who_api.login(credentials)
        if authenticated:
            # redirect to dashboard with login message
            session['logged_in'] = True
            session.save()
            location = h.base_url('/user/%s/dashboard' % login)
            raise HTTPFound(location=location, headers=headers)
        else:
            raise Exception('We have added the user to the Database '
                            'but cannot authenticate him: '
                            '%s (%s)' % (credentials['login'], user))
Example #29
0
    def challenge(self, environ, status, app_headers, forget_headers):
        path_info = environ['PATH_INFO']

        # Configuring the headers to be set:
        cookies = [(h, v) for (h, v) in app_headers
                   if h.lower() == 'set-cookie']
        headers = forget_headers + cookies

        if path_info == self.logout_handler_path:
            params = {}
            if 'came_from' in environ:
                params.update({'came_from': environ['came_from']})
            destination = _build_url(environ,
                                     self.post_logout_url,
                                     params=params)

        else:
            came_from_params = parse_qs(environ.get('QUERY_STRING', ''))
            params = {
                'came_from': _build_url(environ, path_info, came_from_params)
            }
            destination = _build_url(environ,
                                     self.login_form_url,
                                     params=params)

        return HTTPFound(location=destination, headers=headers)
Example #30
0
    def update(self, id):
        _form = DefaultsForm()()

        try:
            form_result = _form.to_python(dict(request.POST))
            for k, v in form_result.items():
                setting = Setting.create_or_update(k, v)
            Session().commit()
            h.flash(_('Default settings updated successfully'),
                    category='success')

        except formencode.Invalid as errors:
            defaults = errors.value

            return htmlfill.render(
                render('admin/defaults/defaults.html'),
                defaults=defaults,
                errors=errors.error_dict or {},
                prefix_error=False,
                encoding="UTF-8",
                force_defaults=False)
        except Exception:
            log.error(traceback.format_exc())
            h.flash(_('Error occurred during update of defaults'),
                    category='error')

        raise HTTPFound(location=url('defaults'))
Example #31
0
    def __call__(self):
        if self.request.method == "POST":
            if self.request.POST["action"] == "cancel":
                return HTTPFound(location=route_url("home", self.request))
            account = self.save()
            if account:
                response = HTTPFound(
                    location=route_url("dashboard", self.request))
                loginUser(account, self.request, response)
                return response

        return render("signup.pt",
                      self.request,
                      status_int=202 if self.request.method == "POST" else 200,
                      view=self,
                      action_url=route_url("signup", self.request))
Example #32
0
def register_view(context, request):
    form = Form(Signup(), buttons=('register', ))
    rendered_form = form.render(null)
    if 'register' in request.POST:
        try:
            appstruct = form.validate(request.POST.items())
        except ValidationFailure, e:
            rendered_form = e.render()
        else:
            pending = request.registry.queryAdapter(context,
                                                    IRegistrations,
                                                    name='pending')
            if pending is None:  #pragma NO COVERAGE
                pending = PendingRegistrations(context)
            email = appstruct['email']
            token = getRandomToken(request)
            pending.set(email, token=token)

            from_addr = request.registry.settings['cartouche.from_addr']
            delivery = request.registry.queryUtility(IMailDelivery,
                                                     default=localhost_mta)
            confirmation_url = view_url(context,
                                        request,
                                        'confirmation_url',
                                        'confirm_registration.html',
                                        email=email)
            body = REGISTRATION_EMAIL % {
                'token': token,
                'confirmation_url': confirmation_url
            }
            message = Message()
            message['Subject'] = 'Site registration confirmation'
            message.set_payload(body)
            delivery.send(from_addr, [email], message)
            return HTTPFound(location=confirmation_url)
Example #33
0
def login(request):
    """Handle login request"""
    login_url = route_url('login', request)
    referrer = request.url
    if referrer == login_url:
        # never use the login form itself as came_from
        referrer = '/'
    came_from = request.params.get('came_from', referrer)
    message = ''
    login = ''
    password = ''
    if 'form.submitted' in request.params:
        login = request.params['login']
        password = request.params['password']
        if USERS.get(login) == password:
            headers = remember(request, login)
            return HTTPFound(location=came_from, headers=headers)
        message = 'Failed login'

    return dict(
        message=message,
        url=request.application_url + '/login',
        came_from=came_from,
        login=login,
        password=password,
    )
 def test_call_ingress_plugin_replaces_application(self):
     from webob.exc import HTTPFound
     environ = self._makeEnviron()
     headers = [('a', '1')]
     app = DummyWorkingApp('200 OK', headers)
     challengers = []
     credentials = {'login': '******', 'password': '******'}
     identifier = DummyIdentifier(
         credentials,
         remember_headers=[('a', '1')],
         replace_app=HTTPFound('http://example.com/redirect'))
     identifiers = [('identifier', identifier)]
     authenticator = DummyAuthenticator()
     authenticators = [('authenticator', authenticator)]
     mdproviders = []
     mw = self._makeOne(app=app,
                        challengers=challengers,
                        identifiers=identifiers,
                        authenticators=authenticators,
                        mdproviders=mdproviders)
     start_response = DummyStartResponse()
     result = b''.join(mw(environ, start_response)).decode('ascii')
     self.assertTrue(result.startswith('302 Found'))
     self.assertEqual(start_response.status, '302 Found')
     headers = start_response.headers
     #self.assertEqual(len(headers), 3, headers)
     #self.assertEqual(headers[0],
     #                 ('Location', 'http://example.com/redirect'))
     self.assertEqual(headers[2],
                      ('Content-Type', 'text/plain; charset=UTF-8'))
     self.assertEqual(headers[3], ('a', '1'))
     self.assertEqual(start_response.exc_info, None)
     self.assertFalse('repoze.who.application' in environ)
Example #35
0
def redirect(*args, **kwargs):
    """Compose a URL using :func:`url_for` and raise a redirect.

    :raises: :class:`webob.exc.HTTPFound`
    """
    url = url_for(*args, **kwargs)
    raise HTTPFound(location=url)
Example #36
0
    def edit_statistics(self, repo_name):
        c.repo_info = self._load_repo()
        repo = c.repo_info.scm_instance

        if c.repo_info.stats:
            # this is on what revision we ended up so we add +1 for count
            last_rev = c.repo_info.stats.stat_on_revision + 1
        else:
            last_rev = 0
        c.stats_revision = last_rev

        c.repo_last_rev = repo.count() if repo.revisions else 0

        if last_rev == 0 or c.repo_last_rev == 0:
            c.stats_percentage = 0
        else:
            c.stats_percentage = '%.2f' % ((float(
                (last_rev)) / c.repo_last_rev) * 100)

        c.active = 'statistics'
        if request.POST:
            try:
                RepoModel().delete_stats(repo_name)
                Session().commit()
            except Exception as e:
                log.error(traceback.format_exc())
                h.flash(
                    _('An error occurred during deletion of repository stats'),
                    category='error')
            raise HTTPFound(
                location=url('edit_repo_statistics', repo_name=c.repo_name))

        return render('admin/repos/repo_edit.html')
Example #37
0
    def edit_advanced_fork(self, repo_name):
        """
        Mark given repository as a fork of another

        :param repo_name:
        """
        try:
            fork_id = request.POST.get('id_fork_of')
            repo = ScmModel().mark_as_fork(repo_name, fork_id,
                                           request.authuser.username)
            fork = repo.fork.repo_name if repo.fork else _('Nothing')
            Session().commit()
            h.flash(_('Marked repository %s as fork of %s') %
                    (repo_name, fork),
                    category='success')
        except RepositoryError as e:
            log.error(traceback.format_exc())
            h.flash(e, category='error')
        except Exception as e:
            log.error(traceback.format_exc())
            h.flash(_('An error occurred during this operation'),
                    category='error')

        raise HTTPFound(
            location=url('edit_repo_advanced', repo_name=repo_name))
Example #38
0
    def edit_advanced(self, repo_name):
        c.repo_info = self._load_repo()
        c.default_user_id = kallithea.DEFAULT_USER_ID
        c.in_public_journal = UserFollowing.query() \
            .filter(UserFollowing.user_id == c.default_user_id) \
            .filter(UserFollowing.follows_repository == c.repo_info).scalar()

        _repos = Repository.query(sorted=True).all()
        read_access_repos = RepoList(_repos, perm_level='read')
        c.repos_list = [(None, _('-- Not a fork --'))]
        c.repos_list += [(x.repo_id, x.repo_name) for x in read_access_repos
                         if x.repo_id != c.repo_info.repo_id
                         and x.repo_type == c.repo_info.repo_type]

        defaults = {
            'id_fork_of': c.repo_info.fork_id if c.repo_info.fork_id else ''
        }

        c.active = 'advanced'
        if request.POST:
            raise HTTPFound(location=url('repo_edit_advanced'))
        return htmlfill.render(render('admin/repos/repo_edit.html'),
                               defaults=defaults,
                               encoding="UTF-8",
                               force_defaults=False)
Example #39
0
def tutorialbin_add_view(context, request):
    params = request.params
    title = u''
    url = u''
    language = u''
    text = u''
    code = u''
    message = u''
    attachment= ''
    tutorialbin_url = resource_url(context, request)
    user = authenticated_userid(request)
    can_manage = has_permission('manage', context, request)

    if params.has_key('form.submitted'):
        title = params.get('title', u'')
        text = params.get('text', u'')
        code = params.get('code', u'')
        url = params.get('url', u'')
        language = params.get('language', u'')
        schema = TutorialAddEditSchema()
        message = None
        attachment = params.get('attachment')
        try:
            schema.to_python(request.params)
        except formencode.validators.Invalid, why:
            message = str(why)
        else:
            file_name = None
            mime_type = None
            stream = None
            if hasattr(attachment, 'filename'):
                file_name = attachment.filename
                mime_type = attachment.type
                stream = attachment.file
            pobj = Tutorial(title, user, text, url, code, language, 
                            stream, file_name, mime_type)
            acl = context.__acl__[:]
            acl.extend([(Allow, user, 'edit'), (Allow, 'admin', 'edit')])
            pobj.__acl__ = acl
            tutorialid = context.add_item(pobj)
            response = HTTPFound(location = '%s%s' % (tutorialbin_url,
                                                      tutorialid))
            response.set_cookie(COOKIE_LANGUAGE, language)
            return response
Example #40
0
    def cook(self, form, login, password, authenticated_for, back):
        privkey = tlib.read_key(form.context.pkey)
        val = base64.b64encode(
            tlib.bauth(
                form.context.cipher,
                '%s:%s' % (login, password))
        )
        #val = val.replace('\n', '', 1)
        validtime = datetime.datetime.now() + datetime.timedelta(hours=1)
        validuntil = int(time.mktime(validtime.timetuple()))
        ticket = tlib.create_ticket(
            privkey, login, validuntil, tokens=list(authenticated_for),
            extra_fields=(('bauth', val),))

        back = form.back(login)
        res = HTTPFound(location=back)
        res.set_cookie('auth_pubtkt', quote(ticket), path='/',
                       domain='novareto.de', secure=False)
        return res
Example #41
0
    def _login(self, request):
        login = request.params.get('login', '')
        password = request.params.get('password', None)
        status_msg = request.params.get('status_msg', '')
        redirect_to = request.params.get('redirect_to', None)
        if redirect_to is None:
            redirect_to = request.application_url
        if login and password:
            if self.password_broker(login, password):
                credential = self.credential_broker.login(login)
                response = HTTPFound(location=redirect_to)
                response.set_cookie(self.cookie_name, credential)
                return response

            status_msg = "Bad login"

        body = self.form_template(
            login=login,
            status_msg=status_msg,
            redirect_to=redirect_to,
        )
        return webob.Response(body, content_type='text/html')
Example #42
0
def delete_photos_view(request, album):
    if request.subpath:
        visibility = request.subpath.pop(0)
    else:
        visibility = None

    photos = []
    for photo in album.photos():
        if visibility is None or photo.visibility == visibility:
            photos.append(photo)

    assert photos, "Nothing to delete."

    catalog = request.app_context.catalog
    catalog.unindex_photos_in_album(album, photos)

    trash = find_trash(album)
    trash_id = trash.trash_photos_in_album(album, photos)

    response = HTTPFound(location=model_url(request, album))
    response.set_cookie('undo', 'trash:%s|Deleted+photos' % trash_id)
    return response
Example #43
0
def home(request):
    domain = email = password = message = ''
    if request.method == 'POST':
        domain =   request.POST['domain']
        email  =   request.POST['email']
        password = request.POST['password']
        # validate form
        if not (domain and email and password):
            message = 'You must fill in all the boxes'
        else:
            # auth and retrieve bank entries
            # pass bank info to expense rendering form (how? session?)
            response = HTTPFound(location="/expense")
            # XXX I should NOT be storing sensitive data in cookies
            # How to pass these to other pages? 
            response.set_cookie('domain_', domain)
            response.set_cookie('email', email)
            response.set_cookie('password', password)
            return response
    return dict(domain=domain, email=email, password=password, message=message)