コード例 #1
0
ファイル: registration.py プロジェクト: nous-consulting/ututi
    def finish(self, registration):
        from ututi.lib.security import sign_in_user
        if not registration.location:
            # if there is a university with same title we will use it.
            existing = LocationTag.get_by_title(registration.university_title)
            if existing is not None:
                registration.location = existing
            else:
                registration.location = registration.create_university()

        user = registration.create_user()
        bind_group_invitations(user)

        # TODO: integrity checks here

        meta.Session.add(user)
        registration.completed = True
        # flush before sending any emails
        meta.Session.flush()

        process_registration_invitations(registration)
        meta.Session.commit()

        if user.is_teacher:
            teacher_registered_email(user)

        sign_in_user(user)
        redirect(url(controller='profile', action='register_welcome'))
コード例 #2
0
ファイル: velruse.py プロジェクト: alkadis/vcv
    def revoke(self, redirect_url=None):
        v_id = request.params.get('id', None)

        if v_id is None:
            abort(401, "id of velruse account not specified")

        v = Velruse.by_id(v_id)
        if v is None:
            self._failure(_("You are trying to disconnect from a provider"
                            " you are disconnected from already."))
            return None

        elif not (v.user == c.user or can.user.manage()):
            abort(403, _("You're not authorized to change %s's settings.")
                  % c.user.id)
        else:
            v.delete_forever()
            model.meta.Session.commit()

            h.flash(_("You successfully disconnected from %(provider)s.")
                    % {'provider': v.domain},
                    'success')

            if redirect_url is None:
                redirect(h.entity_url(c.user, member='settings/login'))
            else:
                redirect(redirect_url)
コード例 #3
0
ファイル: prefix.py プロジェクト: Dhyrule/NIPAP
    def index(self):
        """ Index page

            Redirect to prefix list.
        """

        redirect(url(controller = 'prefix', action = 'list'))
コード例 #4
0
    def create(self, format="html", **kwargs):
        """REST api"""
        fs = self.get_add_fieldset()

        if format == "json" and request.method == "PUT":
            data = json.load(request.body_file)
        else:
            data = request.POST

        try:
            fs = fs.bind(data=data, session=self.Session())
        except:
            # non SA forms
            fs = fs.bind(self.get_model(), data=data, session=self.Session())
        if fs.validate():
            fs.sync()
            self.sync(fs)
            if format == "html":
                if request.is_xhr:
                    response.content_type = "text/plain"
                    return ""
                redirect(model_url(self.collection_name))
            else:
                fs.rebind(fs.model, data=None)
                return self.render(format=format, fs=fs)
        return self.render(format=format, fs=fs, action="new", id=None)
コード例 #5
0
ファイル: root.py プロジェクト: AnonOnWarpath/adhocracy
 def sitemap_xml(self):
     if c.instance:
         redirect(h.base_url(None, path="/sitemap.xml"))
     c.delegateables = model.Delegateable.all()
     c.change_time = datetime.utcnow()
     response.content_type = "text/xml"
     return render("sitemap.xml")
コード例 #6
0
ファイル: snippets.py プロジェクト: Pylons/kai
 def update(self, id):
     slug = id.lower().strip()
     snippets = list(Snippet.by_slug(self.db)[slug]) or abort(404)
     snippet = snippets[0]
     if snippet.displayname:
         author = Human.load(self.db, snippet.human_id)
     is_owner = self._check_owner(snippet, c.user, check_session=True)
     if not is_owner:
         abort(401)
     
     snippet.title = self.form_result['title']
     snippet.content = self.form_result['content']
     snippet.description = self.form_result['description']
     
     ## generate the slug
     slug = snippet.title.replace(" ", "_")
     slug = slug.lower()
     slug = re.sub('[^A-Za-z0-9_]+', '', slug)
     
     snippet.slug = slug
     if 'tags' in self.form_result:
         snippet.tags = self.form_result['tags'].replace(',', ' ').strip().split(' ')
     snippet.store(self.db)
     success_flash('Snippet has been updated')
     redirect(url('snippet', id=slug))
コード例 #7
0
ファイル: registration.py プロジェクト: nous-consulting/ututi
    def invite_friends_fb(self, registration):
        # we don't do fb invitations if university is not created
        if registration.location is None:
            redirect(registration.url(action='invite_friends'))

        # handle facebook callback
        ids = request.params.get('ids[]')
        if ids:
            registration.invited_fb_ids = ids
            meta.Session.commit()
            redirect(registration.url(action='invite_friends'))

        # render page
        fb_user = facebook.get_user_from_cookie(request.cookies,
                      config['facebook.appid'], config['facebook.secret'])
        c.has_facebook = fb_user is not None
        if c.has_facebook:
            try:
                graph = facebook.GraphAPI(fb_user['access_token'])
                friends = graph.get_object("me/friends")
                friend_ids = [f['id'] for f in friends['data']]
                friend_users = meta.Session.query(User)\
                        .filter(User.facebook_id.in_(friend_ids))\
                        .filter(User.location == registration.location).all()
                c.exclude_ids = ','.join(str(u.facebook_id) for u in friend_users)
            except facebook.GraphAPIError:
                c.has_facebook = False

        c.active_step = 'invite_friends'
        return render('registration/invite_friends_fb.mako')
コード例 #8
0
ファイル: memory.py プロジェクト: jrwdunham/old-webapp
    def forget(self, id=None):
        """Remove 0 or more Forms from the User's Memory.

        If id is None, remove all Forms from Memory;
        otherwise, remove Form with provided id."""
        if id is None:
            user = meta.Session.query(model.User).filter(
                model.User.id==session['user_id']).first()
            user.rememberedForms = []
            meta.Session.commit()
            msg = u'All Forms in Memory have been removed.'
        else:
            form_q = meta.Session.query(model.Form)
            form = form_q.get(int(id))
            if form is None:
                msg = u'There is no Form with ID %s' % id
            else:
                user = meta.Session.query(model.User).filter(
                    model.User.id==session['user_id']).first()
                if form in user.rememberedForms:
                    user.rememberedForms.remove(form)
                    meta.Session.commit()
                    msg = u'Form %s has been removed from your memory' % id
                else:
                    msg = u'Form %s was never in your memory to begin with!' % id
        session['flash'] = msg
        session.save()
        redirect(url(controller='memory', action='index', id=None))
コード例 #9
0
ファイル: account.py プロジェクト: asuffield/openspending
 def after_login(self):
     if c.account is not None:
         h.flash_success(_("Welcome back, %s!") % c.account.name)
         redirect("/")
     else:
         h.flash_error(_("Incorrect user name or password!"))
         redirect("/login")
コード例 #10
0
ファイル: location.py プロジェクト: nous-consulting/ututi
    def register_teacher(self, location):
        # bounce existing users to different action
        if c.user is not None:
            redirect(location.url(action='register_teacher_existing'))

        if not hasattr(self, 'form_result'):
            return htmlfill.render(self._register_teacher_form())

        email = self.form_result['email']

        if User.get(email, location):
            h.flash(_('The email you entered is registered in Ututi. '
                      'Please login to proceed.'))
            destination = location.url(action='register_teacher_existing')
            redirect(url(controller='home', action='login', email=email,
                         came_from=destination))

        # lookup/create registration entry and send confirmation code to user
        registration = UserRegistration.create_or_update(location, email)
        registration.teacher = True
        meta.Session.commit()
        registration.send_confirmation_email()

        # show confirmation page
        c.email = email
        return render('registration/email_approval.mako')
