def __init__(self): user_p = user_pack() self.username = user_p.get_username() self.role = authenticator.get_user_role(self.username, email=user_p.get_email()) self.before_request() self.count_call() self.notifications_db = database('notifications')
def notify(self, body): db = database('users') data = threaded_loads(body) list_of_mails = [x["value"] for x in db.raw_query('pwg-mail', {'key': data["pwg"]})] com = communicator() com.sendMail(list_of_mails, data["subject"], data["content"], user_pack().get_email()) return {'results': True, 'message': 'Sent message to {0}'.format(list_of_mails)}
def default(self, *vpath, **params): method = getattr(self, cherrypy.request.method, None) if not method: raise cherrypy.HTTPError(405, "Method not implemented.") if self.access_limit is not None: self.logger.log('Setting access limit to access_rights.%s (%s)' % (roles[self.access_limit], self.access_limit)) self.authenticator.set_limit(self.access_limit) elif cherrypy.request.method in self.limit_per_method: self.authenticator.set_limit(self.limit_per_method[cherrypy.request.method]) else: raise cherrypy.HTTPError(403, 'You cannot access this page with method %s' % cherrypy.request.method ) user_p = user_pack() l_type = locator() if not user_p.get_username(): #meaning we are going public, only allow GET. #if cherrypy.request.method != 'GET' or not l_type.isDev(): # raise cherrypy.HTTPError(403, 'User credentials were not provided.') if not 'public' in str(cherrypy.url()): self.logger.error('From within %s, adfs-login not found: \n %s \n %s' % (self.__class__.__name__, str(cherrypy.request.headers), str(cherrypy.url()) )) else: if not self.authenticator.can_access(user_p.get_username()): raise cherrypy.HTTPError(403, 'You cannot access this page, the limit for the page is {0} ({1})'.format(roles[self.authenticator.get_limit()], self.authenticator.get_limit())) # counter for calls with locker.lock("rest-call-counter"): self.counter[method.im_class.__name__][method.__name__] += 1 return method(*vpath, **params)
def format(self, record): try: if record.done: return record.msg except: record.done = False rtime = time.strftime("%d/%b/%Y:%H:%M:%S", time.localtime(record.created)) from tools.user_management import user_pack email = user_pack().get_email() if record.levelno > 20: if email: record.msg = '[%s][user:%s][%s] {%s} %s' % ( rtime, email, record.levelname, self.find_topmost_stack_frame(), record.msg) else: record.msg = '[%s][%s] {%s} %s' % ( rtime, record.levelname, self.find_topmost_stack_frame(), record.msg) else: if email: record.msg = '[%s][user:%s][%s] %s' % ( rtime, email, record.levelname, record.msg) else: record.msg = '[%s][%s] %s' % (rtime, record.levelname, record.msg) record.done = True return logging.Formatter.format(self, record)
def format(self, record): try: if record.done: return record.msg except: record.done = False rtime = time.strftime("%d/%b/%Y:%H:%M:%S", time.localtime(record.created)) from tools.user_management import user_pack email = user_pack().get_email() if record.levelno > 20: if email: record.msg = '[%s][user:%s][%s] {%s} %s' % ( rtime, email, record.levelname, self.find_topmost_stack_frame(), record.msg) else: record.msg = '[%s][%s] {%s} %s' % ( rtime, record.levelname, self.find_topmost_stack_frame(), record.msg) else: if email: record.msg = '[%s][user:%s][%s] %s' % ( rtime, email, record.levelname, record.msg) else: record.msg = '[%s][%s] %s' % ( rtime, record.levelname, record.msg) record.done = True return logging.Formatter.format(self, record)
def default(self, *vpath, **params): method = getattr(self, cherrypy.request.method, None) if not method: raise cherrypy.HTTPError(405, "Method not implemented.") if self.access_limit is not None: self.logger.log('Setting access limit to access_rights.%s (%s)' % (roles[self.access_limit], self.access_limit)) self.authenticator.set_limit(self.access_limit) elif cherrypy.request.method in self.limit_per_method: self.authenticator.set_limit(self.limit_per_method[cherrypy.request.method]) else: raise cherrypy.HTTPError(403, 'You cannot access this page with method %s' % cherrypy.request.method ) user_p = user_pack() l_type = locator() if not user_p.get_username(): #meaning we are going public, only allow GET. #if cherrypy.request.method != 'GET' or not l_type.isDev(): # raise cherrypy.HTTPError(403, 'User credentials were not provided.') if not 'public' in str(cherrypy.url()): self.logger.error('From within %s, adfs-login not found: \n %s \n %s' % (self.__class__.__name__, str(cherrypy.request.headers), str(cherrypy.url()) )) else: if not self.authenticator.can_access(user_p.get_username()): raise cherrypy.HTTPError(403, 'You cannot access this page, the limit for the page is {0} ({1})'.format(roles[self.authenticator.get_limit()], self.authenticator.get_limit())) # counter for calls with locker.lock("rest-call-counter"): key = method.im_class.__name__ + method.__name__ try: RESTResource.counter[key] += 1 except KeyError: RESTResource.counter[key] = 0 return method(*vpath, **params)
def filter(self, record): from tools.user_management import user_pack email = user_pack().get_email() if email: record.user = email else: record.user = "******" return True
def __get_submission_details(self): user_p = user_pack(db=True) if user_p.get_username() and user_p.get_fullname( ) and user_p.get_email(): return submission_details().build(user_p.get_username(), user_p.get_fullname(), user_p.get_email()) return submission_details().build('automatic')
def get_user_role(self): user_p = user_pack() role_index, role = authenticator.get_user_role_index( user_p.get_username(), email=user_p.get_email()) return { 'username': user_p.get_username(), 'role': role, 'role_index': role_index }
def __init__(self, json_input=None): json_input = json_input if json_input else {} # set invalidation status self._json_base__schema['status'] = self._json_base__status[0] # update self according to json_input self.update(json_input) self.validate() user_p = user_pack() self.current_user_email = user_p.get_email()
def notify(self, body): db = database('users') data = loads(body) list_of_mails = [ x["value"] for x in db.raw_query('pwg-mail', {'key': data["pwg"]}) ] com = communicator() com.sendMail(list_of_mails, data["subject"], data["content"], user_pack().get_email()) return { 'results': True, 'message': 'Sent message to {0}'.format(list_of_mails) }
def add_user(self): db = database(self.db_name) user_p = user_pack() if db.document_exists(user_p.get_username()): return {"results": "User {0} already in database".format(user_p.get_username())} mcm_user = user({"_id": user_p.get_username(), "username": user_p.get_username(), "email": user_p.get_email(), "role": roles[access_rights.user], "fullname": user_p.get_fullname()}) # save to db if not db.save(mcm_user.json()): self.logger.error('Could not save object to database') return {"results": False} return {"results": True}
def __init__(self, json_input={}): # set invalidation status self._json_base__status = ['new', 'announced'] self._json_base__schema = { '_id': '', 'prepid': '', 'object': '', 'status': self._json_base__status[0], 'type': '' } # update self according to json_input self.update(json_input) self.validate() user_p = user_pack() self.current_user_email = user_p.get_email()
def format(self, record): try: if record.done: return record.msg except: record.done = False rtime = time.strftime("%d/%b/%Y:%H:%M:%S", time.localtime(record.created)) from tools.user_management import user_pack email = user_pack().get_email() ## memory usage try: _proc_status = '/proc/%d/status' % os.getpid() t = open(_proc_status) v = t.read() t.close() i = v.index('VmRSS') v = v[i:].split(None, 3) # whitespace mem = "%s %s" % (v[1], v[2]) except: mem = "N/A" if record.levelno > 20: if email: record.msg = '[%s][user:%s][%s] {%s} %s' % ( rtime, email, record.levelname, self.find_topmost_stack_frame(), record.msg) else: record.msg = '[%s][%s] {%s} %s' % ( rtime, record.levelname, self.find_topmost_stack_frame(), record.msg) else: if email: record.msg = '[%s][user:%s][%s] %s' % ( rtime, email, record.levelname, record.msg) else: record.msg = '[%s][%s] %s' % (rtime, record.levelname, record.msg) record.msg = "{%s} %s" % (mem, record.msg) record.done = True return logging.Formatter.format(self, record)
def get(self, pwgs): """ Ask for the increase of the role of the current user to the given pwg """ # get who's there user_p = user_pack() udb = database(self.db_name) mcm_u = user(udb.get(user_p.get_username())) # get the requested pwgs pwgs = pwgs.split(',') # set the pwgs to the current user current = mcm_u.get_attribute('pwg') current = list(set(current + pwgs)) mcm_u.set_attribute('pwg', current) mcm_u.update_history({'action': 'ask role', 'step': pwgs}) udb.update(mcm_u.json()) # get the production managers emails __query = udb.construct_lucene_query({'role': 'production_manager'}) production_managers = udb.full_text_search('search', __query, page=-1) # send a notification to prod manager + service to_who = map(lambda u: u['email'], production_managers) + [ settings.get_value('service_account') ] to_who.append(user_p.get_email()) com = communicator() l_type = locator() subject = 'Increase role for user %s' % mcm_u.get_attribute('fullname') message = 'Please increase the role of the user %s to the next level.\n\n%susers?prepid=%s' % ( mcm_u.get_attribute('username'), l_type.baseurl(), mcm_u.get_attribute('username')) notification(subject, message, [], group=notification.USERS, action_objects=[mcm_u.get_attribute('prepid')], object_type='users', target_role='production_manager') com.sendMail(to_who, subject, message) return { "results": True, "message": "user %s in for %s" % (mcm_u.get_attribute('username'), current) }
def create_new(self, data): db = database('news') try: new_news = threaded_loads(data) except Exception as ex: return {"results":False} user_p = user_pack() new_news['author'] = user_p.get_username() #localtime = time.localtime(time.time()) #datetime = '' #for i in range(5): # datetime += str(localtime[i]).zfill(2)+'-' #datetime = datetime.rstrip('-') #datetime = '-'.join( map ('%02d'%localtime[0:5])) datetime = time.strftime('%Y-%m-%d-%H-%M') new_news['date'] = datetime new_news['announced'] = False db.save(new_news) return {"results":True}
def GET(self, *args): """ Ask for the increase of the role of the current user to the given pwg """ if not args: return dumps({"results": False, "Message": "not pwg provided"}) ## get who's there user_p = user_pack() udb = database(self.db_name) mcm_u = user(udb.get(user_p.get_username())) ## get the requested pwgs pwgs = args[0].split(',') #### set the pwgs to the current user current = mcm_u.get_attribute('pwg') current = list(set(current + pwgs)) mcm_u.set_attribute('pwg', current) mcm_u.update_history({'action': 'ask role', 'step': args[0]}) udb.update(mcm_u.json()) ## get the production managers emails production_managers = udb.queries(['role==production_manager']) ### send a notification to prod manager + service to_who = map(lambda u: u['email'], production_managers) + [ settings().get_value('service_account') ] to_who.append(user_p.get_email()) com = communicator() l_type = locator() com.sendMail( to_who, 'Increase role for user %s' % mcm_u.get_attribute('fullname'), 'Please increase the role of the user %s to the next level.\n\n%susers?prepid=%s' % (mcm_u.get_attribute('username'), l_type.baseurl(), mcm_u.get_attribute('username'))) return dumps({ "results": True, "message": "user %s in for %s" % (mcm_u.get_attribute('username'), current) })
def format(self, record): try: if record.done: return record.msg except: record.done = False rtime = time.strftime("%d/%b/%Y:%H:%M:%S", time.localtime(record.created)) from tools.user_management import user_pack email = user_pack().get_email() ## memory usage try: _proc_status = '/proc/%d/status' % os.getpid() t = open(_proc_status) v = t.read() t.close() i = v.index('VmRSS') v = v[i:].split(None, 3) # whitespace mem = "%s %s" % (v[1], v[2]) except: mem = "N/A" if record.levelno > 20: if email: record.msg = '[%s][user:%s][%s] {%s} %s' % ( rtime, email, record.levelname, self.find_topmost_stack_frame(), record.msg) else: record.msg = '[%s][%s] {%s} %s' % ( rtime, record.levelname, self.find_topmost_stack_frame(), record.msg) else: if email: record.msg = '[%s][user:%s][%s] %s' % ( rtime, email, record.levelname, record.msg) else: record.msg = '[%s][%s] %s' % ( rtime, record.levelname, record.msg) record.msg = "{%s} %s" % (mem, record.msg) record.done = True return logging.Formatter.format(self, record)
def change_role(self, username, action): db = database(self.db_name) doc = user(db.get(username)) user_p = user_pack() current_user = user(db.get(user_p.get_username())) current_role = doc.get_attribute("role") if action == '-1': if current_role != self.all_roles[0]: doc.set_attribute("role", self.all_roles[self.all_roles.index(current_role) - 1]) self.authenticator.set_user_role(username, doc.get_attribute("role")) doc.update_history({'action': 'decrease' , 'step':doc.get_attribute("role")}) return {"results": db.update(doc.json())} return {"results": username + " already is user"} #else return that hes already a user if action == '1': if len(self.all_roles) != self.all_roles.index(current_role) + 1: #if current role is not the top one doc.set_attribute("role", self.all_roles[self.all_roles.index(current_role) + 1]) self.authenticator.set_user_role(username, doc.get_attribute("role")) doc.update_history({'action': 'increase' , 'step':doc.get_attribute("role")}) return {"results": db.update(doc.json())} return {"results": username + " already has top role"} return {"results": "Failed to update user: "******" role"}
def change_role(self, username, action): db = database(self.db_name) doc = user(db.get(username)) user_p = user_pack() current_user = user(db.get(user_p.get_username())) current_role = doc.get_attribute("role") if action == '-1': if current_role != 'user': #if not the lowest role -> then him lower himself doc.set_attribute("role", self.all_roles[self.all_roles.index(current_role) - 1]) self.authenticator.set_user_role(username, doc.get_attribute("role")) return {"results": db.update(doc.json())} return {"results": username + " already is user"} #else return that hes already a user if action == '1': if current_user.get_attribute("role") != "administrator": return {"results": "Only administrators can upgrade roles"} if len(self.all_roles) != self.all_roles.index(current_role) + 1: #if current role is not the top one doc.set_attribute("role", self.all_roles[self.all_roles.index(current_role) + 1]) self.authenticator.set_user_role(username, doc.get_attribute("role")) return {"results": db.update(doc.json())} return {"results": username + " already has top role"} return {"results": "Failed to update user: "******" role"}
def GET(self, *args): """ Ask for the increase of the role of the current user to the given pwg """ if not args: return dumps({"results" : False, "Message" : "not pwg provided"}) ## get who's there user_p = user_pack() udb = database(self.db_name) mcm_u = user( udb.get( user_p.get_username())) ## get the requested pwgs pwgs = args[0].split(',') #### set the pwgs to the current user current = mcm_u.get_attribute('pwg') current = list(set(current+pwgs)) mcm_u.set_attribute('pwg', current) mcm_u.update_history({'action':'ask role','step' : args[0]}) udb.update(mcm_u.json()) ## get the production managers emails production_managers = udb.queries(['role==production_manager']) ### send a notification to prod manager + service to_who = map(lambda u: u['email'], production_managers) + [settings().get_value('service_account')] to_who.append( user_p.get_email() ) com = communicator() l_type = locator() com.sendMail( to_who, 'Increase role for user %s' % mcm_u.get_attribute('fullname'), 'Please increase the role of the user %s to the next level.\n\n%susers?prepid=%s' % ( mcm_u.get_attribute('username'), l_type.baseurl(), mcm_u.get_attribute('username') )) return dumps({"results" : True, "message" : "user %s in for %s" %( mcm_u.get_attribute('username'), current)})
def before_request(self): access_limit = self.__class__.access_limit if access_limit is not None: self.logger.info('Setting access limit to access_rights.%s (%s)' % (roles[access_limit], access_limit)) elif request.method in self.limit_per_method: access_limit = self.limit_per_method[request.method] user_p = user_pack() if not user_p.get_username(): # meaning we are going public, only allow GET. if 'public' not in request.path: self.logger.error( 'From within %s, adfs-login not found: \n %s \n %s' % (self.__class__.__name__, str( request.headers), str(request.path))) else: if not authenticator.can_access(user_p.get_username(), access_limit): if user_p.get_username() in self.access_user: self.logger.error('User %s allowed to get through' % user_p.get_username()) else: abort(403)
def before_request(self): access_limit = self.__class__.access_limit if access_limit is not None: self.logger.info('Setting access limit to access_rights.%s (%s)' % (roles[access_limit], access_limit)) elif request.method in self.limit_per_method: access_limit = self.limit_per_method[request.method] user_p = user_pack() try: self.user_dict = {'username': user_p.get_username(), 'role': authenticator.get_user_role(user_p.get_username())} except: self.user_dict = {'username': '******', 'role': 'user'} if not user_p.get_username(): # meaning we are going public, only allow GET. if 'public' not in request.path: self.logger.error('From within %s, adfs-login not found: \n %s \n %s' % (self.__class__.__name__, str(request.headers), str(request.path))) else: if not authenticator.can_access(user_p.get_username(), access_limit): if user_p.get_username() in self.access_user: self.logger.error('User %s allowed to get through' % user_p.get_username()) else: abort(403)
def change_role(self, username, action): db = database(self.db_name) doc = user(db.get(username)) user_p = user_pack() current_user = user(db.get(user_p.get_username())) current_role = doc.get_attribute("role") if action == '-1': if current_role != self.all_roles[0]: doc.set_attribute( "role", self.all_roles[self.all_roles.index(current_role) - 1]) self.authenticator.set_user_role(username, doc.get_attribute("role")) doc.update_history({ 'action': 'decrease', 'step': doc.get_attribute("role") }) return {"results": db.update(doc.json())} return { "results": username + " already is user" } #else return that hes already a user if action == '1': if len(self.all_roles) != self.all_roles.index( current_role) + 1: #if current role is not the top one doc.set_attribute( "role", self.all_roles[self.all_roles.index(current_role) + 1]) self.authenticator.set_user_role(username, doc.get_attribute("role")) doc.update_history({ 'action': 'increase', 'step': doc.get_attribute("role") }) return {"results": db.update(doc.json())} return {"results": username + " already has top role"} return {"results": "Failed to update user: "******" role"}
def add_user(self): db = database(self.db_name) user_p = user_pack() if db.document_exists(user_p.get_username()): return { "results": "User {0} already in database".format(user_p.get_username()) } mcm_user = user({ "_id": user_p.get_username(), "username": user_p.get_username(), "email": user_p.get_email(), "role": roles[access_rights.user], "fullname": user_p.get_fullname() }) # save to db if not mcm_user.reload(): self.logger.error('Could not save object to database') return {"results": False} mcm_user.update_history({'action': 'created'}) mcm_user.reload() return {"results": True}
def __get_submission_details(self): user_p = user_pack(db=True) if user_p.get_username() and user_p.get_fullname() and user_p.get_email(): return submission_details().build(user_p.get_username(), user_p.get_fullname(), user_p.get_email()) return submission_details().build('automatic')
def index(self): if not self.authenticator.can_access(user_pack().get_username()): raise cherrypy.HTTPError(403, 'You cannot access this page') if not self.restful: return self.header() + self.result + self.footer() return self.result
def get_user_role(self): user_p = user_pack() role_index, role = self.authenticator.get_user_role_index(user_p.get_username(), email=user_p.get_email()) return {'username': user_p.get_username(), 'role': role, 'role_index': role_index}
def header(self): header_tmpl = self.environment.get_template('header.tmpl') return self.authenticator.get_login_box(user_pack().get_username()) + header_tmpl.render({'title': self.title})