Ejemplo n.º 1
0
	def change_password(self):
		c.controller = 'account'
		c.action = 'index'
		m = hashlib.md5()
		m.update(request.params['password'])
		if m.hexdigest() != session['passhash']:
			c.message = _("Incorrect current password!")
			return render('/info.mako')
		new = request.params['new_password']
		new2 = request.params['new_password2']
		if new != new2:
			c.message = _("Passwords do not match!")
			return render('/info.mako')
		bad_password = h.check_password(session['user'], new)
		if bad_password is not None:
			c.message = bad_password
			return render('/info.mako')
		m = hashlib.md5()
		m.update(new)
		new = m.hexdigest()
		app_globals.rpcservice.user_change_password(session['user'], session['passhash'], new)
		session['passhash'] = new
		session.save()
		c.message = _("Password set succesfully")
		return render('/info.mako')
Ejemplo n.º 2
0
def check_flash():
    """If the session data isn't of the particular format python has trouble.
    So we check that it is a dict."""
    if session.has_key('flash'):
        if type(session['flash']) != dict:
            del session['flash']
            session.save()
Ejemplo n.º 3
0
    def update(self, id, format='html'):
        ignore = ['Submit',
                'username']

        params = [
            (p, request.params[p]) for p in request.params \
                if p not in ignore]
        data = {}
        for key, value in params:
            if key == 'cpu_speed' and not value:
                continue
            elif key == 'game' and not value:
                continue
            data[key] = value

        activity_engine = ActivityEngine(Session,
                session['active_user']['user_id'])
        status = activity_engine.update('node', id, data)

        if format =='html':
            session['flash'] = status
            session.save()
            return redirect(url(controller='nodes', action='show', id=id))
        elif format == 'json':
            request.content_type = 'application/json'
            return status
Ejemplo n.º 4
0
    def __before__(self):

        update_session = True
        lang = None
        self.charset = 'utf-8'

        self.root_path = config['root_path']
        self.root_url = config['root_url']
        self.mobile_search_url = config['mobile_search_url']
        self.versionTime = config['versionTime']
        self.yahoo_key = config['yahoo_key']
        self.bing_key = config['bing_key']

        if 'lang' in request.params and self._isLangAvailable(request.params['lang']):
            lang = request.params['lang']
        elif 'lang' in session:
            lang = session['lang']
            update_session = False
        else:
            # get from user agent
            for language in request.languages:
                language = language[0:2]
                if self._isLangAvailable(language):
                    lang = unicode(language)
                    break
        if lang is None:
            lang = unicode(config['lang'])

        if 'charset' in request.params:
           self.charset = request.params['charset']

        set_lang(lang)
        if update_session:
            session['lang'] = lang
            session.save()
Ejemplo n.º 5
0
 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, '&'.join(params))
     redirect(nextpage)
Ejemplo n.º 6
0
	def get_report(self, user):
		report = None
		id = user.GetId()
		if self.mc:
			# Use memcache
			report = self.mc.get("twitter_user_report_for_%s" % str(id))
		else:
			# Use sessions
			if "twitter_user_reports" not in session:
				session["twitter_user_reports"] = {}
			
			if id in session["twitter_user_reports"]:
				report = session["twitter_user_reports"][id]
			else:
				report = None
		
		if not report:
			# Set the total number of followers in the session
			# so we can show the current status via Ajax
			session["follower_count"] = user.GetFollowersCount()
			session.save()
			report_generator = (row for row in OnDeafTweersReport(api=self.tw, user=user))
			report = []
			session["follower_current_num"] = 0;
			for row in report_generator:
				# Set the current follower number, to display
				# the current status via Ajax
				session["follower_current_num"] += 1
				session.save()
				report.append(row)

			self.set_report(user.GetId(), report)
		return report
Ejemplo n.º 7
0
    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))
Ejemplo n.º 8
0
    def login_validate(self):
    
        if (c.userid != "false"):
             redirect(url('/users/login?m=2'))
        session['logged_in'] = True
        session.save()    
            
        if request.method == 'POST':
            loginform = LoginForm(request.POST)
            if   loginform.is_valid():

                userid = authenticate_user(loginform.cleaned_data['email'], \
                         loginform.cleaned_data['password'])

                if (userid != "invalid" ):
                    session['userid'] = userid
                    session.save()
                    print session['userid']
                    c.login = "******"
                    print loginform.cleaned_data['redirect']
                    if request.POST['redirect']=='null':                  
                        redirect(url('/'))
                    else:
                        redirect(url(str(loginform.cleaned_data['redirect'])))
                else:
                    c.login = "******"
                    c.form = LoginForm(request.POST)
                    return render("/users/login.mako")
            else:
                 c.form = LoginForm(request.POST)
                 return render("/users/login.mako")
        redirect(url('/'))
Ejemplo n.º 9
0
    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'))
Ejemplo n.º 10
0
 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)
Ejemplo n.º 11
0
def authenticated_user(reload=False):
    """
    Returns reference to AuthenticatedUser which is stored in session.
    If it's not in session method will add it and save session, then return object.
    """

    AUTHENTICATED_USER = "******"

    # Create authenticated user if it doesn't exist
    if request.environ.has_key('REMOTE_USER'):
        if reload or not session.has_key(AUTHENTICATED_USER) \
            or session[AUTHENTICATED_USER] == None \
            or session[AUTHENTICATED_USER].username != request.environ['REMOTE_USER']:
            model = request.environ['sqlalchemy.model']
            db = request.environ['sqlalchemy.session']

            try:
                authenticated_user = db.query(model.AuthenticatedUser).filter_by(username=request.environ['REMOTE_USER']).one()
            except:
                authenticated_user = model.AuthenticatedUser(
                    username = request.environ['REMOTE_USER'], email = request.environ['REMOTE_USER'])
                db.save(authenticated_user)
                db.commit()
                log.info(_("Created an %s" % (str(authenticated_user))))
            db.expunge(authenticated_user)
            session[AUTHENTICATED_USER] = authenticated_user
            session.save()
    
        return session[AUTHENTICATED_USER]

    if session.has_key(AUTHENTICATED_USER):
        session.pop(AUTHENTICATED_USER, None)
        session.save()

    return None