コード例 #11
0
ファイル: accounts.py プロジェクト: TetraAsh/baruwa2
    def delete(self, userid):
        """/accounts/delete/id"""
        user = self._get_user(userid)
        if not user:
            abort(404)

        c.form = EditUserForm(request.POST, user, csrf_context=session)
        del c.form.domains

        if request.POST and c.form.validate():
            username = user.username
            user_id = unicode(user.id)
            Session.delete(user)
            Session.commit()
            update_serial.delay()
            flash(_('The account has been deleted'))
            info = DELETEACCOUNT_MSG % dict(u=username)
            audit_log(c.user.username,
                    4, unicode(info), request.host,
                    request.remote_addr, now())
            if userid == user_id:
                redirect(url('/logout'))
            redirect(url(controller='accounts', action='index'))
        else:
            flash_info(_('The account: %(a)s and all associated data'
                ' will be deleted, This action is not reversible.') %
                dict(a=user.username))
        c.fields = FORM_FIELDS
        c.id = userid
        return render('/accounts/delete.html')
コード例 #12
0
ファイル: account.py プロジェクト: benosteen/RDFDatabank
 def welcome(self):
     identity = request.environ.get("repoze.who.identity")
     came_from = request.params.get('came_from') or "/"
     came_from = unquote(came_from)
     came_from = unquote(came_from)
     came_from = unquote(came_from)
     came_from = str(came_from)
     if identity:
         # Login succeeded
         userid = identity['repoze.who.userid']
         #user_det = get_mediator_details(userid)
         #if user_det['name']:
         #    session['user_name'] = user_det['name']
         #if user_det['uri']:
         #    session['user_uri'] = str(user_det['uri'])
         session['user_id'] = userid
         session.save()
         return redirect(url(came_from))
     else:
         # Login failed
         try:
             login_counter = request.environ['repoze.who.logins'] + 1
         except:
             login_counter = 0
         destination = "/login?came_from=%s&logins=%s" % (came_from, login_counter)
         return redirect(url(destination))
コード例 #13
0
ファイル: assay.py プロジェクト: v-makarenko/vtoolsmq
    def save(self, id=None):
        """
        """
        if id is None:
            abort(404)
        assay_q = Session.query(Assay)
        assay = assay_q.filter_by(id=id).first()
        if assay is None:
            abort(404)

        reload_sequences = False
        for k, v in self.form_result.items():
            if k in ("primer_fwd", "primer_rev", "chromosome", "probe_pos", "amplicon_width", "snp_rsid"):
                if getattr(assay, k) != v:
                    reload_sequences = True
            if k not in ("id"):
                setattr(assay, k, v)

        # blow away previous sequences; on view, this will update.
        if reload_sequences:
            cached_sequences = assay.cached_sequences
            for i in range(len(cached_sequences)):
                cs = cached_sequences[-1]
                snps = cs.snps
                for j in range(len(snps)):
                    snp = snps.pop()
                    Session.delete(snp)
                cached_sequences.pop()
                Session.delete(cs)

        self.__update_tms(assay)

        Session.commit()
        session.save()
        redirect(url(controller="assay", action="view", id=assay.id))
コード例 #14
0
ファイル: openid.py プロジェクト: MuhamadYULIANTO/LinOTP
    def logout(self):
        '''
        This action deletes the cookie and redirects to the
        /openid/status to show the login status

        If the logout is called in the context of an openid authentication,
        the user is already logged in as a different user. In this case we
        forward to the /openid/login page after the logout was made.

        Another option for the openid authentication context would be to
        redirect to the return_to url by setting
            redirect_to = params["openid.return_to"]
            p["openid.mode"] = "setup_needed"
        which advises the openid relying party to restart the login process.
        '''

        response.delete_cookie(COOKIE_NAME)

        params = {}
        params.update(request.params)
        p = {}

        ## are we are called during an openid auth request?
        if "openid.return_to" in params:
            redirect_to = "/openid/login"
            p.update(params)
            do_redirect = url(str("%s?%s" % (redirect_to, urlencode(p))))

        else:
            redirect_to = "/openid/status"
            do_redirect = url(str("%s?%s" % (redirect_to, urlencode(p))))

        redirect(do_redirect)
コード例 #15
0
ファイル: auth.py プロジェクト: hetznerZA/NIPAP
    def login(self):
        """ Show login form.
        """

        if request.method != 'POST':
            cfg = NipapConfig()
            try:
                c.welcome_message = cfg.get('www', 'welcome_message')
            except NoOptionError:
                pass

            return render('login.html')

        # Verify username and password.
        auth_fact = AuthFactory()
        auth = auth_fact.get_auth(request.params.get('username'), request.params.get('password'), 'nipap')
        if not auth.authenticate():
            c.error = 'Invalid username or password'
            return render('login.html')

        # Mark user as logged in
        session['user'] = auth.username
        session['full_name'] = auth.full_name
        session['current_vrfs'] = {}
        session.save()

        # Send user back to the page he originally wanted to get to
        if session.get('path_before_login'):
            redirect(session['path_before_login'])

        else:
            # if previous target is unknown just send the user to a welcome page
            redirect(url(controller='vrf', action='list'))
コード例 #16
0
ファイル: openid.py プロジェクト: MuhamadYULIANTO/LinOTP
    def checkid_submit(self):
        '''
        This is called when the user accepts - hit the submit button - that he will login to the consumer
        '''
        param = request.params
        log.debug("[checkid_submit] params: %s" % param)
        redirect_token = getParam(param, "redirect_token", required)
        verify_always = getParam(param, "verify_always", optional)
        r_url, site, handle = self.storage.get_redirect(redirect_token)
        self.storage.add_site(site, handle)

        # The user checked the box, that he wants not be bothered again in the future
        # the relying party will be added to the trusted root
        login, token = self._split_cookie()
        user = self.storage.get_user_by_token(token)
        c.audit['user'], c.audit['realm'] = user.split('@', 2)
        c.audit['success'] = True
        c.audit['action_detail'] = site

        if "always" == verify_always:
            log.debug("[checkid_submit] putting into trusted root: %s, %s" % (site, handle))
            if "" != user:
                self.storage.add_trusted_root(user, site)

        log.debug("[checkid_submit] redirecting to %s" % r_url)
        redirect(r_url)
コード例 #17
0
ファイル: mobile.py プロジェクト: feilaoda/kd
 def doadd(self):
     soft = Software()
     soft.name = self.form_result.get('software_name')
     soft.download_url =  self.form_result.get('download_url')
     Session.add(soft)
     Session.commit()        
     redirect(url(controller="mobile", action="index"))
コード例 #18
0
ファイル: location.py プロジェクト: nous-consulting/ututi
 def switch_language(self, location):
     # This is a general language switcher, but is placed here to
     # have a separate route for use in external university pages.
     language = request.params.get('language', 'en')
     # TODO validate
     switch_language(language)
     redirect(c.came_from or location.url())
