def login(self, residence_dn, username, password): if self.get_anon_bind() is None: return False user_base_dn = ldap_config.username_base_dn + residence_dn actual_user = self.get_anon_bind().search_first( user_base_dn, "(uid=" + username + ")") if actual_user is None: return False username_dn = actual_user.dn bind = Ldap.connect(username_dn, password) if bind is None: return False attributes = bind.search_first(username_dn, "(uid=" + username + ")") user = User(bind, attributes, residence_dn) AuthHandler.__users[username] = user session[AuthHandler.__user_session_name] = username session.save() return True
def diff(self, commit, fmt=None, **kw): try: path, filename = os.path.split(self._blob.path()) a_ci = c.app.repo.commit(commit) a = a_ci.get_path(self._blob.path()) apath = a.path() except: a = [] apath = '' b = self._blob if not self._blob.has_html_view: diff = "Cannot display: file marked as a binary type." return dict(a=a, b=b, diff=diff) la = list(a) lb = list(b) adesc = (u'a' + h.really_unicode(apath)).encode('utf-8') bdesc = (u'b' + h.really_unicode(b.path())).encode('utf-8') if not fmt: fmt = web_session.get('diformat', '') else: web_session['diformat'] = fmt web_session.save() if fmt == 'sidebyside': hd = HtmlSideBySideDiff() diff = hd.make_table(la, lb, adesc, bdesc) else: diff = ''.join(difflib.unified_diff(la, lb, adesc, bdesc)) return dict(a=a, b=b, diff=diff)
def check_tequila(self): if not 'repoze.who.identity' in request.environ: session['check_tequila'] = True session.save() raise redirect(url('/login')) else: raise redirect('/search')
def sites(self, *kw): session['date'] = kw[0] session.save() c.reports = sites_report_grid c.query_params = { 'Date' : session['date'] } c.backlink = '/reports/reports' return dict(page = 'squid')
def outcall_fetch(self, page, rows, sidx, sord, cust_id, **kw): ''' Function called on AJAX request made by FlexGrid Fetch data from DB, return the list of rows + total + current page ''' # Try and use grid preference grid_rows = session.get('grid_rows', None) if rows=='-1': # Default value rows = grid_rows if grid_rows is not None else 25 # Save grid preference session['grid_rows'] = rows session.save() rows = int(rows) try: page = int(page) rows = int(rows) offset = (page-1) * int(rp) except: offset = 0 page = 1 rows = 25 data = DBSession.query(Outcall, CDR) \ .outerjoin(CDR, Outcall.uniqueid==CDR.uniqueid) \ .filter(Outcall.cust_id==cust_id) total = 1 + data.count() / rows column = getattr(Outcall, sidx) data = data.order_by(getattr(column,sord)()).offset(offset).limit(rows) rows = [ { 'id' : a.Outcall.out_id, 'cell': outcall_row(a) } for a in data ] return dict(page=page, total=total, rows=rows)
def diff(self, commit, fmt=None): try: path, filename = os.path.split(self._blob.path()) a_ci = c.app.repo.commit(commit) a = a_ci.get_path(self._blob.path()) apath = a.path() except: a = [] apath = '' b = self._blob if not self._blob.has_html_view: diff = "Cannot display: file marked as a binary type." return dict(a=a, b=b, diff=diff) la = list(a) lb = list(b) adesc = (u'a' + h.really_unicode(apath)).encode('utf-8') bdesc = (u'b' + h.really_unicode(b.path())).encode('utf-8') if not fmt: fmt = web_session.get('diformat', '') else: web_session['diformat'] = fmt web_session.save() if fmt == 'sidebyside': hd = HtmlSideBySideDiff() diff = hd.make_table(la, lb, adesc, bdesc) else: diff = ''.join(difflib.unified_diff(la, lb, adesc, bdesc)) return dict(a=a, b=b, diff=diff)
def put(self, _id, title, content, category, precondition, **kw): content = content or [] # Check content precondition element error = self._validate_precondition_with_qa(precondition, content) if error: return error check = self.get_related_entities(_id) if check.get("entities"): entity = dict(_id=_id, title=title, content=content, _category=category, _precondition=precondition, entity='output', html=kw['ks_editor']) session[ 'entity'] = entity # overwrite always same key for avoiding conflicts session.save() return dict(redirect_url=tg.url('/resolve', params=dict(workspace=category))) output = model.Output.query.find({'_id': ObjectId(_id)}).first() output.title = title output._category = ObjectId(category) output._precondition = ObjectId(precondition) output.content = content output.html = kw['ks_editor'] return dict(errors=None, redirect_url=None)
def extern_create(self, *args, **kw): ''' used to upload a file from another web application kw must contain : :file_path == file path :description == verbose to explain some stuff :project_name == name of the external web app :sample_name == name of the plugin web app / or another thing :sample_type == name of the webapp (and type of analysis if asked) kw can contain : :project_description == HTSstation project description :task_id == task_id for BioScript files from HTSstation/BioScript ''' #test if the essential kw are here essential_kws = ["file_path", "description", "project_name", "sample_name", "sample_type"] missing_kw = [] for k in essential_kws: if k not in kw.keys(): missing_kw.append(k) if len(missing_kw) > 0: flash(str(missing_kw) + " not found in keywords. External application error.", "error") raise redirect(url("/")) session['backup_kw'] = kw session.save() #test if the user who was redirected on BioRepo is logged in it if not 'repoze.who.identity' in request.environ: session['extern_meas'] = True session.save() raise redirect(url('/login')) else: raise redirect(url('/measurements/external_add'))
def _basic_security_checks(): """Perform basic security/sanity checks before processing the request.""" # Only allow the following HTTP request methods. if request.method not in ['GET', 'HEAD', 'POST']: raise webob.exc.HTTPMethodNotAllowed() # Also verify the _method override - no longer allowed. if request.params.get('_method') is None: pass # no override, no problem else: raise webob.exc.HTTPMethodNotAllowed() # Make sure CSRF token never appears in the URL. If so, invalidate it. if secure_form.token_key in request.GET: log.error('CSRF key leak detected') session.pop(secure_form.token_key, None) session.save() from kallithea.lib import helpers as h h.flash(_('CSRF token leak has been detected - all form tokens have been expired'), category='error') # WebOb already ignores request payload parameters for anything other # than POST/PUT, but double-check since other Kallithea code relies on # this assumption. if request.method not in ['POST', 'PUT'] and request.POST: log.error('%r request with payload parameters; WebOb should have stopped this', request.method) raise webob.exc.HTTPBadRequest()
def put(self, *args, **kw): '''update''' print "Put Proyecto" pm=ProyectoManager() p = pm.getById(args) params = kw p.nombre= params['nombre'] p.descripcion = params ['descripcion'] f1 = time.strptime(params['fecha_inicio'],"%Y-%m-%d") f2 = time.strptime(params['fecha_finalizacion'],"%Y-%m-%d") if f2 < f1: flash(('La fecha de finalizacion debe ser mayor o igual a la de inicio'), 'warning') raise redirect('/proyecto/'+session['id_proyecto']+'/edit') p.fecha_inicio = params['fecha_inicio'] p.fecha_finalizacion = params['fecha_finalizacion'] if params['costo_estimado']!=None: try: p.costo_estimado = params['costo_estimado'] except: flash(('El costo estimado debe ser un numero'), 'Error') raise redirect("/proyecto/"+session['id_proyecto']+'/edit') #p.estado = 'iniciado' pm.update(p) session['id_proyecto'] = args[0] session.save() raise redirect('/fase/')
def report2(self, **kw): reload(sys) sys.setdefaultencoding("utf-8") set_lang("th") session['lang'] = "th" session.save() year = self.util.isValue(kw.get('year')) disabledSelect = False sectionTeamId = 0 log.info(year) if year is None: year = 2558 listYear = self.util.getRangeYear(year) listHash = app_model.IndicatorsService.listReport2Indicator(year) #log_view_report self.saveLogView() return dict(page='indicator', year=year, listYear=listYear, listHash=listHash)
def pwd_expired_change(self, **kw): require_authenticated() return_to = kw.get("return_to") kw = F.password_change_form.to_python(kw, None) ap = plugin.AuthenticationProvider.get(request) try: expired_username = session.get("expired-username") expired_user = M.User.query.get(username=expired_username) if expired_username else None ap.set_password(expired_user or c.user, kw["oldpw"], kw["pw"]) expired_user.set_tool_data("allura", pwd_reset_preserve_session=session.id) expired_user.set_tool_data("AuthPasswordReset", hash="", hash_expiry="") # Clear password reset token except wexc.HTTPUnauthorized: flash("Incorrect password", "error") redirect(tg.url("/auth/pwd_expired", dict(return_to=return_to))) flash("Password changed") session.pop("pwd-expired", None) session["username"] = session.get("expired-username") session.pop("expired-username", None) session.save() h.auditlog_user("Password reset (via expiration process)") if return_to and return_to != request.url: redirect(return_to) else: redirect("/")
def post_login(self,userid,came_from=url('/')): """ Redirect the user to the initially requested page on successful authentication or redirect her back to the login page if login failed. """ result='' if not userid: result = "{success:false,msg:'session expired'}" return result u=User.by_user_name(to_unicode(userid)) g=Group.by_group_name(to_unicode('adminGroup')) auth=AuthorizationService() auth.user=u session['username']=u.user_name session['user_firstname']=u.firstname session['has_adv_priv']=tg.config.get(constants.ADVANCED_PRIVILEGES) session['PAGEREFRESHINTERVAL']=tg.config.get(constants.PAGEREFRESHINTERVAL) session['TASKPANEREFRESH']=tg.config.get(constants.TASKPANEREFRESH) session['userid']=userid session['auth']=auth session['edition_string']=get_edition_string() session['version']=get_version() self.update_registerd_session() is_admin = u.has_group(g) session['is_admin']=is_admin session.save() TopCache().delete_usercache(auth) result = "{success:true}" return result
def post_login(self,userid,came_from=url('/')): """ Redirect the user to the initially requested page on successful authentication or redirect her back to the login page if login failed. """ result='' if not userid: result = "{success:false,msg:'session expired'}" return result u=User.by_user_name(to_unicode(userid)) g=Group.by_group_name(to_unicode('adminGroup')) auth=AuthorizationService() auth.user=u session['username']=u.user_name session['user_firstname']=u.firstname session['has_adv_priv']=tg.config.get(constants.ADVANCED_PRIVILEGES) session['PAGEREFRESHINTERVAL']=tg.config.get(constants.PAGEREFRESHINTERVAL) session['TASKPANEREFRESH']=tg.config.get(constants.TASKPANEREFRESH) session['userid']=userid session['auth']=auth session['edition_string']=get_edition_string() session['version']=get_version() is_admin = u.has_group(g) session['is_admin']=is_admin session.save() TopCache().delete_usercache(auth) result = "{success:true}" return result
def removeall( self, **kw ): try: del session['items'] session.save() except: pass return redirect( '/ordering/listItems' )
def put(self, _id, title, workspace, conditions, **kw): error, condition = self._marshall_complex_filter(conditions) if error: response.status_code = 412 return dict(errors=error) check = self.get_related_entities(_id) if check.get("entities"): entity = dict( _id=_id, title=title, condition=list(map(str, condition)), _workspace=workspace, auto_generated=False, entity='precondition/advanced', ) session['entity'] = entity # overwrite always same key for avoiding conflicts session.save() return dict(redirect_url=tg.url('/resolve', params=dict(workspace=workspace))) precondition = Precondition.query.get(_id=ObjectId(_id)) precondition.title = title precondition.condition = condition precondition.auto_generated = False precondition.status = Precondition.STATUS.UNREAD precondition._workspace = workspace return dict(errors=None, redirect_url=None)
def ajaxSavetoCart( self, **kw ): _k = kw.get( "_k", None ) if not _k : return {'flag' : 1 , 'msg' : 'No ID provided!'} try: items = session.get( 'items', [] ) for index, item in enumerate( items ): if item['_k'] != _k : continue p = qry( Product ).get( item['id'] ) item['values'], item['optionstext'] = self._formatKW( kw , p ) qs = [] for qk, qv in self._filterAndSorted( "option_qty", kw ): if not qv : continue q, _ = qv.split( "|" ) if not q.isdigit() : continue qs.append( int( q ) ) item['qty'] = sum( qs ) if qs else 0 items[index] = item session['items'] = items session.save() return {'flag' : 0 , 'optionstext' : item['optionstext'], } except: traceback.print_exc() return {'flag' : 1 , 'msg' : 'Error occur on the sever side!'} return {'flag' : 1 , 'msg' : 'No such item!'}
def ajaxAddtoCart( self, **kw ): _id = kw.get( 'id', None ) or None if not _id : return {'flag' : 1 , 'msg' : 'No ID provided!'} try: items = session.get( 'items', [] ) tmp = { '_k' : "%s%s" % ( dt.now().strftime( "%Y%m%d%H%M%S" ), random.randint( 100, 10000 ) ) , 'id' : _id, } qs = [] for qk, qv in self._filterAndSorted( "option_qty", kw ): if not qv : continue q, _ = qv.split( "|" ) if not q.isdigit() : continue qs.append( int( q ) ) tmp['qty'] = sum( qs ) if qs else 0 p = qry( Product ).get( _id ) tmp['values'], tmp['optionstext'] = self._formatKW( kw, p ) items.append( tmp ) session['items'] = items session.save() return {'flag' : 0 , 'total' : len( session['items'] )} except: traceback.print_exc() return {'flag' : 1, 'msg':'Error occur on the sever side!'}
def fetch(self, page, rows, sidx, sord, **kw): ''' Function called on AJAX request made by FlexGrid Fetch data from DB, return the list of rows + total + current page ''' # Try and use grid preference grid_rows = session.get('grid_rows', None) if rows=='-1': # Default value rows = grid_rows if grid_rows is not None else 25 # Save grid preference session['grid_rows'] = rows session.save() rows = int(rows) try: page = int(page) rows = int(rows) offset = (page-1) * int(rows) except: offset = 0 page = 1 rows = 25 apps = DBSession.query(Campaign).filter(Campaign.deleted==None) total = 1 + apps.count() / rows column = getattr(Campaign, sidx) apps = apps.order_by(getattr(column,sord)()).offset(offset).limit(rows) rows = [ { 'id' : a.cmp_id, 'cell': row(a) } for a in apps ] return dict(page=page, total=total, rows=rows)
def fetch(self, page, rows, sidx='lastname', sord='asc', _search='false', searchOper=None, searchField=None, searchString=None, **kw): ''' Function called on AJAX request made by Grid JS component Fetch data from DB, return the list of rows + total + current page ''' # Try and use grid preference grid_rows = session.get('grid_rows', None) if rows=='-1': # Default value rows = grid_rows if grid_rows is not None else 25 # Save grid preference session['grid_rows'] = rows session.save() rows = int(rows) try: page = int(page) rows = int(rows) offset = (page-1) * rows except: offset = 0 page = 1 rows = 25 pb = sorted(phonebook_list(request.identity['user'].user_id, searchOper, searchField, searchString), key = itemgetter(sidx), reverse = True if sord=='desc' else False) total = len(pb)/rows+1 data = [ { 'id' : b['pb_id'], 'cell': row(b) } for b in pb[offset:offset+rows] ] return dict(page=page, total=total, rows=data)
def post_login(self, came_from='/', **kw): """ Redirect the user to the initially requested page on successful authentication or redirect her back to the login page if login failed. """ log.debug('POST_LOGIN') if not request.identity: login_counter = int(request.environ.get('repoze.who.logins', 0)) + 1 redirect( url('/auth_service/login', params=dict(came_from=came_from, __logins=login_counter))) userid = request.identity['repoze.who.userid'] flash(_('Welcome back, %s!') % userid) self._begin_mex_session() timeout = int( config.get('bisque.login.timeout', '0').split('#')[0].strip()) length = int( config.get('bisque.login.session_length', '0').split('#')[0].strip()) if timeout: session['timeout'] = timeout if length: session['expires'] = (datetime.utcnow() + timedelta(seconds=length)) session['length'] = length session.save() log.debug("Current session %s", str(session)) transaction.commit() redirect(came_from)
def customer_fetch(self, page, rows, sidx, sord, cmp_id, **kw): ''' Function called on AJAX request made by FlexGrid Fetch data from DB, return the list of rows + total + current page ''' # Try and use grid preference grid_rows = session.get('grid_rows', None) if rows=='-1': # Default value rows = grid_rows if grid_rows is not None else 25 # Save grid preference session['grid_rows'] = rows session.save() rows = int(rows) try: page = int(page) rows = int(rows) offset = (page-1) * int(rows) except: offset = 0 page = 1 rows = 25 data = DBSession.query(Customer). \ filter(Customer.cmp_id==cmp_id). \ filter(Customer.active==True) total = 1 + data.count() / rows column = getattr(Customer, sidx if sidx!='name' else 'lastname') data = data.order_by(getattr(column,sord)()).offset(offset).limit(rows) rows = [ { 'id' : a.cust_id, 'cell': customer_row(a) } for a in data ] return dict(page=page, total=total, rows=rows)
def nuevo(self, *args, **kw): """Despliega una pagina donde se completan los campos para crear una nueva linea base""" if not 'fase' in kw: flash(('Direccion no valida'), 'error') raise redirect("/index") try: fase, navegacion = self.getNavegacionFromIdFase(kw['fase']) except: flash(('Direccion no valida'), 'error') raise redirect("/index") if not(Secure().FiltrarByFase(int(kw['fase']),'crear_lb')): flash(('USTED NO CUENTA CON PERMISOS SUFICIENTES'), 'error') raise redirect("/index") tmpl_context.widget = self.table_item self.table_filler_item.init(fase) values = self.table_filler_item.get_value(**kw) if not session['creacion_lb']: session['items_lb']=[]; session.save() if len(values)==0 and not(session['creacion_lb']): flash(('No existen items Aprobados'), 'warning') raise redirect ('/lineaBase', id_fase=fase.id_fase) if not session['creacion_lb']: session['creacion_lb']=True; session.save() return dict(value_list=values, model = "Linea Base" ,navegacion=navegacion, id_fase=kw['fase'])
def fetch(self, page, rows, sidx, sord, **kw): """ Function called on AJAX request made by FlexGrid Fetch data from DB, return the list of rows + total + current page """ # Try and use grid preference grid_rows = session.get("grid_rows", None) if rows == "-1": # Default value rows = grid_rows if grid_rows is not None else 25 # Save grid preference session["grid_rows"] = rows session.save() rows = int(rows) try: page = int(page) rows = int(rows) offset = (page - 1) * int(rp) except: offset = 0 page = 1 rows = 25 apps = DBSession.query(Application) total = apps.count() column = getattr(Application, sidx) apps = apps.order_by(getattr(column, sord)()).offset(offset).limit(rows) rows = [{"id": a.app_id, "cell": row(a)} for a in apps] return dict(page=page, total=total, rows=rows)
def oid_session(self): if 'openid_info' in session: return session['openid_info'] else: session['openid_info'] = result = {} session.save() return result
def index(self): reload(sys); sys.setdefaultencoding("utf-8"); print "Index maintenance"; """Handle the front-page.""" set_lang("th"); session['lang'] = "th"; session.save(); userid = ""; sectionid =""; level = "1"; #Admin; 0 user; if request.identity: userid = request.identity['repoze.who.userid']; section = UserRiskSection.getByUserName(userid); if(section): sectionid = section.risk_section_id; section = RiskSection.listBySectionbyId(sectionid); if(section): userid = section.description; level = "0"; print "section : " + str(sectionid); else: #redirect('/computer/add'); pass; log.info("computer"); #print "user : " + str(userid); return dict(page='computer',user=str(userid),sectionid=str(sectionid),level=level);
def check_phone(self, ip, pwd=None, mac=None): # Check phone is connected, get hardware address log.debug('%s %s &> /dev/null' % (command_fping, ip)) ret = system('%s %s &> /dev/null' % (command_fping, ip)) if ret: return dict(status=1, msg=u"Téléphone injoignable, vérifiez l'adresse") if not mac: ret = popen('%s %s' % (command_arp, ip)).readlines() log.debug('arp -> ' + str(ret)) if len(ret)!=2: return dict(status=2, msg=u"Téléphone injoignable, vérifiez l'adresse") mac = ret[1] match = re.search('(\w\w:\w\w:\w\w):(\w\w:\w\w:\w\w)', mac.lower()) if not match: return dict(status=3, msg=u"Téléphone injoignable, vérifiez l'adresse") vendor, device = match.groups() log.debug('vendor=%s, device=%s' % (vendor,device)) if vendor not in _vendors.keys(): return dict(status=4, msg=u"Type de téléphone inconnu") mac = '%s:%s' % (vendor,device) p = DBSession.query(Phone).filter(Phone.mac==mac).all() if len(p): return dict(status=5, msg = u'Téléphone existant, voulez-vous le \ <a href="/phones/%s/edit">modifier</a>.' % p[0].phone_id) if _vendors[vendor]=='Grandstream': new_phone = Grandstream(ip, mac) msg = u"Trouvé téléphone Grandstream : " if not new_phone.login(pwd): return dict(status=6, msg=msg+u'erreur login') infos = new_phone.infos() if not infos: return dict(status=6, msg=msg+u'erreur login') session['new_phone'] = new_phone session.save() return dict(status = 0, ip = ip, mac = mac, conf = 'grandstream_configure', msg = msg + infos['model'] + ', ' + infos['version']) elif _vendors[vendor]=='Cisco': new_phone = Cisco(ip, mac) msg = u"Trouvé téléphone Cisco : " if not new_phone.login(pwd): return dict(status=6, msg=msg+u'erreur login') infos = new_phone.infos() if not infos: return dict(status=6, msg=msg+u'erreur login') session['new_phone'] = new_phone session.save() return dict(status=0, ip=ip, mac=mac, conf='cisco_configure', msg = msg + infos['model'] + ', ' + infos['version']) elif _vendors[vendor]=='Polycom': return dict(status=0, ip=ip, mac=mac, conf='polycom_configure', msg=u"Trouvé téléphone Polycom")
def put(self, _id, title, category, conditions, **kw): error, condition = self._marshall_complex_filter(conditions) if error: response.status_code = 412 return dict(errors=error) check = self.get_related_entities(_id) if check.get("entities"): entity = dict( _id=_id, title=title, condition=list(map(str, condition)), _category=category, entity='precondition/advanced', ) session[ 'entity'] = entity # overwrite always same key for avoiding conflicts session.save() return dict(redirect_url=tg.url('/resolve')) precondition = model.Precondition.query.get(_id=ObjectId(_id)) precondition.title = title precondition.condition = condition precondition._category = category return dict(errors=None, redirect_url=None)
def report2(self,**kw): reload(sys); sys.setdefaultencoding("utf-8"); set_lang("th"); session['lang'] = "th"; session.save(); year = self.util.isValue(kw.get('year')); log.info(year); if year is None: year = self.defaultyear; listYear = self.util.getRangeYear(year); section=[]; if(year): startDate = str(int(year)-543 -1) + '-10-01'; stopDate = str(int(year)-543) + '-09-30'; log.info(startDate); section = RiskManagement.listSectionReport(startDate,stopDate); #log_view_report self.saveLogView(); return dict(page='risk',util=self.util,year=year,listYear = listYear,section = section);
def fetch(self, page, rows, sidx='user_name', sord='asc', _search='false', searchOper=None, searchField=None, searchString=None, **kw): ''' Function called on AJAX request made by FlexGrid Fetch data from DB, return the list of rows + total + current page ''' # Try and use grid preference grid_rows = session.get('grid_rows', None) if rows=='-1': # Default value rows = grid_rows if grid_rows is not None else 25 # Save grid preference session['grid_rows'] = rows session.save() rows = int(rows) try: page = int(page) rows = int(rows) offset = (page-1) * rows except: offset = 0 page = 1 rows = 25 sounds = DBSession.query(Sound) total = sounds.count()/rows + 1 column = getattr(Sound, sidx) sounds = sounds.order_by(getattr(column,sord)()).offset(offset).limit(rows) rows = [ { 'id' : s.sound_id, 'cell': row(s) } for s in sounds ] return dict(page=page, total=total, rows=rows)
def session_csrf_secret_token(): """Return (and create) the current session's CSRF protection token.""" from tg import session if not session_csrf_secret_name in session: session[session_csrf_secret_name] = str(random.getrandbits(128)) session.save() return session[session_csrf_secret_name]
def login(self, residence_dn, username, password): if self.get_anon_bind() is None: return False user_base_dn = ldap_config.username_base_dn + residence_dn actual_user = self.get_anon_bind().search_first(user_base_dn, "(uid=" + username + ")") if actual_user is None: return False username_dn = actual_user.dn bind = Ldap.connect(username_dn, password) if bind is None: return False attributes = bind.search_first(username_dn, "(uid=" + username + ")") user = User(bind, attributes, residence_dn) AuthHandler.__users[username] = user session[AuthHandler.__user_session_name] = username session.save() return True
def index(self): """Handle the front-page.""" set_lang("th"); session['lang'] = "th"; session.save(); return dict(page='index')
def toggle_theme(self): if session.get('theme', None) == 'dark': session['theme'] = 'light' else: session['theme'] = 'dark' session.save() return session.get('theme', None)
def pwd_expired_change(self, **kw): require_authenticated() return_to = kw.get('return_to') kw = F.password_change_form.to_python(kw, None) ap = plugin.AuthenticationProvider.get(request) try: expired_username = session.get('expired-username') expired_user = M.User.query.get( username=expired_username) if expired_username else None ap.set_password(expired_user or c.user, kw['oldpw'], kw['pw']) expired_user.set_tool_data('allura', pwd_reset_preserve_session=session.id) expired_user.set_tool_data( 'AuthPasswordReset', hash='', hash_expiry='') # Clear password reset token except wexc.HTTPUnauthorized: flash('Incorrect password', 'error') redirect(tg.url('/auth/pwd_expired', dict(return_to=return_to))) flash('Password changed') session.pop('pwd-expired', None) session['username'] = session.get('expired-username') session.pop('expired-username', None) session.save() h.auditlog_user('Password reset (via expiration process)') if return_to and return_to != request.url: redirect(return_to) else: redirect('/')
def fetch(self, page, rows, sidx='name', sord='desc', _search='false', searchOper=None, searchField=None, searchString=None, **kw): ''' Function called on AJAX request made by Grid JS component Fetch data from DB, return the list of rows + total + current page ''' # Try and use grid preference grid_rows = session.get('grid_rows', None) if rows=='-1': # Default value rows = grid_rows if grid_rows is not None else 25 # Save grid preference session['grid_rows'] = rows session.save() rows = int(rows) try: page = int(page) rows = int(rows) offset = (page-1) * rows except: offset = 0 page = 1 rows = 25 queue = DBSession.query(Queue) total = queue.count()/rows + 1 column = getattr(Queue, sidx) queue = queue.order_by(getattr(column,sord)()).offset(offset).limit(rows) data = [ { 'id' : q.queue_id, 'cell': row(q) } for q in queue ] return dict(page=page, total=total, rows=data)
def index(self): reload(sys) sys.setdefaultencoding("utf-8") print "Index maintenance" """Handle the front-page.""" set_lang("th") session['lang'] = "th" session.save() userid = "" sectionid = "" level = "1" #Admin; 0 user; if request.identity: userid = request.identity['repoze.who.userid'] section = app_model.UserRiskSection.getByUserName(userid) if (section): sectionid = section.risk_section_id section = app_model.RiskSection.listBySectionbyId(sectionid) if (section): userid = section.description level = "0" print "section : " + str(sectionid) else: #redirect('/computer/add'); pass log.info("computer") #print "user : " + str(userid); return dict(page='computer', user=str(userid), sectionid=str(sectionid), level=level)
def index2(self, custom1=None, member=None, queue=None, date=None, hour=None): ''' List records ''' log.debug('index2: custom1=%s (%s), member=%s (%s), queue=%s (%s), date=%s (%s), hour=%s (%s).' % ( custom1, type(custom1), member, type(member), queue, type(queue), date, type(date), hour, type(hour))) session['custom1'] = custom1 if custom1 is not None and custom1!='' else None session['member'] = member if member is not None and member!=-1 else None session['queue'] = queue if queue is not None and queue!=-1 else None session['date'] = date if date is not None else None session['hour'] = hour if hour is not None and hour!='' else None session.save() # User must be admin or queue supervisor sv = ['admin'] for q in Globals.asterisk.queues: sv.append('SV ' + q) if not in_any_group(*sv): tmpl_context.grid = None flash(u'Accès interdit !', 'error') else: tmpl_context.grid = grid tmpl_context.form = search_form # Use tabs ui_tabs_js.inject() return dict( title=u"Liste des enregistrements", debug='', values={'custom1': custom1, 'member': member, 'queue': queue, 'date': date, 'hour': hour})
def index(self, **kw): log.debug('index') if Globals.manager is None: flash(u'Vérifier la connexion Asterisk', 'error') else: Globals.manager.send_action({'Action': 'QueueStatus'}) for k in ('custom1', 'member', 'queue', 'date', 'hour'): if k in session.keys(): del(session[k]) session.save() # User must be admin or queue supervisor sv = ['admin'] for q in Globals.asterisk.queues: sv.append('SV ' + q) if not in_any_group(*sv): tmpl_context.grid = None flash(u'Accès interdit !', 'error') else: tmpl_context.grid = grid tmpl_context.form = search_form # Use tabs ui_tabs_js.inject() return dict(title=u"Liste des enregistrements", debug='', values={})
def asignar(self, *args, **kw): rm = RolManager() params = kw session['asignacion'] = False; session.save() try: parametros = str(kw['rol_proyecto']).split('?') id_rol = parametros[0] id_proyecto = parametros[1] r = rm.getById(int(id_rol)) except: try: r = rm.getById(int(params['id'])) id_proyecto=kw['id_proyecto'] except: flash (("Direccion no valida."), 'error') raise redirect('/index') if r.tipo == 0: if not(Secure().FiltrarBySistema('asignar_rol_sistema')): flash(('USTED NO CUENTA CON PERMISOS SUFICIENTES'), 'error') raise redirect("/index") u = UsuarioManager().getNoThisRol(r.id_rol) f=[] p=[] navegacion=self.getNavegacionSistema() if r.tipo == 1: if not(Secure().FiltrarByProyecto(kw['id_proyecto'],'asignar_rol_proyecto')): flash(('USTED NO CUENTA CON PERMISOS SUFICIENTES'), 'error') raise redirect("/index") u = UsuarioManager().getNotThisRolThisProject(r.id_rol, int(id_proyecto)) p = PermisoManager().getProyecto(int(id_proyecto)) f = PermisoManager().getFases(int(id_proyecto)) p1,navegacion = self.getNavegacionFromIdProyecto(int(id_proyecto)) return dict(id=r.id_rol,nombre = r.nombre, tipo = r.tipo, usuarios= u, proyectos=p, fases=f, permisos = r.permisos, navegacion=navegacion )
def pwd_expired_change(self, **kw): require_authenticated() return_to = kw.get('return_to') kw = F.password_change_form.to_python(kw, None) ap = plugin.AuthenticationProvider.get(request) try: expired_username = session.get('expired-username') expired_user = M.User.query.get(username=expired_username) if expired_username else None ap.set_password(expired_user or c.user, kw['oldpw'], kw['pw']) expired_user.set_tool_data('allura', pwd_reset_preserve_session=session.id) expired_user.set_tool_data('AuthPasswordReset', hash='', hash_expiry='') # Clear password reset token except wexc.HTTPUnauthorized: flash('Incorrect password', 'error') redirect(tg.url('/auth/pwd_expired', dict(return_to=return_to))) flash('Password changed') session.pop('pwd-expired', None) session['username'] = session.get('expired-username') session.pop('expired-username', None) session.save() h.auditlog_user('Password reset (via expiration process)') if return_to and return_to != request.url: redirect(return_to) else: redirect('/')
def edit(self, *args, **kw): th_name = str(args[0]) session["th_name"] = th_name session.save() user = handler.user.get_user_in_session(request) user_lab = session.get("current_lab", None) mail_path = str(user._email).lower().replace('@', 'AT') if user_lab is None: flash( "Problem detected with your lab in session. Contact your administrator please", 'error') raise redirect('/trackhubs') complementary_path = str( user_lab) + "/" + mail_path + "/" + th_name + "/" th_path = trackhubs_path() + "/" + complementary_path genome_path = th_path + "genomes.txt" if os.path.exists(genome_path): #get the final path with open(genome_path, 'r') as gen: l = gen.readline() while l != '': if l.startswith("trackDb"): trackdb_path = l.split('trackDb')[1].strip() l = gen.readline() final_path = th_path + trackdb_path + "trackDb.txt" with open(final_path, 'r') as final: l = final.readline() dic_colors = {} cpt = 0 while l != '': if l.startswith("\ttrack"): track = l.split("\ttrack")[1].strip() dic_colors[cpt] = track cpt += 1 elif l.startswith("\tcolor"): color = l.split("\tcolor")[1].strip() dic_colors[cpt] = color cpt += 1 l = final.readline() t_length = len(dic_colors.keys()) edit_form = build_form_edit_th(t_length)( action=url('/trackhubs/post_edit')).req() for k, v in dic_colors.items(): #even --> track if (k % 2 == 0): edit_form.child.children[k].value = v #odd --> color else: edit_form.child.children[k].value = v return dict(page='trackhubs', widget=edit_form, value=kw) else: flash( "Your trackhub is not accessible right now. Hardware problem on /data. Sorry for this inconvenient, retry in a fiew moment please.", 'error') raise redirect('/trackhubs')
def clear(self): session.pop('settings', None) session.pop('skip', None) session.pop('lang', None) session.save() logging.debug('clear all settings: session: %s', session) flash(_('All settings cleared')) redirect(self.menu.base)
def getSession(self): id = session.id if session.has_key('sessionInfo'): return session['sessionInfo'] sessionInfo = SessionInfo(id) session['sessionInfo'] = sessionInfo session.save() return sessionInfo
def getSession(self): id = session.id if session.has_key('sessionInfo'): return session['sessionInfo'] else: sessionInfo = SessionInfo(id) session['sessionInfo'] = sessionInfo session.save() return sessionInfo
def post_login(self, came_from=lurl('/')): if not request.identity: return 'False' user = DBSession.query(User).filter(User.user_name == request.remote_user).one_or_none() session['user_id'] = user.user_id session['user_name'] = user.user_name session['display_name'] = user.display_name session.save() return 'True'
def update_registerd_session(self): session['did'] = 0 session['registered'] = False from convirt.model import DBSession,Deployment dep=DBSession.query(Deployment).first() if dep: session['did'] = dep.deployment_id session['registered'] = dep.registered session.save()
def login(self, username, password, id): self.username = username self.password = password self.role = "superUser" self.group = "superGroup" self.isValid = 1 self.id = id session['sessionInfo'] = self session.save()
def clear(self): try: session.get('skip', set()).remove(self.name) except KeyError: pass session['settings'].pop(self.name, None) session.save() flash(_('Settings cleared')) redirect(self.url)
def pop_messages(self): """Return all accumulated messages and delete them from the session. The return value is a list of ``Message`` objects. """ from tg import session messages = session.pop(self.session_key, []) session.save() return [_Message(*m) for m in messages]
def logout(self): user = session[AuthHandler.__user_session_name] if user in AuthHandler.__users: stored_user = AuthHandler.__users[user] stored_user.ldap_bind.close() del AuthHandler.__users[user] #end if session[AuthHandler.__user_session_name] = None session.save()
def session_update(): timeout = session.get('timeout', 0) length = session.get('length', 0) if timeout and length: newexpire = datetime.utcnow() + timedelta(seconds=length) log.debug("SESSION EXPIRE %s", session['expires']) if newexpire >= session['expires'] + timedelta(seconds=timeout): session['expires'] = newexpire session.save()
def process_oid(failure_redirect=None): oidconsumer = consumer.Consumer(g.oid_session(), g.oid_store) info = oidconsumer.complete(request.params, request.url) display_identifier = info.getDisplayIdentifier() or info.identity_url if info.status == consumer.FAILURE and display_identifier: # In the case of failure, if info is non-None, it is the # URL that we were verifying. We include it in the error # message to help the user figure out what happened. fmt = "Verification of %s failed: %s" flash(fmt % (display_identifier, info.message), 'error') redirect(failure_redirect) elif info.status == consumer.SUCCESS: # Success means that the transaction completed without # error. If info is None, it means that the user cancelled # the verification. css_class = 'alert' # This is a successful verification attempt. If this # was a real application, we would do our login, # comment posting, etc. here. fmt = "You have successfully verified %s as your identity." message = fmt % display_identifier if info.endpoint.canonicalID: # You should authorize i-name users by their canonicalID, # rather than their more human-friendly identifiers. That # way their account with you is not compromised if their # i-name registration expires and is bought by someone else. message += (" This is an i-name, and its persistent ID is %s" % info.endpoint.canonicalID) flash(message, 'info') elif info.status == consumer.CANCEL: # cancelled message = 'Verification cancelled' flash(message, 'error') redirect(failure_redirect) elif info.status == consumer.SETUP_NEEDED: if info.setup_url: message = '<a href=%s>Setup needed</a>' % info.setup_url else: # This means auth didn't succeed, but you're welcome to try # non-immediate mode. message = 'Setup needed' flash(message, 'error') redirect(failure_redirect) else: # Either we don't understand the code or there is no # openid_url included with the error. Give a generic # failure message. The library should supply debug # information in a log. message = 'Verification failed.' flash(message, 'error') redirect(failure_redirect) session.save() oid_obj = M.OpenId.upsert(info.identity_url, display_identifier=display_identifier) return oid_obj
def index(self): try: if session['menu'] != []: pass except: session['menu'] = [] session.save() session['admin_tipo'] = "ninguno" session.save() return dict(page='index')
def index(self): print "Index maintenance" """Handle the front-page.""" set_lang("th") session['lang'] = "th" session.save() userid = "" #print "user : " + str(userid); return dict(page='datacenter')
def login_process_oid(self, **kw): oid_obj = process_oid(failure_redirect='.') c.user = oid_obj.claimed_by_user() session['userid'] = c.user._id session.save() if not c.user.username: flash('Please choose a user name for SourceForge, %s.' % c.user.get_pref('display_name')) redirect('setup_openid_user') redirect(kw.pop('return_to', '/'))
def index(self, *args, **kwargs): try: server = oauth2.Server() server.add_signature_method(oauth2.SignatureMethod_HMAC_SHA1()) req = oauth2.Request.from_request(request.method, request.url, request.headers, request.params, request.query_string) params = server.verify_request( req, oauth2.Consumer(self.key, self.secret), None) except: log.debug('LTI Tool Provider OAuth Error', exc_info=True) flash('LTI Tool Provider OAuth Error', 'error') abort(403) else: log.debug(params) user_name = ( params.get('tool_consumer_info_product_family_code', 'external') + '_' + params.get('tool_consumer_instance_guid', 'external') + '_' + params.get('user_id')) user = User.query.filter_by(user_name=user_name).first() if not user: log.info('New user %s', user_name) user = User( user_name=user_name, display_name=params.get('lis_person_name_full'), email_address=params.get('lis_person_contact_email_primary'), ) DBSession.add(user) submission = Submission.query.filter( Submission.assignment == self.assignment, Submission.user == user).first() if not submission: submission = Submission( assignment=self.assignment, filename=self.assignment.submission_filename or None, source=self.assignment.submission_template or None, language=self.assignment.allowed_languages[0], user=user, created=datetime.now(), modified=datetime.now(), ) DBSession.add(submission) DBSession.flush() session['lti'] = True session['params'] = params session['user'] = user.id session['submission'] = submission.id session.save() redirect('/lti/%d/edit' % self.assignment.id)