Ejemplo n.º 12
0
    def updatebyname(self, name, format='html'):
        id = Session.query(Node).filter(Node.hostname == name).first()
        if id:
            id = id.id
        else:
            return 'Host: %s is not in nodetraq' % name

        ignore = ['Submit',
                'username']

        params = [
            (p, request.params[p]) for p in request.params \
                if p not in ignore]
        data = {}
        for key, value in params:
            if value:
                if key == 'cpu_speed' and not value:
                    continue
                data[key] = value

        activity_engine = ActivityEngine(Session,
                session['active_user']['user_id'])
        status = activity_engine.update('node', id, data)

        if format =='html':
            session['flash'] = status
            session.save()
            return redirect(url(controller='nodes', action='show', id=id))
        elif format == 'json':
            request.content_type = 'application/json'
            return status
Ejemplo n.º 13
0
    def logged_in(self):
        # we need to set the language via a redirect
        lang = session.pop('lang', None)
        session.save()

        # we need to set the language explicitly here or the flash
        # messages will not be translated.
        i18n.set_lang(lang)

        if c.user:
            is_new = False
            is_sysadmin = new_authz.is_sysadmin(c.user)

            # Retrieve information about the current user
            context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author,
                   'schema': schema.user_new_form_schema()}
            data_dict = {'id': c.user}

            user_dict = get_action('user_show')(context, data_dict)

            # This check is not needed (or correct) for sys admins
            if not is_sysadmin:

                # Get all organizations and all groups the user belongs to
                orgs_q = model.Session.query(model.Group) \
                    .filter(model.Group.is_organization == True) \
                    .filter(model.Group.state == 'active')
                q = model.Session.query(model.Member) \
                    .filter(model.Member.table_name == 'user') \
                    .filter(model.Member.table_id == user_dict['id'])

                group_ids = []
                for row in q.all():
                    group_ids.append(row.group_id)

                if not group_ids:
                    is_new = True
                else:
                    orgs_q = orgs_q.filter(model.Group.id.in_(group_ids))

                    orgs_list = model_dictize.group_list_dictize(orgs_q.all(), context)

                    if len(orgs_list) == 0:
                        is_new = True

            h.flash_success(_("<p><strong>Note</strong></p>"
                "<p>%s is now logged in</p>") %
                user_dict['display_name'], allow_html=True)

            if is_new:
                return h.redirect_to(controller='ckanext.canada.controller:CanadaController',
                                         action='view_new_user', locale=lang)
            else:
                return h.redirect_to(controller='package',
                    action='search', locale=lang)
        else:
            h.flash_error(_('Login failed. Bad username or password.'))
            return h.redirect_to(controller='user',
                action='login', locale=lang)
Ejemplo n.º 14
0
def check_flash():
    # If the session data isn't of the particular format python has trouble.
    # So we check that it is a dict.
    if session.has_key("flash"):
        if type(session["flash"]) != dict:
            del session["flash"]
            session.save()
Ejemplo n.º 15
0
    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))
Ejemplo n.º 16
0
    def logged_in(self):
        # we need to set the language via a redirect
        lang = session.pop('lang', None)
        session.save()
        came_from = request.params.get('came_from', '')

        # we need to set the language explicitly here or the flash
        # messages will not be translated.
        i18n.set_lang(lang)

        if c.user:
            context = None
            data_dict = {'id': c.user}

            user_dict = get_action('user_show')(context, data_dict)

            h.flash_success(_("%s is now logged in") %
                            user_dict['display_name'])
            if came_from:
                return h.redirect_to(str(came_from))
            return self.me()
        else:
            err = _('Login failed. Bad username or password.')
            if g.openid_enabled:
                err += _(' (Or if using OpenID, it hasn\'t been associated '
                         'with a user account.)')
            if h.asbool(config.get('ckan.legacy_templates', 'false')):
                h.flash_error(err)
                h.redirect_to(locale=lang, controller='user',
                              action='login', came_from=came_from)
            else:
                return self.login(error=err)
Ejemplo n.º 17
0
    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'))
                axreq.add(ax.AttrInfo(AX_MAIL_SCHEMA, alias="email",
                                      required=True))
                authrequest.addExtension(axreq)
                sreq = sreg.SRegRequest(required=['nickname'],
                                        optional=['email'])
                authrequest.addExtension(sreq)

            redirecturl = authrequest.redirectURL(
                h.base_url('/'),
                return_to=h.base_url('/openid/verify'),
                immediate=False)
            session['openid_session'] = self.openid_session
            session.save()
            return redirect(redirecturl)
        except HTTPFound:
            raise
        except Exception, e:
            log.exception(e)
            return self._failure(openid, str(e))
Ejemplo n.º 18
0
def autorize():
    loged_in = session.get("loged_in")
    if loged_in:
        email = session.get("email")
        password = session.get("password")
        pers = Session.query(Person).filter_by(email=email, password=password).first()
        pers.last_activity = int(time.time())
        Session.commit()
        return True
    if "email" and "password" in request.cookies:
        email = request.cookies.get("email")
        password = request.cookies.get("password")
    elif request.method == "POST" and "email" in request.POST:
        email = request.POST.get("password")
        password = md5(request.POST.get("password"))
    else:
        return False
    pers = Session.query(Person).filter_by(email=email, password=password).first()
    if pers:
        print "pers is ", pers
        session["email"] = email
        session["password"] = password
        session["loged_in"] = True
        session["name"] = pers.name
        session["person_id"] = pers.id
        session.save()
        return True
    return False
Ejemplo n.º 19
0
    def login(self, error=None):
        lang = session.pop('lang', None)
        if lang:
            session.save()
            return h.redirect_to(locale=str(lang), controller='user',
                                 action='login')
        if 'error' in request.params:
            h.flash_error(request.params['error'])

        if request.environ['SCRIPT_NAME'] and g.openid_enabled:
            # #1662 restriction
            log.warn('Cannot mount CKAN at a URL and login with OpenID.')
            g.openid_enabled = False

        if not c.user:
            came_from = request.params.get('came_from', '')
            c.login_handler = h.url_for(
                self._get_repoze_handler('login_handler_path'),
                came_from=came_from)
            if error:
                vars = {'error_summary': {'': error}}
            else:
                vars = {}
            return render('user/login.html', extra_vars=vars)
        else:
            return render('user/logout_first.html')