コード例 #19
0
ファイル: manage.py プロジェクト: Ethanlord300/Saloon.tf
  def matchesLeagues(self):
    # Returns a rendered template
    user = User()
    if user:
      RUser = user[0]
      if RUser.Permissions[0].bets:
        c.user = user[1]
        c.current = "manage"
        c.managePage = "matches"

        RLeagues = db.Session.query(db.Leagues).order_by(db.Leagues.id).limit(10).all()
        c.leagues = []
        for RLeague in RLeagues:
          league = {}
          league["id"] = RLeague.id
          league["name"] = RLeague.name
          league["type"] = RLeague.type
          league["region"] = RLeague.region
          league["colour"] = RLeague.colour
          league["json"] = json.dumps(league)
          c.leagues.append(league)

        return render('/manage/matches/index.mako')
      else:
        return redirect('/home/')
    else:
      return redirect('/home/')
コード例 #20
0
ファイル: home.py プロジェクト: nous-consulting/ututi
    def register(self):
        name = request.POST.get('name')
        email = request.POST.get('email')
        location_id = request.POST.get('location_id')
        accept_terms = request.POST.get('accept_terms')
        person = request.POST.get('person')

        c.universities = self._universities(limit=12)
        c.all_universities = self._universities()

        # checks if email, name, person are not empty
        if not email or not name or not person or accept_terms != '1':
            redirect(url('frontpage'))

        # redirect to login if user is already registered
        if User.get_all(email):
            redirect(url(controller='home', action='login', email=email))

        # otherwise we validate the form properly
        try:
            self.form_result = RegistrationForm().to_python(request.POST)
        except validators.Invalid, e:
            return htmlfill.render(self._sign_up_form(),
                                   defaults=request.POST,
                                   errors=e.error_dict,
                                   error_formatters=u_error_formatters)
コード例 #21
0
ファイル: poll.py プロジェクト: drmalex07/pylons-helloworld
    def _vote_save(self):
        post = request.POST

        # Fetch POST data
        vote = post.get(u'vote')
        email = post.get(u'email')
        op = post.get(u'op')
        attachment = post.get(u'vote-attachment')
        comment = post.get(u'vote-comment')
        fp = attachment.file if isinstance(attachment, cgi.FieldStorage) else None
        attachment_data = fp.read(256).decode('utf-8') if fp else '<None>' # Note: assume plain text utf-8 file
        #raise Exception('Inspect POST data')

        # Validate request
        if not (post.get(secure_form.token_key, None) == secure_form.authentication_token()):
            abort (403, detail=u'Not permitted (possible CSRF attack)')

        # Validate POST data: in practice we should not abort but rather redirect to the form
        # with all the errors highlighted
        vote = int(vote)
        if not (vote >= 0 and vote <= 10):
            abort (400, detail=u'Bad value for vote')

        # Done with validation, now just log this and store the (vote,email) in the underlying model
        log.info ('Saving vote for poll (%r)' %(dict(vote=vote, email=email, op=op, attachment_data=attachment_data)))
        db_session = model.Session()
        v = model.Vote (vote=vote, email=email, created_at=None, description=comment);
        db_session.add(v)
        db_session.commit()

        # Done with form processing, redirect to a normal (GET) request ...
        h.flash('Your vote is saved!')
        redirect (url(controller='poll', action='results'))
        return
コード例 #22
0
ファイル: manage.py プロジェクト: Ethanlord300/Saloon.tf
  def addTeam(self, leagueID):
    # Returns a redirection to /manage/teams/{leagueID}
    user = User()
    if user:
      RUser = user[0]
      if RUser.Permissions[0].teams:
        RTeam = db.Teams(name=request.params["name"], short=request.params["short"], country=request.params["country"], league=leagueID, leagueID=request.params["leagueID"])
        db.Session.add(RTeam)
        db.Session.commit()

        avatar = request.params["avatar"].file
        avatar_path = os.path.join('website/public/images/teams', str(RTeam.id) + '.jpg')
        temp_path = avatar_path + '~'
        output_file = open(temp_path, 'wb')
        avatar.seek(0)
        while True:
          data = avatar.read(2<<16)
          if not data:
            break
          output_file.write(data)
        output_file.close()
        os.rename(temp_path, avatar_path)
        return redirect("/manage/teams/" + leagueID)
      else:
        return redirect("/")
    else:
      return redirect("/")
コード例 #23
0
ファイル: accounts.py プロジェクト: TetraAsh/baruwa2
 def loggedout(self):
     "Logged out page"
     session.clear()
     session.save()
     came_from = (unquote(str(request.params.get('came_from', '')))
                 or url('/accounts/login'))
     redirect(url(came_from))
コード例 #24
0
ファイル: accounts.py プロジェクト: TetraAsh/baruwa2
    def login(self):
        "login"
        if request.remote_addr in session:
            if session[request.remote_addr] > now():
                abort(409, _('You have been banned after'
                            ' several failed logins'))
            else:
                del session[request.remote_addr]
                session.save()

        identity = request.environ.get('repoze.who.identity')
        came_from = unquote(str(request.GET.get('came_from', '')))
        if not came_from or ' ' in came_from:
            came_from = url('home')
        if '://' in came_from:
            from_url = urlparse(came_from)
            came_from = from_url[2]

        if identity:
            redirect(url(came_from))
        else:
            c.came_from = came_from
            c.login_counter = request.environ['repoze.who.logins']
            if c.login_counter >= 3:
                ban_until = now() + timedelta(minutes=5)
                if request.remote_addr not in session:
                    session[request.remote_addr] = ban_until
                    session.save()
                else:
                    if now() > session[request.remote_addr]:
                        del session[request.remote_addr]
                        session.save()
            c.form = ResetPwForm(request.POST, csrf_context=session)
            return render('/accounts/login.html')
コード例 #25
0
ファイル: accounts.py プロジェクト: TetraAsh/baruwa2
 def pwchange(self, userid):
     """Reset a user password"""
     user = self._get_user(userid)
     if not user:
         abort(404)
     c.form = ChangePasswordForm(request.POST, csrf_context=session)
     if request.POST and c.form.validate():
         if user.local and not user.is_superadmin:
             user.set_password(c.form.password1.data)
             Session.add(user)
             Session.commit()
             flash(_('The account password for %(name)s has been reset')
                 % dict(name=user.username))
             info = PASSWORDCHANGE_MSG % dict(u=user.username)
             audit_log(c.user.username,
                     2, unicode(info), request.host,
                     request.remote_addr, now())
         else:
             if user.is_superadmin:
                 flash(_('Admin accounts can not be modified via the web'))
             else:
                 flash(_('This is an external account, use'
                     ' external system to reset the password'))
         redirect(url('account-detail', userid=user.id))
     c.id = userid
     c.username = user.username
     c.posturl = 'accounts-pw-change'
     return render('/accounts/pwchange.html')
