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 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 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 check_phone_verification(self, pin, **kw): p = plugin.ProjectRegistrationProvider.get() request_id = session.get('phone_verification.request_id') number_hash = session.get('phone_verification.number_hash') res = p.check_phone_verification(c.user, request_id, pin, number_hash) if 'error' in res: res['error'] = jinja2.Markup.escape(res['error']) res['error'] = h.really_unicode(res['error']) return res
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 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 index(self): result = None if session.get('username') is not None: user = DBSession.query(User).filter_by(user_name=session.get('username')).first() if user is not None and user.is_cloud(): if session['cloud_only'] == True: override_template(self.index, 'genshi:stackone.templates.clouddashboard') result = self.controller_impl.index() return dict(result)
def oauth_callback(self, **kw): client_id = config.get("github_importer.client_id") secret = config.get("github_importer.client_secret") if not client_id or not secret: return # GitHub app is not configured oauth = OAuth2Session(client_id, state=session.get("github.oauth.state")) token = oauth.fetch_token( "https://github.com/login/oauth/access_token", client_secret=secret, authorization_response=request.url ) c.user.set_tool_data("GitHubProjectImport", token=token["access_token"]) redirect(session.get("github.oauth.redirect", "/"))
def post_logout(self, came_from=url('/')): try: if session.get('username'): UIUpdateManager().del_user_updated_entities(session['username'], session['group_names']) UIUpdateManager().del_user_updated_tasks(session['username']) TopCache().delete_usercache(session.get('auth')) except Exception as e: print_traceback() LOGGER.error(to_str(e)) session.delete()
def index(self, *args, **kw): ''' Find first not set up service ''' for name, item in self.menu: if name in session.get('skip', set()): continue if name not in session.get('settings', {}): redirect(item.url) # Redirect to the first item in list # redirect(self.menu[0][1].url) # Redirect to the last item in list redirect(item.url)
def oauth_callback(self, **kw): client_id = config.get('github_importer.client_id') secret = config.get('github_importer.client_secret') if not client_id or not secret: return # GitHub app is not configured oauth = OAuth2Session(client_id, state=session.get('github.oauth.state')) token = oauth.fetch_token( 'https://github.com/login/oauth/access_token', client_secret=secret, authorization_response=request.url) c.user.set_tool_data('GitHubProjectImport', token=token['access_token']) self.oauth_callback_complete() redirect(session.get('github.oauth.redirect', '/'))
def oauth_callback(self, **kw): client_id = config.get('github_importer.client_id') secret = config.get('github_importer.client_secret') if not client_id or not secret: return # GitHub app is not configured oauth = OAuth2Session( client_id, state=session.get('github.oauth.state')) token = oauth.fetch_token( 'https://github.com/login/oauth/access_token', client_secret=secret, authorization_response=request.url ) c.user.set_tool_data('GitHubProjectImport', token=token['access_token']) redirect(session.get('github.oauth.redirect', '/'))
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 _clone_object(self): params = session.get('entity') entity = self._get_entity(params['entity'], params['_id']) params['title'] += ' [NUOVO]' new_obj = clone_obj(self.related_models[params['entity']], entity, params) return new_obj
def index(self, *args, **kw): user = handler.user.get_user_in_session(request) user_lab = session.get("current_lab", None) mail = user.email mail_tmp = mail.split("@") mail_final = mail_tmp[0] + "AT" + mail_tmp[1] user_TH_path = trackhubs_path() + "/" + user_lab + "/" + mail_final trackhubs = [] if os.path.exists(user_TH_path): list_trackhubs = os.listdir(user_TH_path) for t in list_trackhubs: th_path = user_TH_path + "/" + t #the only one directory into at this th level is named by the assembly used for it for i in os.listdir(th_path): path_to_test = th_path + "/" + i if os.path.isdir(path_to_test): assembly = i if not assembly: break else: #hub_url = th_path + "/hub.txt" hostname = socket.gethostname().lower() #because of aliasing if hostname == "ptbbsrv2.epfl.ch": hostname = "biorepo.epfl.ch" hub_url = "http://" + hostname + url("/trackHubs/") + user_lab + "/" + mail_final + "/" + t + "/hub.txt" th = Trackhub(t, 'http://genome.ucsc.edu/cgi-bin/hgTracks?hubUrl=' + hub_url + "&db=" + assembly) trackhubs.append(th) all_trackhubs = [util.to_datagrid(TrackhubGrid(), trackhubs, " UCSC's Trackhub(s)", len(trackhubs) > 0)] return dict(page='trackhubs', model=trackhubs, items=all_trackhubs, value=kw)
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 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 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 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 send_email_to_user(self, msg): self.msg = msg curr_user_id = session.get('userid') userRecord = DBSession.query(User.email_address).filter(User.user_name == curr_user_id).first() if userRecord: self.receivers = userRecord.email_address emailservers = self.get_mailservers() for eachmailserver in emailservers: if eachmailserver: self.mail_server = eachmailserver['MailSetup'].mail_server self.port = int(eachmailserver['MailSetup'].port) self.secure_type = int(eachmailserver['MailSetup'].use_secure) self.cred_details = eachmailserver['Creds'].cred_details self.password = self.cred_details['password'] self.sender = self.cred_details['user_email'] result = False if self.secure_type == NONSECURE: result = EmailManager().send_nonsecure(self.mail_server, self.port, self.sender, self.receivers, msg) else: if self.secure_type == TLS: result = EmailManager().send_tls(self.mail_server, self.port, self.sender, self.password, self.receivers, msg) else: result = EmailManager().send_ssl(self.mail_server, self.port, self.sender, self.password, self.receivers, msg) if result == True: return 'Test mail sent from ' + eachmailserver['MailSetup'].mail_server
def build_columns(): list_columns = [ {"title": "", "data": "scroll_info"}, {"title": "Description", "data": "Description", "defaultContent": ""}, {"title": "User", "data": "User", "defaultContent": ""}, {"title": "Projects", "data": "Projects", "defaultContent": ""}, {"title": "Samples", "data": "Samples", "defaultContent": ""}, {"title": "Type", "data": "Type", "defaultContent": ""}, {"title": "Measurements", "data": "Measurements", "defaultContent": ""}, #6 {"title": "DataType", "data": "DataType", "defaultContent": ""}, {"title": "Attachment", "data": "Attachment", "defaultContent": ""}, {"title": "Created", "data": "Created", "defaultContent": ""}, {"title": "Actions", "data": "Actions", "defaultContent": ""}] dyn_fields = sorted(session.get("search_grid_fields", [])) for d in dyn_fields: dic_column = {} d = d.replace("_", " ") d = d.capitalize() dic_column["title"] = d dic_column["data"] = d dic_column["defaultContent"] = "" #insert dynamic fields after "DataType" and before "Attachment" list_columns[6:6] = [dic_column] return list_columns
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 search_to_json(self, *args, **kw): #TODO : sort by column on user's click user_lab = session.get("current_lab", None) #get parameters from ajax request search_value = kw.get("search[value]", None) if search_value == '': search_value = None #word lenght > 2 to avoid DDoS in your server.... elif search_value is not None: list_search_words = [x for x in search_value.split(" ") if len(x) > 2] draw = int(kw.get("draw", 1)) start_point = int(kw.get("start", 0)) data_by_page = int(kw.get("length", 50)) stop_point = start_point + data_by_page if user_lab: lab = DBSession.query(Labs).filter(Labs.name == user_lab).first() measurements_total = DBSession.query(Measurements).join(Measurements.attributs).filter(and_(Attributs.lab_id == lab.id, Attributs.deprecated == False)).all() measurements = DBSession.query(Measurements).join(Measurements.attributs).filter(and_(Attributs.lab_id == lab.id, Attributs.deprecated == False)).distinct()[start_point:stop_point] if search_value is not None: final_request = self.search_engine(list_search_words, lab) #query mixed with results from all the table of interest paginated_request = final_request[start_point:stop_point] searching_tosort = [SW(meas).to_json_test() for meas in paginated_request] searching = sorted(searching_tosort, key=lambda k: (k['User'], k['Type'])) return json.dumps({"draw": draw, "recordsTotal": len(measurements_total), "recordsFiltered": len(final_request), "data": searching}) searching_tosort = [SW(meas).to_json_test() for meas in measurements] searching = sorted(searching_tosort, key=lambda k: (k['User'], k['Type'])) return json.dumps({"draw": draw, "recordsTotal": len(measurements_total), "recordsFiltered": len(measurements_total), "data": searching})
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 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 __call__(self, environ, context): try: request.ip_addr = _get_ip_addr(environ) # make sure that we update permissions each time we call controller self._basic_security_checks() #set globals for auth user bearer_token = None try: # Request.authorization may raise ValueError on invalid input type, params = request.authorization except (ValueError, TypeError): pass else: if type.lower() == 'bearer': bearer_token = params request.authuser = request.user = self._determine_auth_user( request.GET.get('api_key'), bearer_token, session.get('authuser'), ) log.info('IP: %s User: %s accessed %s', request.ip_addr, request.authuser, safe_unicode(_get_access_path(environ)), ) return super(BaseController, self).__call__(environ, context) except webob.exc.HTTPException as e: return e
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 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 send_email_to_user(self, msg): # Query sender and password from email credential table # Query mail_server,port,use_secure from the email setup table for curenly logged in user # receiver: to be queried from users table self.msg = msg curr_user_id = session.get("userid") # query users table to retrieve email address of currenlt logged in user userRecord = DBSession.query(User.email_address).filter(User.user_name == curr_user_id).first() if userRecord: self.receivers = userRecord.email_address emailservers = self.get_mailservers() for eachmailserver in emailservers: if eachmailserver: self.mail_server = eachmailserver["MailSetup"].mail_server self.port = int(eachmailserver["MailSetup"].port) self.secure_type = int(eachmailserver["MailSetup"].use_secure) self.cred_details = eachmailserver["Creds"].cred_details self.password = self.cred_details["password"] self.sender = self.cred_details["user_email"] result = False if self.secure_type == NONSECURE: result = EmailManager().send_nonsecure( self.mail_server, self.port, self.sender, self.receivers, msg ) elif self.secure_type == TLS: result = EmailManager().send_tls( self.mail_server, self.port, self.sender, self.password, self.receivers, msg ) else: result = EmailManager().send_ssl( self.mail_server, self.port, self.sender, self.password, self.receivers, msg ) if result == True: return "Test mail sent from " + eachmailserver["MailSetup"].mail_server
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 get_all_instance_categories(self): try: return self.csep_service.get_all_instance_categories_db(session.get('servicepoint_id')) except Exception as ex: print_traceback() LOGGER.error(to_str(ex)) raise ex
def index(self, *args): """ Display a list of all plugins in BioScript """ # get BioScript Server url (usually from config file) bs_server_url = tg.config.get('main.proxy') + '/' # build request to send to BioScript server bs_url = bs_server_url + 'plugins?ordered=true' # get the operation list back operation_list = urllib2.urlopen(bs_url).read() # fields can be pre-filled meth = 'get' if len(args) > 0 and args[0] == 'prefill': meth = 'get_prefill' # get previous launched jobs taht are in the session task_ids = session.get('task_ids', []) jobs = [] if task_ids: jobs = DBSession.query(Job).join(PluginRequest).filter( Job.task_id.in_(task_ids)).order_by( desc(PluginRequest.date_done)).all() # serve result on visual_index.mak template file return { 'oplist': operation_list, 'serv': bs_server_url, 'method': meth, 'jobs': jobs }
def send_email_to_user(self, msg): # Query sender and password from email credential table # Query mail_server,port,use_secure from the email setup table for curenly logged in user # receiver: to be queried from users table self.msg = msg curr_user_id = session.get('userid') #query users table to retrieve email address of currenlt logged in user userRecord = DBSession.query(User.email_address).filter(User.user_name == curr_user_id).first() if userRecord: self.receivers = userRecord.email_address emailservers = self.get_mailservers() for eachmailserver in emailservers: if eachmailserver: self.mail_server = eachmailserver['MailSetup'].mail_server self.port = int(eachmailserver['MailSetup'].port) self.secure_type = int(eachmailserver['MailSetup'].use_secure) self.cred_details = eachmailserver['Creds'].cred_details self.password = self.cred_details['password'] self.sender = self.cred_details['user_email'] result = False if (self.secure_type== NONSECURE): result = EmailManager().send_nonsecure(self.mail_server,self.port,self.sender,self.receivers,msg) elif (self.secure_type== TLS): result = EmailManager().send_tls(self.mail_server,self.port,self.sender,self.password,self.receivers,msg) else: result = EmailManager().send_ssl(self.mail_server,self.port,self.sender,self.password,self.receivers,msg) if (result == True): return "Test mail sent from " + eachmailserver['MailSetup'].mail_server
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 login(self, came_from=url('/')): """Start the user login.""" if session.get('userid') is None and request.identity is not None: self.redirect_to(url('/user_logout')) # login_counter = request.environ['repoze.who.logins'] # if login_counter > 0: # flash(_('Wrong credentials'), 'warning') return dict(page='login',came_from=came_from)
def manually_resolve(self, workspace, **kw): entity = session.get('entity') return dict( entity=entity['entity'], values=entity, workspace=workspace )
def create_volume(self, name, size, zone, snapshot, vdc_name): try: csep_id = session.get('servicepoint_id') return self.csep_service.create_volume(name, size, zone, snapshot, csep_id, vdc_name) except Exception as ex: print_traceback() LOGGER.error(to_str(ex)) raise ex
def searchlists_to_json(self, *args, **kw): user_lab = session.get("current_lab", None) if user_lab: lab = DBSession.query(Labs).filter(Labs.name == user_lab).first() one_meas = DBSession.query(Measurements).join(Measurements.attributs).filter(and_(Attributs.lab_id == lab.id, Attributs.deprecated == False)).first() search_grid, hidden_positions, positions_not_searchable = build_search_grid(one_meas) searchlists = json.dumps([hidden_positions, positions_not_searchable]) return searchlists
def mensajes(self, id): """ imprime un mensaje flash""" mensaje = session.get(id, "") if (mensaje == ""): flash(u"Relacionado exitósamente") else: flash(mensaje, "warning") redirect("../../")
def _end_mex_session(self): """Close a mex associated with the visit to record changes""" try: mexuri = session.get('mex_uri') if mexuri: module_service.end_internal_mex(mexuri) except AttributeError: pass return ""
def set_prefs(self, menu=None): log.debug('menu -> %s' % menu) if menu is not None: grid_rows = session.get('grid_rows', None) session['menu'] = menu session.save() return dict(status='ok')
def event(self, idevent, page): """ Affichage de l'historique d'un événement brut. Pour accéder à cette page, l'utilisateur doit être authentifié. @param idevent: identifiant de l'événement brut souhaité. @type idevent: C{int} @param page: numéro de la page à afficher. @type page: C{int} Cette méthode permet de satisfaire l'exigence VIGILO_EXIG_VIGILO_BAC_0080. """ # Auto-supervision self.get_failures() user = get_current_user() events = VigiboardRequest(user, False) events.add_table( Event, events.items.c.hostname.label('hostname'), events.items.c.servicename.label('servicename'), ) events.add_join((EVENTSAGGREGATE_TABLE, \ EVENTSAGGREGATE_TABLE.c.idevent == Event.idevent)) events.add_join((CorrEvent, CorrEvent.idcorrevent == \ EVENTSAGGREGATE_TABLE.c.idcorrevent)) events.add_join((events.items, Event.idsupitem == events.items.c.idsupitem)) events.add_filter(Event.idevent == idevent) if events.num_rows() != 1: flash(_('No such event or access denied'), 'error') redirect('/') events.format_events(0, 1) events.generate_tmpl_context() history = events.format_history() # Pagination des résultats items_per_page = int(session.get('items_per_page', config['vigiboard_items_per_page'])) page = paginate.Page(history, page=page, items_per_page=items_per_page) event = events.req[0] return dict( idevent = idevent, hostname = event.hostname, servicename = event.servicename, plugins_data = {}, page = page, search_form = create_search_form, search = {}, fixed_search = {}, )
def session(self): sess = etree.Element('session', uri=posixpath.join(self.uri, "session")) if identity.not_anonymous(): #vk = tgidentity.current.visit_link.visit_key #log.debug ("session_timout for visit %s" % str(vk)) #visit = Visit.lookup_visit (vk) #expire = (visit.expiry - datetime.now()).seconds #KGKif 'mex_auth' not in session: #KGKlog.warn ("INVALID Session or session deleted: forcing logout on client") #KGK return etree.tostring (sess) #KGK #redirect ('/auth_service/logout_handler') timeout = int(session.get('timeout', 0)) length = int(session.get('length', 0)) expires = session.get('expires', datetime(2100, 1, 1)) current_user = identity.get_user() if current_user: # Pylint misses type of current_user # pylint: disable=no-member etree.SubElement(sess, 'tag', name='user', value=data_service.uri() + current_user.uri) etree.SubElement(sess, 'tag', name='group', value=",".join([ g.group_name for g in current_user.get_groups() ])) # https://stackoverflow.com/questions/19654578/python-utc-datetime-objects-iso-format-doesnt-include-z-zulu-or-zero-offset etree.SubElement(sess, 'tag', name='expires', value=expires.isoformat() + 'Z') etree.SubElement(sess, 'tag', name='timeout', value=str(timeout)) etree.SubElement(sess, 'tag', name='length', value=str(length)) return etree.tostring(sess)
def update(self, *args, **kw): # Make sure passwords won't leak from session session.setdefault('settings', password_dict({})) # This is the first time this service is set up first_time = self.name not in session['settings'] session['settings'].setdefault(self.name, {}) if 'password' in kw.get(self.name, {}): if not kw[self.name]['password']: logging.debug('Not updating %r password. No value given.', self.name) old_password = session['settings'][self.name].get('password') kw[self.name]['password'] = old_password # Check if actually changed settings old_settings = copy.deepcopy(session['settings'][self.name]) new_settings = copy.deepcopy(kw.get(self.name)) # Don't include 'enable' in comparison old_settings.pop('enable', None) new_settings.pop('enable', None) settings_changed = old_settings != new_settings session['settings'].update(kw) logging.debug('update: session: %r', session) try: session.get('skip', set()).remove(self.name) except KeyError: pass session.save() if settings_changed: flash(_('Changes saved')) if first_time: # Pick the next uncofigured service redirect(self.menu.base) else: redirect(self.url)
def updateIndicator(self, **kw): #print kw; df = loads(request.body, encoding=request.charset) data = df['root'] years_id = session.get('years_id') months_id = session.get('months_id') for value in data: print value['indicator_value'] #years_id = value['years_id']; #months_id = value['months_id']; indicators_service = str( self.util.valueNull(value['indicators_service_id'])) indicators_detail_id = value['indicators_detail_id'] risk_section_id = value['risk_section_id'] indicator_value = value['indicator_value'] years_id = value['years_id'] if (len(indicators_service) == 0): indicatorsService = app_model.IndicatorsService() indicatorsService.indicators_detail_id = indicators_detail_id indicatorsService.years_id = years_id indicatorsService.months_id = months_id indicatorsService.risk_section_id = risk_section_id indicatorsService.indicator_value = indicator_value log.info("save service indicators:") indicatorsService.save() else: indicatorsService = app_model.IndicatorsService.getById( indicators_service) indicatorsService.indicator_value = indicator_value log.info("update service indicators:") #print request.POST['root'].getall(); #print request.GET.get['indicator_value']; return dict(success=True, message="update success")
def post_logout(self, came_from=url('/')): """Redirect the user to the initially requested page on logout and say goodbye as well.""" #flash(_('We hope to see you soon!')) # sessionInfo = getSession() # sessionInfo.logout() try: if session.get('username'): UIUpdateManager().del_user_updated_entities(session['username']) UIUpdateManager().del_user_updated_tasks(session['username']) except Exception, e: print_traceback() LOGGER.error(to_str(e))
def __call__(self, environ, context): try: ip_addr = _get_ip_addr(environ) self._basic_security_checks() api_key = request.GET.get('api_key') try: # Request.authorization may raise ValueError on invalid input type, params = request.authorization except (ValueError, TypeError): pass else: if type.lower() == 'bearer': api_key = params # bearer token is an api key too if api_key is None: authuser = self._determine_auth_user( session.get('authuser'), ip_addr=ip_addr, ) needs_csrf_check = request.method not in ['GET', 'HEAD'] else: dbuser = User.get_by_api_key(api_key) if dbuser is None: log.info( 'No db user found for authentication with API key ****%s from %s', api_key[-4:], ip_addr) authuser = AuthUser.make(dbuser=dbuser, is_external_auth=True, ip_addr=ip_addr) needs_csrf_check = False # API key provides CSRF protection if authuser is None: log.info('No valid user found') raise webob.exc.HTTPForbidden() # set globals for auth user request.authuser = authuser request.ip_addr = ip_addr request.needs_csrf_check = needs_csrf_check log.info( 'IP: %s User: %s Request: %s', request.ip_addr, request.authuser, get_path_info(environ), ) return super(BaseController, self).__call__(environ, context) except webob.exc.HTTPException as e: return e
def diff(self, prev_commit, fmt=None, prev_file=None, **kw): ''' :param prev_commit: previous commit to compare against :param fmt: "sidebyside", or anything else for "unified" :param prev_file: previous filename, if different :return: ''' try: path, filename = os.path.split(self._blob.path()) a_ci = c.app.repo.commit(prev_commit) a = a_ci.get_path(prev_file or self._blob.path()) apath = a.path() except Exception: # prev commit doesn't have the file a = M.repository.EmptyBlob() 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) # could consider making Blob.__iter__ do unicode conversion? # py2 unified_diff can handle some unicode but not consistently, so best to do ensure_str (can drop it on py3) la = [six.ensure_str(h.really_unicode(line)) for line in a] lb = [six.ensure_str(h.really_unicode(line)) for line in b] adesc = 'a' + h.really_unicode(apath) bdesc = 'b' + h.really_unicode(b.path()) if not fmt: fmt = web_session.get('diformat', '') else: web_session['diformat'] = fmt web_session.save() if fmt == 'sidebyside': if max(a.size, b.size) > asint( tg.config.get('scm.view.max_syntax_highlight_bytes', 500000)): # have to check the original file size, not diff size, because difflib._mdiff inside HtmlSideBySideDiff # can take an extremely long time on large files (and its even a generator) diff = '<em>File too large for side-by-side view</em>' else: hd = HtmlSideBySideDiff() diff = hd.make_table(la, lb, adesc, bdesc) else: # py2 unified_diff can handle some unicode but not consistently, so best to do str() and ensure_str() # (can drop it on py3) diff = str('').join( difflib.unified_diff(la, lb, six.ensure_str(adesc), six.ensure_str(bdesc))) return dict(a=a, b=b, diff=diff)
def relacionar_ph(self, *args, **kw): #recibe los elementos seleccionados en relacionar_item #relaciona, y retorna. Ajax id_item = UrlParser.parse_id(request.url, "items") item = Item.por_id(id_item) p_item = PropiedadItem.por_id(item.id_propiedad_item) ids = [] id = None if kw: for k, pk in kw.items(): if not k.isalnum(): continue ids.append(int(pk)) else: try: id = int(args[0]) if (id > 0): ids.append(id) except: id = 0 flash(u"Argumento inválido", "warning") retorno, creado = p_item.agregar_relaciones(ids, 'p-h') if (creado ): #si por lo menos se pudo crear una relacion se guarda en el #historial usuario = Usuario.by_user_name( request.identity['repoze.who.userid']) item.guardar_historial(u"relacionar-PH", usuario) mensaje = "" if (retorno == u"" and not creado): mensaje = u"No se crearon relaciones" elif (retorno != u""): mensaje = u"No se pudo crear la relación con %s" % retorno #no sé como pasar strings como parámetro, fea solución indice = session.get('indice_mensaje', 0) session['indice_mensaje'] = indice + 1 session[str(indice)] = mensaje if (id): redirect('../mensajes/%d' % indice) else: transaction.commit() #return "/items/%d/edit" % id_item return './mensajes/%d' % indice
def post_edit(self, *args, **kw): dic_colors = {} th_name = session["th_name"] user = handler.user.get_user_in_session(request) user_lab = session.get("current_lab", None) mail_path = str(user._email).lower().replace('@', 'AT') for key in kw.keys(): if key.startswith('Color_Track_'): key_id = key.replace('Color_Track_', '') dic_colors[int(key_id)] = kw[key] + "\n\n" #paths... 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() source_path = th_path + trackdb_path + "trackDb.txt" final_path_tmp = th_path + trackdb_path + "trackDb_tmp.txt" with open(source_path, 'r') as source: with open(final_path_tmp, 'a') as destination: l = source.readline() color_cpt = 0 while l != '': if l.startswith("\tcolor "): color_cpt += 1 destination.write("\tcolor " + dic_colors[color_cpt]) else: destination.write(l) l = source.readline() # remove old file os.remove(source_path) # rename new one os.rename(final_path_tmp, source_path) flash("Trackhub edited !") raise redirect("/trackhubs") 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 mark_resolved(self, list_to_new=None, list_to_old=None, **kw): entity = session.get('entity') if len(list_to_new) >= 1: if len(list_to_old) >= 1: # worst case, we have some objects that refer to new and other that refer ro old, need a clone self._clone_and_modify_(entity, list_to_new) else: # we can just edit old object because no one refer more to old object self._original_edit() else: # all objects refer to old, we can just edit old object self._original_edit() session.delete() flash(_(u'All the conflicts are successfully resolved')) return dict(errors=None)
def delete(self, *args, **kw): th_name = str(args[0]) user = handler.user.get_user_in_session(request) user_lab = session.get("current_lab", None) mail = user.email mail_tmp = mail.split("@") mail_final = mail_tmp[0] + "AT" + mail_tmp[1] user_path = trackhubs_path() + "/" + user_lab + "/" + mail_final th_path = user_path + "/" + th_name try: shutil.rmtree(th_path) flash("Your trackhub " + th_name + " was deleted.") except: flash( "Error : your trackhub was not deleted. Contact the administrator please.", 'error') raise redirect(url('/trackhubs'))
def add_storage_def_task(self, auth, site_id, group_id, node_id, type, opts, op_level, sp_ids): from tg import session task_service = self.svc_central.get_service(self.task_service_id) user_name = self._get_username(auth) #get scan result scan_result = session.get(constants.SCAN_RESULT) t= AddStorageDefTask(u'Add Storage Definition', {}, [], dict(site_id=site_id, group_id=group_id,\ node_id=node_id, type=type, opts=opts, op_level=op_level, sp_ids=sp_ids,\ scan_result=scan_result), None, user_name) t.set_entity_details(site_id) task_service.submit_sync(t) logger.debug("Add Storage Definition task submitted") #remove scan result from session session[constants.SCAN_RESULT] = None session.save() return t.task_id
def _original_edit(self): params = session.get('entity') params['_workspace'] = to_object_id(params.get('_workspace')) params['_precondition'] = to_object_id(params.get('_precondition')) entity = entity_from_id(params['_id']) if (type(entity) is model.Precondition): if entity.is_advanced: params['condition'] = [to_object_id(__) if __ not in model.Precondition.PRECONDITION_OPERATOR else __ for __ in params['condition'] ] else: params['condition'][0] = ObjectId(params['condition'][0]) old_hash = entity['hash'] params.pop('entity', None) for k, v in params.items(): setattr(entity, k, v) DBSession.flush(entity) entity.update_dependencies(old_hash) return entity
def do_login(self, return_to=None, **kw): location = '/' if session.get('expired-username'): if return_to and return_to not in plugin.AuthenticationProvider.pwd_expired_allowed_urls: location = tg.url( plugin.AuthenticationProvider.pwd_expired_allowed_urls[0], dict(return_to=return_to)) else: location = tg.url( plugin.AuthenticationProvider.pwd_expired_allowed_urls[0]) elif return_to and return_to != request.url: rt_host = urlparse(urljoin(config['base_url'], return_to)).netloc base_host = urlparse(config['base_url']).netloc if rt_host == base_host: location = return_to redirect(location)