Ejemplo n.º 20
0
    def link_google(self, registration):
        openid_session = session.get("openid_session", {})
        openid_store = None # stateless
        cons = Consumer(openid_session, openid_store)

        GOOGLE_OPENID = 'https://www.google.com/accounts/o8/id'
        try:
            authrequest = cons.begin(GOOGLE_OPENID)
        except DiscoveryFailure:
            h.flash(_('Authentication failed, please try again.'))
            redirect(registration.url(action='personal_info'))

        ax_req = ax.FetchRequest()
        ax_req.add(ax.AttrInfo('http://axschema.org/namePerson/first',
                               alias='firstname', required=True))
        ax_req.add(ax.AttrInfo('http://axschema.org/namePerson/last',
                               alias='lastname', required=True))
        ax_req.add(ax.AttrInfo('http://schema.openid.net/contact/email',
                               alias='email', required=True))
        authrequest.addExtension(ax_req)

        session['openid_session'] = openid_session
        session.save()

        realm = url(controller='home', action='index', qualified=True)
        return_to = registration.url(action='google_verify', qualified=True)

        redirect(authrequest.redirectURL(realm, return_to))
Ejemplo n.º 21
0
Archivo: user.py Proyecto: abulte/ckan
    def logged_in(self):
        # we need to set the language via a redirect
        lang = session.pop('lang', None)
        session.save()

        # we need to set the language explicitly here or the flash
        # messages will not be translated.
        ckan.lib.i18n.set_lang(lang)

        if c.user:
            context = {'model': model,
                       'user': c.user}

            data_dict = {'id': c.user}

            user_dict = get_action('user_show')(context, data_dict)

            h.flash_success(_("%s is now logged in") %
                            user_dict['display_name'])
            return self.me(locale=lang)
        else:
            err = _('Login failed. Bad username or password.')
            if g.openid_enabled:
                err += _(' (Or if using OpenID, it hasn\'t been associated '
                         'with a user account.)')
            h.flash_error(err)
            h.redirect_to(locale=lang, controller='user', action='login')
Ejemplo n.º 22
0
def authenticate_admin(username, password):
    
    auth_user = AdminUser.query.filter(AdminUser.username==username).first()

    if not auth_user:
        log.debug("No user named: '%s'", username)
        return False        
    elif not auth_user.password:
        log.error("Bad username/pass:'******'")
        return False
    elif password != auth_user.password:
        log.debug("Database password for user '%s'", username)
        return False
    else:
        request.environ["REMOTE_USER"] = auth_user.username
        request.environ["HTTP_REMOTE_USER"] = auth_user.username

    session["perms"]= auth_user.permissions
    session["user"] = auth_user
    session["name"] = auth_user.name
    session['user_id'] = auth_user.id

    auth_user.register_login(username, session, request)  
    db.commit()
    db.flush()
    session.save()
    return True
Ejemplo n.º 23
0
 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))
Ejemplo n.º 24
0
    def login_validate(self):
        if (c.userid != "false"):
             redirect(url('/users/login?m=2'))
        session['logged_in'] = True
        session.save()    
            
        if request.method == 'POST':
            c.form = LoginForm(request.POST)
            if c.form.is_valid():

                userid = authenticate_user(c.form.cleaned_data['email'], \
                         c.form.cleaned_data['password'])
                print "hellooooo", c.form.cleaned_data['email'], c.form.cleaned_data['password']
                if (userid != "invalid" ):
                    session['userid'] = userid
                    session.save()
                    print session['userid']
                    redirect(url('/'))
                    c.login = "******"
                else:
                 c.login = "******"

            else:
                 c.form = LoginForm(request.POST)

        return render("/users/login.mako")
Ejemplo n.º 25
0
 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))
Ejemplo n.º 26
0
	def authorize(self):
		context = self._get_context()

		try:
			tk.check_access('oauth2provider_token_create', context)
		except tk.NotAuthorized:
			return tk.abort(401)

		client_id = self._get_required_param('client_id')
		response_type = tk.request.params.get('redirect_uri', 'code')
		scopes = self._get_required_param('scope').split(' ')
		redirect_uri = tk.request.params.get('redirect_uri', '')
		state = tk.request.params.get('state', '')

		if state:
			session['oauth2provider_state'] = state
			session.save()

		client = Client.get(client_id=client_id)

		data = {
			'client_name': client.name,
			'client_id': client.client_id,
			'response_type': response_type,
			'redirect_uri': redirect_uri,
			'scopes': scopes,
		}

		vars = {'data': data, 'action': 'authorize'}
		return tk.render('ckanext/oauth2provider/authorize.html',
			extra_vars=vars)
Ejemplo n.º 27
0
def UpdateUserPoints(UserID):

    # Start user point count
    UserPoints = 0

    # Query all complete unique solutions
    challenges = Challenges.QueryAllChallenges()
    for challenge in challenges:
        if Solutions.HasUserSolvedChallenge(UserID, challenge.ChallengeID):
            UserPoints += Challenges.ChallengeQueryID(challenge.ChallengeID).Points

            # Query all achievements
    achievements = Achievements.AchievementsQueryUserID(UserID)
    for achievement in achievements:
        UserPoints += int(achievement.AchievementScore)

        # Update this user's score in the database
    ExistingUsers = Session.query(UsersTable).filter(UsersTable.UserID == UserID).all()

    # Commit changes
    if len(ExistingUsers) == 1:
        ExistingUsers[0].UserPoints = UserPoints
        Session.commit()

        # Post to session if we have a matching ID (otherwise, just return the user points)
    if session.get("UserID") and session["UserID"] == UserID:
        session["UserPoints"] = UserPoints
        session.save()
    return UserPoints