コード例 #26
0
ファイル: manage.py プロジェクト: Ethanlord300/Saloon.tf
  def bots(self):
    user = User()
    if user:
      RUser = user[0]
      if RUser.Permissions[0].bots:
        c.current = "manage"
        c.managePage = "bots"
        c.user = user[1]
        c.bots = []
        RBots = db.Session.query(db.Bots).order_by(db.Bots.id).limit(10).all()

        for RBot in RBots:
          bot = {}
          bot["id"] = RBot.id
          bot["name"] = RBot.name
          bot["emailAddress"] = RBot.emailAddress
          bot["steamLogin"] = RBot.steamLogin
          bot["steamID"] = RBot.steamID
          bot["steamAPI"] = RBot.steamAPI
          bot["tradeoffers"] = "http://steamcommunity.com/tradeoffer/new/?partner=%d&token=%s" % (int(RBot.steamID) - 76561197960265728, RBot.token)
          bot["slots"] = RBot.slots
          bot["slotsEmpty"] = RBot.slotsEmpty
          bot["backpackAPI"] = RBot.backpackAPI

          bot["json"] = json.dumps(bot)
          c.bots.append(bot)

        return render('/manage/bots.mako')
      else:
        return redirect("/manage/")
    else: 
      return redirect("/")
コード例 #27
0
ファイル: comment.py プロジェクト: jaywink/argonaut
 def submit(self):
     c.post = h.post.get(int(request.params.get('post_id')))
     c.posts = None
     if h.forms.validate(h.forms.CommentForm()):         
         # save comment
         comment = h.comment.new()
         for k, v in c.form_result.items():
             setattr(comment, k, v)
         # some checks and defaults
         if len(comment.author) == 0:
             comment.author = 'anonymous'
         comment.posted = h.timehelpers.now()
         comment.body = h.html_escape(comment.body)
         comment.body = comment.body.replace('\n','<br>')
         comment.body = comment.body.replace('\t','&nbsp;')
         comment.body = comment.body.replace('  ','&nbsp; ')
         # save to db
         h.comment.save(comment)
         # flash message
         session['flash'] = 'Comment successfully saved.'
         session.save()
         # notify author
         h.mailer.send_mail('*****@*****.**', h.auth.get_user_mail(c.post.author), 'New comment for: '+c.post.subject, render('/messages/mail_new_comment.mako', extra_vars={'user':h.auth.get_user_name(id=c.post.author), 'post_subject':c.post.subject, 'site_name':h.config.get('site_title'), 'post_url':h.config.get('site_url')+url(controller='blog', action='view', id=c.post.id, subject=h.urlify(c.post.subject))}))
         # redirect to post
         redirect(url(controller='blog', action='view', id=request.params.get('post_id'), subject=h.urlify(c.post.subject)), code=303)
     else:
         session['flash'] = 'Erros in the submitted form, please correct and try again.'
         session.save()
         html = render('/blog/view.mako', extra_vars={'page_id':1, 'post_count':1})
         return htmlfill.render(html,defaults=c.form_result,errors=c.form_errors)
コード例 #28
0
ファイル: accounts.py プロジェクト: TetraAsh/baruwa2
 def upwchange(self, userid):
     """User change own password"""
     user = self._get_user(userid)
     if not user:
         abort(404)
     if user.id != c.user.id or c.user.is_superadmin:
         abort(403)
     c.form = UserPasswordForm(request.POST, csrf_context=session)
     if (request.POST and c.form.validate() and
         user.validate_password(c.form.password3.data)):
         if user.local:
             user.set_password(c.form.password1.data)
             Session.add(user)
             Session.commit()
             flash(_('The account password for %(name)s has been reset')
                 % dict(name=user.username))
             info = PASSWORDCHANGE_MSG % dict(u=user.username)
             audit_log(c.user.username,
                     2, unicode(info), request.host,
                     request.remote_addr, now())
         else:
             flash(_('This is an external account, use'
                 ' external system to reset the password'))
         redirect(url('account-detail', userid=user.id))
     elif (request.POST and not
         user.validate_password(c.form.password3.data)
         and not c.form.password3.errors):
         flash_alert(_('The old password supplied does'
                     ' not match our records'))
     c.id = userid
     c.username = user.username
     c.posturl = 'accounts-pw-uchange'
     return render('/accounts/pwchange.html')
コード例 #29
0
ファイル: home.py プロジェクト: nous-consulting/ututi
    def login(self):
        # Here below email get parameter may be used for convenience
        # i.e. when redirecting from sign-up form.
        # POST and GET params are accepted for external javascript logins
        # to work via JSONP (see _js_login above).

        username = request.params.get('username') or request.params.get('email')
        password = request.params.get('password')
        location = request.params.get('location')
        location = int(location) if location else None
        remember = bool(request.params.get('remember'))

        if 'js' in request.params:
            return self._js_login(username, password, location, remember)

        errors = None
        if username and password:
            # form was posted
            errors = self._try_sign_in(username, password, location, remember)
            if errors is None:
                redirect(c.came_from or url(controller='profile', action='home'))

        # show the form, possibly with errors.
        return htmlfill.render(render('login.mako'),
                               errors=errors,
                               error_formatters=u_error_formatters,
                               defaults={'username': username,
                                         'location': location,
                                         'came_from': c.came_from})
コード例 #30
0
ファイル: accounts.py プロジェクト: TetraAsh/baruwa2
 def set_language(self):
     "Set the language"
     nextpage = request.params.get('next', None)
     if not nextpage:
         nextpage = request.headers.get('Referer', None)
     if not nextpage:
         nextpage = '/'
     if '://' in nextpage:
         from_url = urlparse(nextpage)
         nextpage = from_url[2]
     lang_code = request.params.get('language', None)
     if lang_code and check_language(lang_code):
         session['lang'] = lang_code
         session.save()
     params = []
     for param in request.params:
         if not param in ['language', 'amp']:
             value = request.params[param]
             if value:
                 if (param == 'came_from' and
                     '://' in urllib2.unquote(value)):
                     urlparts = urlparse(urllib2.unquote(value))
                     value = urlparts[2] or '/'
                 params.append('%s=%s' % (urllib2.quote(param),
                                         urllib2.quote(value)))
     if 'lc=1' not in params:
         params.append('lc=1')
     if params:
         nextpage = "%s?%s" % (nextpage, '&amp;'.join(params))
     redirect(nextpage)
コード例 #31
0
    def delete(self, user_group_id):
        """DELETE /user_groups/user_group_id: Delete an existing item"""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="DELETE" />
        # Or using helpers:
        #    h.form(url('users_group', user_group_id=ID),
        #           method='delete')
        # url('users_group', user_group_id=ID)
        user_group_id = safe_int(user_group_id)
        c.user_group = UserGroup.get_or_404(user_group_id)
        force = str2bool(request.POST.get('force'))

        try:
            UserGroupModel().delete(c.user_group, force=force)
            Session().commit()
            h.flash(_('Successfully deleted user group'), category='success')
        except UserGroupAssignedException as e:
            h.flash(str(e), category='error')
        except Exception:
            log.exception("Exception during deletion of user group")
            h.flash(_('An error occurred during deletion of user group'),
                    category='error')
        return redirect(url('users_groups'))
コード例 #32
0
ファイル: picture.py プロジェクト: freelizhun/eencms
    def submit(self, id=None):
        if id == 'new':
            image = model.Image()
        else:
            image = model.find_image(int(id))

        rp = request.POST
        f = rp.get('image')
        if not os.path.exists(config['pictures_dir']):
            os.makedirs(config['pictures_dir'])

        image.filename = f.filename
        image.filetype = f.type
        image.filesize = len(f.value)
        if id == 'new':
            model.save(image)
        model.commit()

        newfile = self._pathForImage(image.id)
        nf = open(newfile, 'wb')
        shutil.copyfileobj(f.file, nf)

        return redirect(url(controller='picture', action='list'))
コード例 #33
0
    def submit(self, id=None):
        rp = request.POST
        c.page = c.tree.find_node(id=int(id))
        try:
            content = Session.query(model.Content).get(c.page.content_id)
        except:
            content = model.Content()

        c.page.title = rp.get('title')
        content.content = rp.get('content')
        c.page.menutitle = rp.get('menutitle')
        if not content.id:
            Session.add(content)
        Session.commit()
        c.page.type = 'content'
        c.page.content_id = content.id
        Session.commit()

        return redirect(
            url(controller='page',
                action='view',
                id=c.page.id,
                title=c.page.get_url_title()))
コード例 #34
0
    def i(self, id):

        uuid = self._decodeId(id)

        if len(uuid) == 36:

            sol = solr.SolrConnection(solrconfig.solr_urls['all'])
            sol_response = sol.query("uuid:" + uuid,
                                     fields=['object_type'],
                                     score=False,
                                     rows=1,
                                     start=0)

            if sol_response.numFound > 0:

                return redirect(url(
                    controller='profile',
                    action=sol_response.results[0]['object_type'],
                    id=uuid),
                                code=301)

        c.profile = {}
        return render('/main/profile.mako')
コード例 #35
0
    def reset_password(self, user_id):
        """
        toggle reset password flag for this user

        :param user_id:
        """
        user_id = safe_int(user_id)
        c.user = User.get_or_404(user_id)
        try:
            old_value = c.user.user_data.get('force_password_change')
            c.user.update_userdata(force_password_change=not old_value)
            Session().commit()
            if old_value:
                msg = _('Force password change disabled for user')
            else:
                msg = _('Force password change enabled for user')
            h.flash(msg, category='success')
        except Exception:
            log.exception("Exception during password reset for user")
            h.flash(_('An error occurred during password reset for user'),
                    category='error')

        return redirect(url('edit_user_advanced', user_id=user_id))
コード例 #36
0
ファイル: abuse.py プロジェクト: alex-obi/adhocracy
class AbuseController(BaseController):
    @guard.perm('abuse.report')
    def new(self, format='html', errors={}):
        c.url = request.params.get('url', request.environ.get('HTTP_REFERER'))
        #require.user.message(c.page_user)
        html = render("/abuse/new.html", overlay=format == u'overlay')
        return htmlfill.render(html,
                               defaults=request.params,
                               errors=errors,
                               force_defaults=False)

    @RequireInternalRequest()
    @guard.perm('abuse.report')
    def report(self, format='html'):
        try:
            self.form_result = AbuseReportForm().to_python(request.params)
        except Invalid, i:
            return self.new(errors=i.unpack_errors())

        broadcast.notify_abuse(c.instance, c.user, self.form_result.get('url'),
                               self.form_result.get('message'))
        h.flash(_("Thank you for helping."), 'notice')
        redirect(self.form_result.get('url'))
コード例 #37
0
    def audit_export_status(self, taskid):
        "Audit log export status"
        result = AsyncResult(taskid)
        if result is None or taskid not in session['taskids']:
            flash(_('The task status requested has expired or does not exist'))
            redirect(url('status-audit-logs'))

        if result.ready():
            finished = True
            flash.pop_messages()
            if isinstance(result.result, Exception):
                if c.user.is_superadmin:
                    flash_alert(_('Error occured in processing %s') %
                                result.result)
                else:
                    flash_alert(_('Backend error occured during processing.'))
                redirect(url('status-audit-logs'))
        else:
            session['exportauditlog-counter'] += 1
            session.save()
            if (session['exportauditlog-counter'] >= 20 and
                result.state in ['PENDING', 'RETRY', 'FAILURE']):
                result.revoke()
                del session['exportauditlog-counter']
                session.save()
                flash_alert(_('The audit log export failed, try again later'))
                redirect(url('status-audit-logs'))
            finished = False

        c.finished = finished
        c.results = result.result
        c.success = result.successful()
        d = request.GET.get('d', None)
        if finished and (d and d == 'y'):
            audit_log(c.user.username,
                    5, AUDITLOGEXPORT_MSG, request.host,
                    request.remote_addr, datetime.now())
            response.content_type = result.result['content_type']
            response.headers['Cache-Control'] = 'max-age=0'
            respdata = result.result['f']
            disposition = 'attachment; filename=%s' % result.result['filename']
            response.headers['Content-Disposition'] = disposition
            response.headers['Content-Length'] = len(respdata)
            return respdata
        return render('/status/auditexportstatus.html')
コード例 #38
0
ファイル: repos_groups.py プロジェクト: elfixit/rhodecode
    def show(self, id, format='html'):
        """GET /repos_groups/id: Show a specific item"""
        # url('repos_group', id=ID)

        c.group = RepoGroup.get(id)

        if c.group:
            c.group_repos = c.group.repositories.all()
        else:
            return redirect(url('home'))

        #overwrite our cached list with current filter
        gr_filter = c.group_repos
        c.cached_repo_list = self.scm_model.get_repos(all_repos=gr_filter)

        c.repos_list = c.cached_repo_list

        c.repo_cnt = 0

        c.groups = self.sa.query(RepoGroup).order_by(RepoGroup.group_name)\
            .filter(RepoGroup.group_parent_id == id).all()

        return render('admin/repos_groups/repos_groups.html')
コード例 #39
0
ファイル: remarks.py プロジェクト: xiaomailong/szarp
    def save(self, id=None):
        log.info('id: %s', id)
        user_id = id
        users_q = meta.Session.query(model.Users)

        if user_id is None:
            user = model.Users()
            user.name = request.params['name']
        else:
            user = users_q.get(user_id)
        user.real_name = request.params['real_name']
        if len(request.params['password']) > 0:
            m = hashlib.md5()
            m.update(request.params['password'])
            user.password = m.hexdigest()

        if user_id is None:
            meta.Session.add(user)
            meta.Session.flush()

        bases_q = meta.Session.query(model.Prefix)

        for base in bases_q:
            if request.params.has_key(str(base.id)):
                a = [q for q in user.base if q.prefix.id == base.id]
                if not a:
                    a = model.UsersPrefixAssociation()
                    a.prefix = base
                    a.write_access = 1
                    user.base.append(a)
            else:
                map(lambda x: meta.Session.delete(x),
                    filter(lambda x: x.prefix.id == base.id, user.base))

        meta.Session.commit()

        return redirect(url(controller='remarks', action='index'))