Ejemplo n.º 28
0
    def submit(self):
        """
        Verify username and password
        """
        # Both fields filled?
        form_username = str(request.params.get('username'))
        form_password = str(request.params.get('password'))

        # Get user data from database
        db_user = meta.Session.query(User).filter(User.username==form_username).first()
        if db_user is None: # User does not exist
            return render('login.mako')

        # AUTHENTIC USER HERE
        #if db_user.passwd != md5.md5(form_password).hexdigest():
        #    return render('login.mako')

        # Mark user as logged in
        session['user'] = form_username
        session.save()

        # Send user back to the page he originally wanted to get to
        if session.get('path_before_login'):
            redirect_to(session['path_before_login'])
        else: # if previous target is unknown just send the user to a welcome page
            return redirect_to(controller='application', action='index')
Ejemplo n.º 29
0
    def changedir(self):
        # Grab params
        box = request.params.get('box').decode('latin1')
        dir = request.params.get('dir').decode('latin1')

        # Check a host exists
        if 'host' not in session[SESS_KEY][box]:
            return

        path = session[SESS_KEY][box]['path']
        account = int(session[SESS_KEY][box]['host'] or 0)

        # Clean input
        dir = dir[:-1] if dir[-1] == '/' else dir

        # Change full path
        if dir == '..Parent Directory':
            arr = session[SESS_KEY][box]['path'].split('/')
            path = '/'.join(arr[:-1])
            if not path:
                path = '/'
        elif dir == '..User Home Directory':
            path = '~'
        elif dir == '..Home Directory':
            path = None
        elif dir == '..Refresh Listing':
            pass
        else:
            path = path + '/' + dir

        # Update listing
        session[SESS_KEY][box]['path'] = path
        session.save()
        self._updatelisting(box, path)
Ejemplo n.º 30
0
def UserSetIconID(UserID, IconID):

    # Convert to integer
    if not IconID.isdigit():
        return "Error: IconID is not an integer."
    else:
        IconID = int(IconID)

        # Bounds check the icon ID (should only range betwee [0, 18]
    if IconID < 0 or IconID > 19:
        return "Error: IconID is out of range."

        # Update this user's score in the database
    ExistingUsers = Session.query(UsersTable).filter(UsersTable.UserID == UserID).all()

    # Commit changes
    if len(ExistingUsers) == 1:
        ExistingUsers[0].IconID = IconID
        Session.commit()
    else:
        return "Error: No users found."

        # Post to session if we have a matching ID (otherwise, just return the user points)
    if session.get("UserID") and session["UserID"] == UserID:
        session["UserIconID"] = IconID
        session.save()

        # All done!
    return "Icon change saved!"
Ejemplo n.º 31
0
    def mailq(self, serverid=None, queue='inbound', page=1, direction='dsc',
        order_by='timestamp'):
        "Display mailqueue"
        server = None
        if not serverid is None:
            server = self._get_server(serverid)
            if not server:
                abort(404)

        c.queue = queue
        c.server = server
        c.direction = direction
        c.order_by = desc(order_by) if direction == 'dsc' else order_by
        if queue == 'inbound':
            qdirection = 1
        else:
            qdirection = 2

        num_items = session.get('mailq_num_items', 10)

        query = Session.query(MailQueueItem).filter(
                MailQueueItem.direction == qdirection).order_by(order_by)

        if server:
            query = query.filter(MailQueueItem.hostname == server.hostname)

        uquery = UserFilter(Session, c.user, query, model=MailQueueItem)
        query = uquery.filter()

        c.form = MailQueueProcessForm(request.POST, csrf_context=session)
        pages = paginate.Page(query, page=int(page), items_per_page=num_items)
        choices = [(str(item.id), item.id) for item in pages.items]
        session['queue_choices'] = choices
        session.save()

        c.page = paginate.Page(query, page=int(page),
                                items_per_page=num_items)
        return render('/status/mailq.html')
Ejemplo n.º 32
0
 def update(self):
     identity = request.environ.get("repoze.who.identity")
     if not identity:
         came_from = "/update"
         session['login_flash'] = "Please login to update your details"
         session.save()
         destination = "/login?came_from=%s" % came_from
         return redirect(destination, code=303)
     userid = identity['repoze.who.userid']
     #if not (identity['repoze.who.userid'] == userid):
     #    session['browse_flash'] = "You are not authorized to change the registration details for %s"%userid
     #    session.save()
     #    return redirect(url(controller='vocabs', action='index'), code=303)
     params = request.POST
     if not ('firstname' in params and params['firstname']) and \
        not ('lastname' in params and params['lastname']) and \
        not ('email' in params and params['email']) and \
        not ('dept' in params and params['dept']) and \
        not ('password' in params and params['password']):
         c.userid = userid
         c.user_det = get_mediator_details(c.userid)
         return render('/update.html')
     if not ('username' in params
             and params['username']) or not (params['username'] == userid):
         c.message = "The userid on record did not match the one sent"
         c.userid = userid
         c.user_det = get_mediator_details(c.userid)
         return render('/update.html')
     if 'username' in params and params['username'] and \
        'password' in params and params['password']:
         ag.passwdfile.update(params['username'], params['password'])
         ag.passwdfile.save()
     #Write user metadata and save the rdf file
     update_mediator(params)
     c.message = "Your details have been updated!"
     c.userid = userid
     c.user_det = get_mediator_details(c.userid)
     return render('/update.html')
Ejemplo n.º 33
0
    def bulk_update(self):
        for k, v in request.params.iteritems():
            data = json.loads(k)
            # updates
            for update in data['updates']:
                try:
                    node_backup = Session.query(NodeDatabaseBackup).filter(
                        NodeDatabaseBackup.id == update['id']).first()
                    node_backup.server = Session.query(Node)\
                        .filter(Node.hostname == update['server']).first()
                    node_backup.server_id = node_backup.server.id
                    node_backup.storage = Session.query(Node)\
                        .filter(Node.hostname == \
                                    update['storage']).first()
                    node_backup.storage_id = node_backup.storage.id
                    node_backup.directory = update['directory']
                    node_backup.enabled = update['enabled']

                    if node_backup.storage and node_backup.server:
                        Session.add(node_backup)
                        Session.commit()
                except Exception as e:
                    session['flash'] = "Error: %s" % e
                    session.save()
                    return {"success": False}

            # new backups
            for backup in data['new_backups']:
                try:
                    node = Session.query(Node).filter(
                        Node.hostname == backup['server']).first()
                    if not node.db_backups:
                        node.db_backups = []

                    node_backup = NodeDatabaseBackup()
                    node_backup.enabled = backup['enabled']
                    node_backup.server = node
                    node_backup.server_id = node_backup.server.id
                    node_backup.storage = Session.query(Node)\
                        .filter(Node.hostname == \
                                    backup['storage']).first()
                    node_backup.storage_id = node_backup.storage.id
                    node_backup.directory = backup['directory']

                    if node_backup.storage and node_backup.server:
                        Session.add(node_backup)
                        Session.commit()
                        node.db_backups.append(node_backup)
                        Session.add(node)
                        Session.commit()
                except Exception as e:
                    session['flash'] = "Error: %s" % e
                    session.save()
                    return {"success": False}

        session['flash'] = "Successfully updated backups!"
        session.save()
        return {"success": True}
Ejemplo n.º 34
0
    def _identify_user_default(self):
        '''
        Identifies the user using two methods:
        a) If they logged into the web interface then repoze.who will
           set REMOTE_USER.
        b) For API calls they may set a header with an API key.
        '''

        # environ['REMOTE_USER'] is set by repoze.who if it authenticates a
        # user's cookie. But repoze.who doesn't check the user (still) exists
        # in our database - we need to do that here. (Another way would be
        # with an userid_checker, but that would mean another db access.
        # See: http://docs.repoze.org/who/1.0/narr.html#module-repoze.who\
        # .plugins.sql )
        c.user = request.environ.get('REMOTE_USER', '')
        if c.user:
            c.user = c.user.decode('utf8')
            c.userobj = model.User.by_name(c.user)
            if c.userobj is None or not c.userobj.is_active():
                # This occurs when a user that was still logged in is deleted,
                # or when you are logged in, clean db
                # and then restart (or when you change your username)
                # There is no user object, so even though repoze thinks you
                # are logged in and your cookie has ckan_display_name, we
                # need to force user to logout and login again to get the
                # User object.
                session['lang'] = request.environ.get('CKAN_LANG')
                session.save()

                ev = request.environ
                if 'repoze.who.plugins' in ev:
                    pth = getattr(ev['repoze.who.plugins']['friendlyform'],
                                  'logout_handler_path')
                    h.redirect_to(pth)
        else:
            c.userobj = self._get_user_for_apikey()
            if c.userobj is not None:
                c.user = c.userobj.name
Ejemplo n.º 35
0
Archivo: xhr.py Proyecto: crosson/NIPAP
    def get_current_vrfs(self):
        """ Return VRF filter list from session variable

            Before returning list, make a search for all VRFs currently in the
            list to verify that they still exist.
        """

        # Verify that all currently selected VRFs still exists
        cur_vrfs = session.get('current_vrfs', {}).items()
        if len(cur_vrfs) > 0:
            q = {'operator': 'equals', 'val1': 'id', 'val2': cur_vrfs[0][0]}

            if len(cur_vrfs) > 1:
                for vrf_id, vrf in cur_vrfs[1:]:
                    q = {
                        'operator': 'or',
                        'val1': q,
                        'val2': {
                            'operator': 'equals',
                            'val1': 'id',
                            'val2': vrf_id
                        }
                    }

            res = VRF.search(q)

            session['current_vrfs'] = {}
            for vrf in res['result']:
                session['current_vrfs'][vrf.id] = {
                    'id': vrf.id,
                    'rt': vrf.rt,
                    'name': vrf.name,
                    'description': vrf.description
                }

            session.save()

        return json.dumps(session.get('current_vrfs', {}))
Ejemplo n.º 36
0
    def _login(self, invitation, password= None):
        # Set info in session.
        session['mode'] = MODE_WS
        session['email_id'] = invitation.email_id
        session['user_id'] = invitation.user_id
        session['secure'] = c.workspace.secured
        # TODO account for password changes
        session['password'] = password

        c.perms.addRole('normal')

        user = User.get_by(workspace_id=invitation.kws_id, id=invitation.user_id)
        if user:
            session['user'] = user.to_dict()
 
        # Save session.
        session.save()
       
        # Do a last minute permissions check on KCD.
        self._check_perms()
        
        # Redirect to teambox url.
        redirect_to(url('teambox', workspace_id = session['workspace_id']))
Ejemplo n.º 37
0
    def recomputeMorphemeReferences_(self):
        """Compute the values of Form.morphemeBreakIDs, Form.morphemeGlossIDs
        and Form.syntacticCategoryString for each Form in the database.

        WARNING, this is a computationally intensive and long-running script.
        With a database of 20,000 Forms, this took about 20 minutes to run on
        a MBP 2.26GHz 2GB ram.
        
        """

        i = 1
        forms = meta.Session.query(model.Form).all()
        for form in forms:
            syntacticCategoryString = form.syntacticCategoryString
            form.getMorphemeIDLists(meta, model)
            meta.Session.commit()
            i += 1
        meta.Session.commit()

        session['flash'] = 'Morpheme references have been recomputed.'
        session.save()

        return render('/derived/administer/index.html')
    def add(self, id):
        if not id:
            abort(409, 'Dataset not identified')
        preview_list = pylons_session.get('preview_list', [])

        pkg = model.Package.get(id)
        if not pkg:
            abort(404, 'Dataset not found')

        if not self._get(pkg.id):
            extent = (pkg.extras.get('bbox-north-lat'),
                      pkg.extras.get('bbox-west-long'),
                      pkg.extras.get('bbox-east-long'),
                      pkg.extras.get('bbox-south-lat'))
            preview_list.append({
                'id': pkg.id,
                'querystring': self._querystring(pkg),
                'name': pkg.name,
                'extent': extent,
            })
            pylons_session['preview_list'] = preview_list
            pylons_session.save()
        return self.view()