コード例 #40
0
    def fork_create(self, repo_name):
        self.__load_defaults()
        c.repo_info = Repository.get_by_repo_name(repo_name)
        _form = RepoForkForm(old_data={'repo_type': c.repo_info.repo_type},
                             repo_groups=c.repo_groups_choices,
                             landing_revs=c.landing_revs_choices)()
        form_result = {}
        task_id = None
        try:
            form_result = _form.to_python(dict(request.POST))
            # create fork is done sometimes async on celery, db transaction
            # management is handled there.
            task = RepoModel().create_fork(
                form_result, c.rhodecode_user.user_id)
            from celery.result import BaseAsyncResult
            if isinstance(task, BaseAsyncResult):
                task_id = task.task_id
        except formencode.Invalid as errors:
            c.new_repo = errors.value['repo_name']
            return htmlfill.render(
                render('forks/fork.html'),
                defaults=errors.value,
                errors=errors.error_dict or {},
                prefix_error=False,
                encoding="UTF-8",
                force_defaults=False)
        except Exception:
            log.exception(
                u'Exception while trying to fork the repository %s', repo_name)
            msg = (
                _('An error occurred during repository forking %s') %
                (repo_name, ))
            h.flash(msg, category='error')

        return redirect(h.url('repo_creating_home',
                              repo_name=form_result['repo_name_full'],
                              task_id=task_id))
コード例 #41
0
ファイル: auth.py プロジェクト: xuhai008/FreePyBX
 def check(self):
     try:
         if 'user' in session:
             row = AdminUser.query.filter_by(
                 id=session['user_id']).filter_by(
                     session_id=session.id).first()
             if not row:
                 session.invalidate()
                 redirect("/admin/logout")
             c.perms = row.permissions
             for p in c.perms:
                 if 'superuser' in p:
                     return True
             raise AuthenticationError("You have no rights here.")
         else:
             redirect("/admin/logout")
     except:
         redirect("/admin/logout")
コード例 #42
0
ファイル: users.py プロジェクト: seryl/Nodetraq
    def create(self):
        hash_params = ('username', 'name', 'mail',
                       'loginShell', 'title', 'manager',
                       'departmentNumber', 'roomNumber',
                       'orgchartmanager', 'utilityaccount', 'deploycode')
        dh = DirectoryHelper(
                directoryCN, directoryPassword, directoryDomain)

        data_map = {}
        groups = []
        for k,v in request.params.items():
            if k in hash_params:
                data_map[k] = v
            elif k == 'group':
                groups.append(v)

        data_map['username'] = data_map['username'].lower()

        dh.ldap.create(data_map['username'], data_map['name'],
                       data_map['mail'], data_map['loginShell'],
                       data_map['title'], data_map['manager'],
                       data_map['departmentNumber'], data_map['roomNumber'],
                       data_map['deploycode'], data_map['orgchartmanager'],
                       data_map['utilityaccount'] )

        dh.set_groups(data_map['username'], groups)

        session['flash'] = 'Successfully created %s' % data_map['username']
        session.save()

        data_map['account'] = data_map['username']
        ae = ActivityEngine(Session, session['active_user']['user_id'])
        ae.create('user', data_map)

        return redirect(url(
                controller='users', action='edit',
                account=data_map['username']))
コード例 #43
0
ファイル: users.py プロジェクト: seryl/Nodetraq
    def update(self, account):
        update_items = (
            'cn', 'uidNumber', 'mail',
            'loginShell', 'title', 'manager',
            'departmentNumber', 'roomNumber',
            'deploycode', 'orgchartmanager', 'utilityaccount')

        dh = DirectoryHelper(
            directoryCN, directoryPassword, directoryDomain)

        updates = {}
        groups = [v for k,v in request.params.items() if k == 'group']
        for item in update_items:
            if item in request.params:
                if item == 'cn':
                    updates['cn'] = request.params[item]
                    updates['gecos'] = request.params[item]
                    splitname = request.params[item].split()
                    updates['givenName'] = splitname[0]
                    if len(splitname) > 1:
                        updates['sn'] = splitname[1]
                updates[item] = request.params[item]

        # for key in updates, update ldap and ad
        for k, v in updates.iteritems():
            dh.update_attribute(account, k, v)
        # for group in groups, update ldap groups
        dh.set_groups(account, groups)

        session['flash'] = 'Successfully updated %s' % account
        session.save()

        updates['account'] = account
        ae = ActivityEngine(Session, session['active_user']['user_id'])
        ae.update('user', None, updates)

        return redirect(url(controller='users', action='edit', account=account))
コード例 #44
0
    def repo_check(self, repo_name):
        c.repo = repo_name
        task_id = request.GET.get('task_id')

        if task_id and task_id not in ['None']:
            import rhodecode
            from celery.result import AsyncResult
            if rhodecode.CELERY_ENABLED:
                task = AsyncResult(task_id)
                if task.failed():
                    msg = self._log_creation_exception(task.result, c.repo)
                    h.flash(msg, category='error')
                    return redirect(url('home'), code=501)

        repo = Repository.get_by_repo_name(repo_name)
        if repo and repo.repo_state == Repository.STATE_CREATED:
            if repo.clone_uri:
                clone_uri = repo.clone_uri_hidden
                h.flash(_('Created repository %s from %s') %
                        (repo.repo_name, clone_uri),
                        category='success')
            else:
                repo_url = h.link_to(
                    repo.repo_name,
                    h.url('summary_home', repo_name=repo.repo_name))
                fork = repo.fork
                if fork:
                    fork_name = fork.repo_name
                    h.flash(h.literal(
                        _('Forked repository %s as %s') %
                        (fork_name, repo_url)),
                            category='success')
                else:
                    h.flash(h.literal(_('Created repository %s') % repo_url),
                            category='success')
            return {'result': True}
        return {'result': False}
コード例 #45
0
    def password_reset(self):
        settings = Setting.get_app_settings()
        captcha_private_key = settings.get('captcha_private_key')
        c.captcha_active = bool(captcha_private_key)
        c.captcha_public_key = settings.get('captcha_public_key')

        if request.POST:
            password_reset_form = PasswordResetForm()()
            try:
                form_result = password_reset_form.to_python(dict(request.POST))
                if c.captcha_active:
                    from kallithea.lib.recaptcha import submit
                    response = submit(
                        request.POST.get('recaptcha_challenge_field'),
                        request.POST.get('recaptcha_response_field'),
                        private_key=captcha_private_key,
                        remoteip=self.ip_addr)
                    if c.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)
                UserModel().reset_password_link(form_result)
                h.flash(_('Your password reset link was sent'),
                        category='success')
                return redirect(url('login_home'))

            except formencode.Invalid, errors:
                return htmlfill.render(render('/password_reset.html'),
                                       defaults=errors.value,
                                       errors=errors.error_dict or {},
                                       prefix_error=False,
                                       encoding="UTF-8",
                                       force_defaults=False)