Ejemplo n.º 39
0
    def _generate_internal_metadata(self):
        session.cookie_expires = False
        session.cookie_domain = '.sabayon.org'

        c.HTTP_PROTOCOL = model.config.get_http_protocol(request)
        if model.config.is_https(request):
            c.site_uri = model.config.SITE_URI_SSL
            c.forum_uri = model.config.FORUM_URI_SSL
        else:
            c.site_uri = model.config.SITE_URI
            c.forum_uri = model.config.FORUM_URI
        c.login_uri = model.config.LOGIN_URI
        c.www_current_url = construct_url(request.environ)

        c.this_uri = request.environ.get('PATH_INFO')
        if request.environ.get('QUERY_STRING'):
            c.this_uri += '?' + request.environ['QUERY_STRING']
        c.this_uri_full = model.config.SITE_URI + c.this_uri
        c.this_uri_full_quoted = urllib.quote(
            model.config.htmlencode(c.this_uri_full))

        self._generate_login_statistics()
        session.save()
Ejemplo n.º 40
0
    def add_current_vrf(self):
        """ Add VRF to filter list session variable
        """

        vrf_id = request.json['vrf_id']

        if vrf_id is not None:

            if vrf_id == 'null':
                vrf = VRF()
            else:
                vrf_id = int(vrf_id)
                vrf = VRF.get(vrf_id)

            session['current_vrfs'][vrf_id] = {
                'id': vrf.id,
                'rt': vrf.rt,
                'name': vrf.name,
                'description': vrf.description
            }
            session.save()

        return json.dumps(session.get('current_vrfs', {}))
Ejemplo n.º 41
0
    def delete(self, id):
        """Delete the BLD Researcher with ID=id.
        
        """

        if id is None:
            abort(404)
        researcher_q = meta.Session.query(model.User)
        researcher = researcher_q.get(int(id))
        if researcher is None:
            abort(404)
        meta.Session.delete(researcher)
        meta.Session.commit()

        # Destroy the researcher's directory in the files directory
        h.destroyResearcherDirectory(researcher)

        # Update the users variable in app_globals
        tags = h.getSecondaryObjects(['users'])
        app_globals.users = tags['users']
        session['flash'] = "Researcher %s has been deleted" % id
        session.save()
        redirect(url(controller='people'))
Ejemplo n.º 42
0
    def token(self):
        """ Return a session token, one-time hash and password hash
        for the user.
        """
        # Ensure Content-type is text/xml
        if request.headers.get("Content-Type", "").startswith("text/xml") is False:
            return self._auth_abort(417, 'Invalid Parameter')

        # Retrieve request XML body
        payload = request.body
        if payload is None:
            log.error('Empty payload in auth:token()')
            return self._auth_abort(417, 'Invalid Parameter')

        # Retrieve the salt from the model
        authModel = AuthenticateModel.AuthenticateModel()
        login = authModel.getTokenLogin(payload)
        if login is None:
            return self._auth_abort(417, 'Invalid Parameter')

        salt = authModel.getTokenLoginSalt(login)
        if salt is None:
            log.debug('Invalid user %s', login)
            salt = encode(hashlib.sha1(os.urandom(4)).digest())

        session['token'] = encode(hashlib.sha1(os.urandom(8)).digest())
        session['token_salt'] = encode(hashlib.sha1(os.urandom(8)).digest())
        session['salt'] = salt
        session['login'] = login
        session.save()

        c.token_salt = session['token_salt']
        c.salt = salt

        response.set_cookie('token', session['token'])
        response.headers['content-type'] = 'text/xml; charset=utf-8'
        return render('/token.xml')
Ejemplo n.º 43
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'))
Ejemplo n.º 44
0
    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']))
Ejemplo n.º 45
0
    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))
Ejemplo n.º 46
0
    def submit(self, id=None):
        if id == 'new':
            usr = model.CMSUser()
        else:
            usr = model.find_cmsuser(int(id))

        errors = []
        rp = request.POST
        usr.fullname = rp.get('fullname')
        usr.username = rp.get('username')
        if rp.get('password1') and rp.get('password1') == rp.get('password2'):
            usr.password = security.hash_password(rp.get('password1'))

        if id == 'new' and not usr.password:
            errors.append({
                'field':
                'password1',
                'message':
                "een wachtwoord is verplicht bij nieuwe gebruikers"
            })
        if not usr.username:
            errors.append({
                'field': 'username',
                'message': "dit veld moet worden ingevuld"
            })

        if errors:
            session['post'] = rp
            session['errors'] = errors
            session.save()
            redirect(url.current(action='edit'))

        if id == 'new':
            model.save(usr)
        model.commit()

        return redirect(url(controller='cmsuser', action='list'))
Ejemplo n.º 47
0
    def save(self):
        if hasattr(self, 'idx'):
            self.idx += 1
        else:
            self.idx = 1
        if 'orig_aircraft' in request.params:
            bad = self.do_save()
            if bad:
                print "Save failed", bad
                return self.index(bad, orig=request.params['orig_aircraft'])

        if request.params.get('del_button', False):

            for trip in meta.Session.query(Trip).filter(
                    sa.and_(Trip.user == session['user'], Trip.aircraft ==
                            request.params['orig_aircraft'])).all():
                trip.aircraft = None

            meta.Session.query(Aircraft).filter(
                sa.and_(Aircraft.user == session['user'], Aircraft.aircraft ==
                        request.params['orig_aircraft'])).delete()
            session['cur_aircraft'] = None
            session.save()

        if request.params.get('change_aircraft', None) != request.params.get(
                'orig_aircraft', None) and request.params.get(
                    'change_aircraft', False):
            session['cur_aircraft'] = request.params['change_aircraft']
            session.save()
        flash = None
        if request.params.get('add_button', False):
            i = None
            cur_acname = "SE-ABC"
            while True:
                if i != None:
                    cur_acname += "(%d)" % (i, )
                if meta.Session.query(Aircraft).filter(
                        sa.and_(Aircraft.user == session['user'],
                                Aircraft.aircraft == cur_acname)).count() == 0:
                    break
                if i == None: i = 2
                else: i += 1
            a = Aircraft(session['user'], cur_acname)
            a.advanced_model = False
            meta.Session.add(a)
            flash = 'new'
            session['cur_aircraft'] = cur_acname
            session.save()
        meta.Session.flush()
        meta.Session.commit()
        if 'navigate_to' in request.params and len(
                request.params['navigate_to']) > 0:
            redirect(request.params['navigate_to'].encode('utf8'))
        else:
            print "Redirect to index"
            redirect(
                h.url_for(controller='aircraft', action="index", flash=flash))
Ejemplo n.º 48
0
    def login(self):
        """Authenticate the user on ocsmanager.
        """

        if not "ocsmanager" in request.cookies:
            return self._auth_abort(403, 'Invalid Session')
        if not "token" in session:
            return self._auth_abort(403, 'Invalid Session')
        if not "token" in request.cookies:
            return self._auth_abort(403, 'Invalid Token')
        if request.cookies.get('token') != session['token']:
            return self._auth_abort(403, 'Invalid Token')
        if not "login" in session:
            return self._auth_abort(403, 'Invalid Session')

        payload = request.body
        if payload is None:
            log.error('Empty payload in auth:login()')
            return self._auth_abort(417, 'Invalid Parameter')

        authModel = AuthenticateModel.AuthenticateModel()
        (error, msg) = authModel.verifyPassword(session['login'],
                                                session['token_salt'],
                                                session['salt'], payload)
        if error is True:
            response.delete_cookie('token')
            session['token'] = None
            return self._auth_abort(401, 'Invalid credentials')

        # Authentication was successful, remove auth token - no longer needed
        session['token'] = None
        response.delete_cookie('token')
        session['tokenLogin'] = hashlib.sha1(os.urandom(8)).hexdigest()
        session.save()
        c.tokenLogin = encode(session['tokenLogin'])
        c.ttl = 10
        return render('/login.xml')
Ejemplo n.º 49
0
    def index(self):
        flickr = FlickrAPI()
        token = flickr.get_token(request.GET.getone('frob'))

        session['flickr_token'] = token
        session.save()

        flickr = FlickrAPI(token)
        result = flickr.auth_checkToken()
        nsid = result[0][2].get('nsid')

        if session.get('user_id'):
            # a user is already logged in
            user = Session.query(User).filter_by(
                id=session.get('user_id')).first()
        else:
            # the user is not already logged in, let's see if they have
            # already created an account before
            user = Session.query(User).filter_by(flickr_nsid=nsid).first()

        if user:
            user.flickr_nsid = nsid
            user.flickr_token = token
            Session.commit()
        else:
            # the user does not have an account.  We need to create a new one
            # for them.
            user = User(flickr_nsid=nsid, flickr_token=token)
            Session.add(user)
            Session.commit()
            user = Session.query(User).filter_by(flickr_nsid=nsid).first()

        session['user_id'] = user.id
        session['flickr_token'] = token
        session.save()
        log.info("Logged in user %s", user)
        redirect(url('index'))
Ejemplo n.º 50
0
    def index(self):
        gd_client = gdata.photos.service.PhotosService()
        #token = request.GET.getone('token')
        parameters = cgi.FieldStorage()
        token = parameters['token']
        gd_client.auth_token = token
        gd_client.UpgradeToSessionToken()

        session['picasa_token'] = token
        session.save()

        if session.get('user_id'):
            # a user is already logged in
            user = Session.query(User).filter_by(
                id=session.get('user_id')).first()
        else:
            # the user is not already logged in, let's see if they have
            # already created an account before
            user = Session.query(User).filter_by(picasa_token=token).first()

        if user:
            user.picasa_token = token
            Session.commit()
        else:
            # the user does not have an account.  We need to create a new one
            # for them.
            user = User(picasa_token=token)
            Session.add(user)
            Session.commit()
            user = Session.query(User).filter_by(
                picasa_token=picasa_token).first()

        session['user_id'] = user.id
        session['picasa_token'] = token
        session.save()
        log.info("Logged in user %s", user)
        redirect(url('index'))
Ejemplo n.º 51
0
    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))
Ejemplo n.º 52
0
 def __call__(self,
              message,
              category=None,
              ignore_duplicate=False,
              allow_html=False):
     if not category:
         category = self.default_category
     elif self.categories and category not in self.categories:
         raise ValueError("unrecognized category %r" % (category, ))
     # Don't store Message objects in the session, to avoid unpickling
     # errors in edge cases.
     new_message_tuple = (category, message, allow_html)
     messages = session.setdefault(self.session_key, [])
     # ``messages`` is a mutable list, so changes to the local variable are
     # reflected in the session.
     if ignore_duplicate:
         for i, m in enumerate(messages):
             if m[1] == message:
                 if m[0] != category:
                     messages[i] = new_message_tuple
                     session.save()
                 return  # Original message found, so exit early.
     messages.append(new_message_tuple)
     session.save()
Ejemplo n.º 53
0
    def disassociate(self, id, otherID):
        """Disassociate BLD Collection id from BLD File otherID.

        """

        if id is None or otherID is None:
            abort(404)
        collection = meta.Session.query(model.Collection).get(int(id))
        file = meta.Session.query(model.File).get(int(otherID))
        if file is None:
            if collection is None:
                abort(404)
            else:
                session['flash'] = 'There is no File with ID %s' % otherID
        if file in collection.files:
            collection.files.remove(file)
            meta.Session.commit()
            session['flash'] = 'File %s disassociated' % otherID
        else:
            session[
                'flash'] = 'Collection %s was never associated to File %s' % (
                    id, otherID)
        session.save()
        redirect(url(controller='collection', action='view', id=id))
Ejemplo n.º 54
0
 def signout(self):
     domain = request.params.get('domain')
     username = request.params.get('username')
     userid = request.params.get('userid')
     if domain and username or userid:
         try:
             keys = [
                 k for k in session.get('account_keys', '').split(',') if k
             ]
             rem_keys = keys[:]
             for k in keys:
                 acct = session[k]
                 if acct['domain']==domain and \
                    (not username or acct['username']==username) and \
                    (not userid or acct['userid']==userid):
                     session.pop(k)
                     rem_keys.remove(k)
             session['account_keys'] = ','.join(rem_keys)
         except:
             log.exception('failed to signout from domain %s', domain)
             session.clear()
     else:
         session.clear()
     session.save()