コード例 #46
0
    def index(self):
        limit = 100
        default = 20
        if request.params.get('size'):
            try:
                int_size = int(request.params.get('size'))
            except ValueError:
                int_size = default
            int_size = int_size if int_size <= limit else limit
            c.size = int_size
            session['changelog_size'] = c.size
            session.save()
        else:
            c.size = int(session.get('changelog_size', default))

        p = int(request.params.get('page', 1))
        branch_name = request.params.get('branch', None)
        try:
            if branch_name:
                collection = [z for z in
                              c.rhodecode_repo.get_changesets(start=0,
                                                    branch_name=branch_name)]
                c.total_cs = len(collection)
            else:
                collection = c.rhodecode_repo
                c.total_cs = len(c.rhodecode_repo)

            c.pagination = RepoPage(collection, page=p, item_count=c.total_cs,
                                    items_per_page=c.size, branch=branch_name)
            collection = list(c.pagination)
            page_revisions = [x.raw_id for x in collection]
            c.comments = c.rhodecode_db_repo.comments(page_revisions)

        except (RepositoryError, ChangesetDoesNotExistError, Exception), e:
            log.error(traceback.format_exc())
            h.flash(str(e), category='warning')
            return redirect(url('home'))
コード例 #47
0
    def import_status(self, taskid):
        "import domains status"
        result = AsyncResult(taskid)
        if result is None or taskid not in session['taskids']:
            flash(_('The task status requested has expired or does not exist'))
            redirect(url(controller='organizations', action='index'))

        if result.ready():
            finished = True
            flash.pop_messages()
            if isinstance(result.result, Exception):
                if c.user.is_superadmin:
                    flash_alert(
                        _('Error occured in processing %s') % result.result)
                else:
                    flash_alert(_('Backend error occured during processing.'))
                redirect(url(controller='organizations'))
            update_serial.delay()
            info = IMPORTORG_MSG % dict(o='-')
            audit_log(c.user.username, 3, info, request.host,
                      request.remote_addr, datetime.now())
        else:
            session['dimport-counter'] += 1
            session.save()
            if (session['dimport-counter'] >= 10
                    and result.state in ['PENDING', 'RETRY', 'FAILURE']):
                result.revoke()
                try:
                    os.unlink(session['dimport-file'])
                except OSError:
                    pass
                del session['dimport-file']
                del session['dimport-counter']
                session.save()
                flash_alert(
                    _('The import could not be processed,'
                      ' try again later'))
                redirect(url(controller='organizations'))
            finished = False

        c.finished = finished
        c.results = result.result
        c.success = result.successful()
        return render('/organizations/importstatus.html')
コード例 #48
0
ファイル: openidauth.py プロジェクト: alkadis/vcv
    def init(self):
        self.consumer = create_consumer(self.openid_session)
        if not hasattr(self, 'form_result'):
            return self._failure('', _("Invalid input."))
        openid = self.form_result.get("openid")
        try:
            if not openid:
                raise ValueError(_("No OpenID given!"))
            authrequest = self.consumer.begin(openid)

            if not c.user and not model.OpenID.find(openid):
                axreq = ax.FetchRequest(
                    h.base_url('/openid/update', absolute=True))
                axreq.add(
                    ax.AttrInfo(get_ax_mail_schema(openid),
                                alias="email",
                                required=True))
                authrequest.addExtension(axreq)
                sreq = sreg.SRegRequest(required=['nickname'],
                                        optional=['email'])
                authrequest.addExtension(sreq)

            redirecturl = authrequest.redirectURL(h.base_url('/',
                                                             absolute=True),
                                                  return_to=h.base_url(
                                                      '/openid/verify',
                                                      absolute=True),
                                                  immediate=False)
            self.set_session(self.openid_session)
            session.save()
            return redirect(redirecturl)
        except HTTPFound:
            raise
        except Exception, e:
            log.exception(e)
            return self._failure(openid, str(e))
コード例 #49
0
ファイル: teamboxes.py プロジェクト: fdgonthier/kas
    def kws_mgt_kwmo_management(self):
        # Get workspace ID.
        kws_id = get_var("kws_id") or abort(404)

        # Get kcd password.
        if c.mc.kcd_pwd and len(c.mc.kcd_pwd):
            passwd = c.mc.kcd_pwd
        else:
            passwd = c.mc.admin_pwd

        # Get current timestamp.
        stamp = int(time.time())

        # Generate a time-based hash of the password.
        md5 = hashlib.md5()
        md5.update(str(stamp))
        md5.update(passwd)
        hex_hash = md5.digest().encode('hex')

        # Generate the url to redirect to.
        url = "https://%s/teambox_admin/login/%s?stamp=%i&hash=%s" % \
            ( c.mc.kwmo_host, str(kws_id), stamp, str(hex_hash) )

        return redirect(url)
コード例 #50
0
    def permission_global_update(self):
        c.active = 'global'
        self.__load_data()
        _form = UserPermissionsForm(
            [x[0] for x in c.repo_create_choices],
            [x[0] for x in c.repo_create_on_write_choices],
            [x[0] for x in c.repo_group_create_choices],
            [x[0] for x in c.user_group_create_choices],
            [x[0] for x in c.fork_choices],
            [x[0] for x in c.inherit_default_permission_choices])()

        try:
            form_result = _form.to_python(dict(request.POST))
            form_result.update({'perm_user_name': User.DEFAULT_USER})
            PermissionModel().update_user_permissions(form_result)

            Session().commit()
            h.flash(_('Global permissions updated successfully'),
                    category='success')

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

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

        return redirect(url('admin_permissions_global'))
コード例 #51
0
    def index(self):
        requests = request.params
        #if len( requests ) > 0: # a form has been submitted
        #    return self.send()

        c.http_host = ""

        if 'id' in requests:
            c.id = requests['id']

            sol = solr.SolrConnection(solrconfig.solr_urls['all'])
            sol_response = sol.query("id:uuid_" + c.id,
                                     score=False,
                                     rows=1,
                                     start=0)

            if len(sol_response.results) == 1:
                manuscript = None

                obj = sol_response.results[0]
                manuscript = sol_response.results[0]

                if manuscript:

                    c.record = manuscript
                    c.repository = None

                    c.comment = ''
                    c.messages = {}
                    c.name = ''
                    c.email = ''
                    c.http_host = request.url

                    return render('/main/comment.mako')

        return redirect(url(controller='home'))
コード例 #52
0
    def rollOver(self):
        #get the financial start and financial end along with the organisation name and type.
        print request.params
        c.orgname = session['orgname']
        c.financialfrom = session['financialfrom']
        c.financialto = session['financialto']
        c.orgtype = session['orgtype']
        fromdate = datetime.datetime.strptime(
            str(session['financialfrom']),
            "%d-%m-%Y").strftime("%Y-%m-%d %H:%M:%S")
        print fromdate
        c.from_date = session['financialfrom']

        todate = datetime.datetime.strptime(str(
            session['financialto']), "%d-%m-%Y").strftime("%Y-%m-%d %H:%M:%S")
        newTodate = request.params["todated"] + "-" + request.params[
            "todatem"] + "-" + request.params["todatey"]

        print newTodate
        app_globals.server_proxy.rollover(
            [c.orgname, fromdate, todate, newTodate, c.orgtype],
            session["gnukhata"])

        return redirect('/startup/index')