Ejemplo n.º 55
0
    def show(self, workspace_id):
        #TODO: handle logged out users
        if 'tmp_notif_user_id' in session:
            user_id = session['tmp_notif_user_id']
        elif 'user_id' in session:
            user_id = session['user_id']
        else:
            abort(403)

        settings = UserWorkspaceSettings(user_id, workspace_id)

        c.notificationEnabled = settings.getNotificationsEnabled()
        c.summaryEnabled = settings.getSummaryEnabled()
        if (c.workspace.public):
            c.email_id = session['email_id']

        if 'HTTP_REFERER' in request.environ:
            session['notif_page_referer'] = request.environ['HTTP_REFERER']
            session.save()

        if 'notif_page_referer' in session:
            c.cancel_url = session['notif_page_referer']

        return render('/teambox/settings.mako')
Ejemplo n.º 56
0
    def __before__(self):
        if self.lightweight:
            return

        routes = request.environ.get('pylons.routes_dict', dict())

        c.bodyclass = None
        c.cmsuser = None
        c.current_action = routes.get('action')

        if 'token' not in session:
            session['token'] = security.generate_token()
            session.save()

        if not session.get('cmsuser'):
            session['cmsuser'] = None
        else:
            c.cmsuser = model.find_cmsuser(session['cmsuser'])

        try:
            act = getattr(self, c.current_action)
        except:
            abort(404)

        if not security.allowed_action(act, request.method, c.cmsuser):
            print "1", act.__dict__
            abort(403)
        if not security.check_token(request, session):
            print "2"
            abort(403)

        c.tree = Tree(Session)
        c.tree.load()
        c.menubase = c.tree.find_node(iname='pages')
        c.cmsmenuOptions = dict()
        c.cmsmenuOptions['page'] = c.tree.get_menu_options()
Ejemplo n.º 57
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))
Ejemplo n.º 58
0
    def __before__(self):

        update_session = True
        lang = None
        self.charset = 'utf-8'

        self.root_path = config['root_path']
        self.root_url = config['root_url']
        self.mobile_search_url = config['mobile_search_url']
        self.versionTime = config['versionTime']
        self.yahoo_key = config['yahoo_key']
        self.bing_key = config['bing_key']

        if 'lang' in request.params and self._isLangAvailable(
                request.params['lang']):
            lang = request.params['lang']
        elif 'lang' in session:
            lang = session['lang']
            update_session = False
        else:
            # get from user agent
            for language in request.languages:
                language = language[0:2]
                if self._isLangAvailable(language):
                    lang = unicode(language)
                    break
        if lang is None:
            lang = unicode(config['lang'])

        if 'charset' in request.params:
            self.charset = request.params['charset']

        set_lang(lang)
        if update_session:
            session['lang'] = lang
            session.save()
Ejemplo n.º 59
0
    def testdestination(self, destinationid):
        "Test mail destination server"
        server = self._get_server(destinationid)
        if not server:
            abort(404)

        taskid = request.GET.get('taskid', None)
        if not taskid:
            to_addr = 'postmaster@%s' % server.domains.name
            task = test_smtp_server.apply_async(args=[
                server.address, server.port, '<>', to_addr, server.id, 3
            ])
            taskid = task.task_id
            session['taskids'].append(taskid)
            session['testdest-count'] = 1
            session.save()
            redirect(url.current(taskid=taskid))
        else:
            result = AsyncResult(taskid)
            if result is None or taskid not in session['taskids']:
                flash(_('The connection test failed try again later'))
                redirect(url('domain-detail', domainid=server.domain_id))
            if result.ready():
                if ('smtp' in result.result and 'ping' in result.result
                        and result.result['smtp'] and result.result['ping']):
                    flash(
                        _('The server: %s is up and accepting mail from us' %
                          server.address))
                else:
                    if 'ping' in result.result['errors']:
                        errors = result.result['errors']['ping']
                    else:
                        errors = result.result['errors']['smtp']
                    flash(
                        _('The server: %s is not accepting mail from us: %s') %
                        (server.address, errors))
                redirect(url('domain-detail', domainid=server.domain_id))
            else:
                session['testdest-count'] += 1
                session.save()
                if (session['testdest-count'] >= 10
                        and result.state in ['PENDING', 'RETRY', 'FAILURE']):
                    result.revoke()
                    del session['testdest-count']
                    session.save()
                    flash_alert('Failed to initialize backend,'
                                ' try again later')
                    redirect(url('domain-detail', domainid=server.domain_id))

        c.server = server
        c.domainid = server.domain_id
        c.taskid = taskid
        c.finished = False
        return render('/domains/testdestination.html')
Ejemplo n.º 60
0
    def sendbatchedit(self):
        response.content_type = 'application/json'
        user_id = int(request.params['user_id'])
        field = request.params['field']
        info = [json.loads(d[1]) for d in request.params.items()\
                    if 'items[]' in d]

        if field == 'hostname':
            for item in info:
                data = {}
                data['hostname'] = item['hostname']
                activity_engine = ActivityEngine(Session, user_id)
                status = activity_engine.update('node', item['node_id'], data)
            session['flash'] = "Success"
            session.save()

        elif field == 'groups':
            for item in info:
                node = Session.query(Node)\
                    .filter(Node.id == item['node_id']).first()
                group_list = item['groups']\
                    .replace(' ', '').split(',')
                node.groups = Session.query(Group)\
                    .filter(Group.name.in_(group_list)).all()
                Session.add(node)
                Session.commit()
            session['flash'] = "Success"
            session.save()

        elif field == 'db_backups':
            for item in info:
                backup = Session.query(NodeDatabaseBackup)\
                    .filter(NodeDatabaseBackup.id == item['backup_id'])\
                    .first()
                node = Session.query(Node)\
                    .filter(Node.id == item['node_id']).first()
                backup.server_id = node.id

                if item['data_type'] == 'storage':
                    storage = Session.query(Node)\
                        .filter(Node.hostname == item['value']).first()
                    backup.storage_id = storage.id

                elif item['data_type'] == 'directory':
                    backup.directory = item['value']

            Session.add(backup)
            Session.commit()
            session['flash'] = "Success"
            session.save()
        else:
            return '{"success": false}'
        return '{"success": true}'