コード例 #53
0
ファイル: settings.py プロジェクト: elfixit/rhodecode
    def my_account(self):
        """
        GET /_admin/my_account Displays info about my account
        """
        # url('admin_settings_my_account')

        c.user = User.get(self.rhodecode_user.user_id)
        all_repos = self.sa.query(Repository)\
                     .filter(Repository.user_id == c.user.user_id)\
                     .order_by(func.lower(Repository.repo_name)).all()

        c.user_repos = ScmModel().get_repos(all_repos)

        if c.user.username == 'default':
            h.flash(_("You can't edit this user since it's"
                      " crucial for entire application"),
                    category='warning')
            return redirect(url('users'))

        defaults = c.user.get_dict()
        return htmlfill.render(render('admin/users/user_edit_my_account.html'),
                               defaults=defaults,
                               encoding="UTF-8",
                               force_defaults=False)
コード例 #54
0
    def index(self):
        limit = 100
        default = 20
        if request.GET.get('size'):
            c.size = max(min(safe_int(request.GET.get('size')), limit), 1)
            session['changelog_size'] = c.size
            session.save()
        else:
            c.size = int(session.get('changelog_size', default))
        # min size must be 1
        c.size = max(c.size, 1)
        p = safe_int(request.GET.get('page', 1), 1)
        branch_name = request.GET.get('branch', None)
        try:
            if branch_name:
                collection = [
                    z for z in c.rhodecode_repo.get_changesets(
                        start=0, branch_name=branch_name)
                ]
                c.total_cs = len(collection)
            else:
                collection = c.rhodecode_repo
                c.total_cs = len(c.rhodecode_repo)

            c.pagination = RepoPage(collection,
                                    page=p,
                                    item_count=c.total_cs,
                                    items_per_page=c.size,
                                    branch=branch_name)
            collection = list(c.pagination)
            page_revisions = [x.raw_id for x in collection]
            c.comments = c.rhodecode_db_repo.get_comments(page_revisions)
            c.statuses = c.rhodecode_db_repo.statuses(page_revisions)
        except (EmptyRepositoryError), e:
            h.flash(str(e), category='warning')
            return redirect(url('summary_home', repo_name=c.repo_name))
コード例 #55
0
ファイル: account.py プロジェクト: asuffield/openspending
 def register(self):
     require.account.create()
     errors, values = {}, None
     if request.method == 'POST':
         try:
             schema = AccountRegister()
             values = request.params
             data = schema.deserialize(values)
             if Account.by_name(data['name']):
                 raise colander.Invalid(
                     AccountRegister.name,
                     _("Login name already exists, please choose a "
                       "different one"))
             if not data['password1'] == data['password2']:
                 raise colander.Invalid(
                     AccountRegister.password1,
                     _("Passwords \
                     don't match!"))
             account = Account()
             account.name = data['name']
             account.fullname = data['fullname']
             account.email = data['email']
             account.password = generate_password_hash(data['password1'])
             db.session.add(account)
             db.session.commit()
             who_api = get_api(request.environ)
             authenticated, headers = who_api.login({
                 "login":
                 account.name,
                 "password":
                 data['password1']
             })
             response.headers.extend(headers)
             return redirect("/")
         except colander.Invalid, i:
             errors = i.asdict()
コード例 #56
0
ファイル: notifications.py プロジェクト: elfixit/rhodecode
    def show(self, notification_id, format='html'):
        """GET /_admin/notifications/id: Show a specific item"""
        # url('notification', notification_id=ID)
        c.user = self.rhodecode_user
        no = Notification.get(notification_id)

        owner = lambda: (no.notifications_to_users.user.user_id == c.user.
                         user_id)
        if no and (h.HasPermissionAny('hg.admin', 'repository.admin')()
                   or owner):
            unotification = NotificationModel()\
                            .get_user_notification(c.user.user_id, no)

            # if this association to user is not valid, we don't want to show
            # this message
            if unotification:
                if unotification.read is False:
                    unotification.mark_as_read()
                    Session.commit()
                c.notification = no

                return render('admin/notifications/show_notification.html')

        return redirect(url('notifications'))
コード例 #57
0
ファイル: velruse.py プロジェクト: alkadis/vcv
    def _login(self, adhocracy_user, redirect_url=None):
        """
        Log the user in and redirect him to a sane place.
        """

        assert adhocracy_user

        login_user(adhocracy_user, request, response)
        session['login_type'] = 'velruse'

        if redirect_url is None:
            if c.instance and not adhocracy_user.is_member(c.instance):
                redirect(
                    h.base_url("/instance/join/%s?%s" %
                               (c.instance.key, h.url_token())))
            else:
                redirect(h.user.post_login_url(adhocracy_user))
        else:
            redirect(redirect_url)
コード例 #58
0
ファイル: user.py プロジェクト: AnonOnWarpath/adhocracy
    def create(self):
        require.user.create()
        # 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(
                    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 = model.Membership(user, c.instance,
                                          c.instance.default_group)
            model.meta.Session.expunge(membership)
            model.meta.Session.add(membership)
            model.meta.Session.commit()

        # info message
        h.flash(
            _("You have successfully registered as user %s.") % user.name,
            'success')
        redirect("/perform_login?%s" % urllib.urlencode(
            {
                'login': self.form_result.get("user_name").encode('utf-8'),
                'password': self.form_result.get("password").encode('utf-8')
            }))
コード例 #59
0
ファイル: mapview.py プロジェクト: dimme/SwFlightPlanner
    def updsharing(self):
        if 'stop' in request.params:
            meta.Session.query(SharedTrip).filter(
                sa.and_(SharedTrip.user == session['user'],
                        SharedTrip.trip == session.get('current_trip',
                                                       None))).delete()
            meta.Session.flush()
            meta.Session.commit()
            redirect(h.url_for(controller='mapview', action="share"))

        if 'share' in request.params:
            secret = ""
            for c in open("/dev/urandom").read(16):
                secret += chr(65 + (ord(c) % 25))
            share = SharedTrip(session['user'], session['current_trip'],
                               secret)
            meta.Session.add(share)
            meta.Session.commit()
            redirect(h.url_for(controller='mapview', action="share"))
        redirect(h.url_for(controller='mapview', action="index"))
コード例 #60
0
    def check_with_closure(self, closure, *a, **kw):

        auth_check = authorization.AuthCheck(method=self.obj.__name__)
        self.obj(auth_check, *a, **kw)

        if self.raise_type == RETURN_AUTH_CHECK:
            return auth_check

        elif self.raise_type == RETURN_BOOL:
            return bool(auth_check)

        else:
            assert (self.raise_type in [RETURN_TEMPLATE, RETURN_DECORATOR])
            if auth_check:
                if self.raise_type == RETURN_DECORATOR:
                    return closure()
                else:
                    return auth_check
            elif auth_check.propose_login():
                # Authentication might help
                from adhocracy.lib.helpers import login_redirect_url
                from pylons.controllers.util import redirect
                redirect(login_redirect_url())
            elif auth_check.propose_join():
                from adhocracy.lib.helpers import join_redirect_url
                from pylons.controllers.util import redirect
                redirect(join_redirect_url())
            elif auth_check.propose_validate_email():
                from adhocracy.lib.helpers import validate_redirect_url
                from pylons.controllers.util import redirect
                redirect(validate_redirect_url())
            else:
                from adhocracy.lib.templating import ret_abort
                log.debug("Aborting due to authorisation error: %s" %
                          repr(self.obj))
                ret_abort(_("We're sorry, but it seems that you lack the "
                            "permissions to continue."),
                          code=403)