def user_is_admin(): try: has_group = authorized(HasAuthKitGroup('administrators')) except: has_group = False try: has_role = authorized(HasAuthKitRole('administrator')) except: has_role = False log.debug('Is user administrator: by group %s? by role %s?' % (has_group, has_role)) return has_group or has_role
def send_email(self): if not authorized(ValidAuthKitUser()): return { "failure" : Messages.invalidSession() } try: to_address = request.params['to_address'] subject = request.params['subject'] body = request.params['body'] except: return { "failure" : Messages.invalidArguments() } if to_address == "" or subject == "" or body == "": return { "failure" : Messages.invalidArguments() } from email.MIMEText import MIMEText message = MIMEText(body.encode('utf-8'), 'plain', 'utf-8') message['Subject'] = subject message['From'] = config['from_address'] message['To'] = to_address try: from fivecents.lib.mail import EmailSender ms = EmailSender(to_addresses = to_address) ms.send_mime(message) except Exception, e: return { "failure" : Messages.failedToSendEmail(exception=e) }
def user_is_admin(): """ Returns True if current user is an admin. """ try: has_group = authorized(HasAuthKitGroup("administrators")) except: has_group = False try: has_role = authorized(HasAuthKitRole("administrator")) except: has_role = False log.debug(_("Is user administrator: by group %s? by role %s?" % (has_group, has_role))) return has_group or has_role
def send_email(self): """ Will send an e-mail with to a given address. Only authenticated users can use it. """ if not authorized(ValidAuthKitUser()): return { "failure" : Messages.invalidSession() } to_address = request.params.get('to_address') subject = request.params.get('subject') body = request.params.get('body') if not to_address or not subject or not body: return { "failure" : Messages.invalidArguments() } from email.MIMEText import MIMEText message = MIMEText(body.encode('utf-8'), 'plain', 'utf-8') message['Subject'] = subject message['From'] = config['from_address'] message['To'] = to_address try: self.emailSender().send_mime(to_address, config['from_address'], message) except Exception, e: return { "failure" : Messages.failedToSendEmail(exception=e) }
def send_invitation(self): model = self.get_sa_model() db = self.get_sa_session() if not authorized(ValidAuthKitUser()): return { "failure" : Messages.invalidSession() } to_address = request.params.get('to_address') body = request.params.get('body') if not to_address or not body: return { "failure" : Messages.invalidArguments() } invitation = db.query(model.Invitation).filter_by(to_address = to_address).filter_by(sender_uid=h.authenticated_user().uid).first() if invitation: invitation.message = body invitation.sent = False invitation.sent_on = datetime.today() else: invitation = model.Invitation( sender_uid = h.authenticated_user().uid, to_address = to_address, message = body ) db.save(invitation) db.commit() return { "success" : Messages.messageWasSent() }
def get_permissions(self): return { "url": self.url, "layers": dict(((name, authorized(perm)) for (name, perm) in self.layers.iteritems())) }
def login(self): if not authorized(RemoteUser()): response.status = "401 Not authenticated" return "Only project administrator may view this page. " \ "Please try again." session['user_id'] = request.environ.get("REMOTE_USER") session.save() redirect(url(controller="scalak_user", action="userInfo"))
def user_is_authenticated(): try: si = authorized(ValidAuthKitUser()) except: si = False if si: try: if c.signed_out: si = False except: pass return si
def login(self, id=None): if not id: return "<h1>Please log in first.</h1>" if not authorized(RemoteUser()) or \ request.environ.get("REMOTE_USER") != getAdmin(id): response.status = "401 Not authenticated" return "Only project administrator may view this page. " \ "Please try again." session['project_id'] = id session.save() redirect(url(controller="project", action="projectInfo"))
def check_permissions(self): # Check layers layers = self.get_requested_layers() for layer in layers: if self.layers.has_key(layer): perm = self.layers[layer] elif self.layers.has_key("DEFAULT"): perm = self.layers["DEFAULT"] else: continue if not authorized(perm): return False, "Not allowed to access layer: %s" % cgi.escape(layer) # TODO add other checks here (bbox, ...) return True, "Access allowed"
def check_permissions(self): # Check layers layers = self.get_requested_layers() for layer in layers: if self.layers.has_key(layer): perm = self.layers[layer] elif self.layers.has_key("DEFAULT"): perm = self.layers["DEFAULT"] else: continue if not authorized(perm): return False, "Not allowed to access layer: %s" % cgi.escape( layer) # TODO add other checks here (bbox, ...) return True, "Access allowed"
def send_invitation(self): model = request.environ["sqlalchemy.model"] db = request.environ["sqlalchemy.session"] if not authorized(ValidAuthKitUser()): return { "failure" : Messages.invalidSession() } try: to_address = request.params['to_address'] subject = _("You have been invited to %s " % h.site_name()) body = request.params['body'] except: return { "failure" : Messages.invalidArguments() } if to_address == "" or subject == "" or body == "": return { "failure" : Messages.invalidArguments() } invitation = model.Invitation( sender_uid = h.authenticated_user().uid, to_address = to_address, ) db.save(invitation) db.commit() c.invitation_link = h.site_url() + h.url_for(controller='signup', action='invitation', id=invitation.token) from email.MIMEText import MIMEText body = body + render_jinja('messages/invitation_footer.jinja') message = MIMEText(body.encode('utf-8'), 'plain', 'utf-8') message['Subject'] = subject message['From'] = config['from_address'] message['To'] = to_address try: from fivecents.lib.mail import EmailSender ms = EmailSender(to_addresses = to_address) ms.send_mime(message) except Exception, e: return { "failure" : Messages.failedToSendEmail(exception=e) }
def _get_master_permissions(self): """Read the permissions in the config/permissions.json file and return an object """ perm_json = os.path.join(config.here, config['pylons.package'], "config", "permissions.json") permissions = {} modulename = "%s.config.permissions" % config['pylons.package'] try: mod = __import__(modulename) for comp in modulename.split(".")[1:]: mod = getattr(mod, comp) permissions = mod.permissions except ImportError: log.debug("Couldn't find permission configuration module %s" % modulename) # compute permissions # TODO: calling authorized should be propagated inside nested dicts. permissions = dict(((key, authorized(perm)) for (key, perm) in permissions.iteritems())) return permissions
def messages(self): # Grab the list of possible recipients (for sending). Includes both users and groups # title c.title = config.get('project.shortname','CyberWeb') + ' Messages for: ' + session.get('user','you') c.recipients = [{'name':i.username,'value':'u%d' % i.id} for i in meta.Session.query(User)] # Admins can see all groups, but non-admins can only see their own groups. if authorized(auth.is_admin): for i in meta.Session.query(GroupDefinition): c.recipients.append({'name':'%s (group)' % i.name,'value':'g%d' % i.id}) c.recipients.append({'name':'Broadcast','value':'b0'}) else: for i in meta.Session.query(Group).filter(Group.user_id == session['user_id']): c.recipients.append({'name':'%s (group)' % i.group_definition.name,'value':'g%d' % i.group_definition_id}) # Grab the list of messages messages = meta.Session.query(Message).filter(sa.or_(Message.recipient_group_id.in_(session['user_groups']),\ Message.recipient_user_id == session['user_id'],\ sa.and_(Message.recipient_group_id == sa.null(), Message.recipient_user_id == sa.null())))\ .order_by() c.messages = [ {'Date':i.date.strftime("%b %d,%y %H %M %p"), 'Message':i.message, 'From':i.author.username} for i in messages ] c.messageheaders = ['Date','From','Message'] meta.Session.close() return render('/account/messages.mako')
def is_admin(): return authorized(HasAuthKitRole('admin'))
def is_authorized(): return authorized(ValidAuthKitUser())
def checkLogin(): if not session.get("project_id", None) or \ not authorized(RemoteUser()): redirect(url(controller="auth", action="logout"))
def checkLogIn(session): if not session.get("user_id", None) or \ not authorized(RemoteUser()): redirect(url(controller="scalak_user", action="login"))
def _updatelisting(self, box, hostname='', path=''): account_id = int(session[SESS_KEY][box]['host'] or 0) account = meta.Session.query(Account).filter(Account.id == account_id).one() try: is_account_holder = account.user_id == session.get('user_id') except Exception as _: is_account_holder = False # Get user project path. ###cwuserpath = config.get('cw.cwuser_loc') cwuserpath = config.get('cw.cwuser_rem') userprojpath = os.path.sep.join([cwuserpath, session.get('user', 'guest')]) # Set the path to one of the following (in order): specified path, existing path, user cw directory path = path if path else session[SESS_KEY][box].get('path', '') if not path: path = userprojpath # Prevent non-admins from accessing other folders elif not (authorized(auth.is_admin) or is_account_holder) and not path.startswith(userprojpath): path = userprojpath # Obtain actual listing try: listing = self._getlisting(account_id, path) log.debug('Updating %s %d:%s', box, account_id, path) except Exception: listing = [] log.critical('Cannot update listing on %d!', account_id) if path.startswith(cwuserpath): mindir = None maxdir = None mypath = '' outputpath = '' jobname = '' jobid = '' path_arr = path.replace(cwuserpath, '').split('/') if len(path_arr) >= 2: jobname = path_arr[1] jobid = jobname.split('_')[-1] mypath = cwuserpath + '/'.join(path_arr[:2]) outputpath = mypath + '/output' ls_output = self._getlisting(account_id, outputpath) if not ls_output: outputpath = mypath + '/OUTPUT' ls_output = self._getlisting(account_id, outputpath) for i in ls_output: if i[0] == 'file' and i[1].endswith('.dat'): try: mynum = int(i[1][1:5]) except Exception as e: log.error('Listing update failure! %s,%s. %s' % i[1], i[1][1:5], e) if mindir == None or mynum < mindir: mindir = mynum if max == None or mynum > max: maxdir = mynum session[SESS_KEY]['viz']['jobname'] = jobname session[SESS_KEY]['viz']['jobid'] = jobid session[SESS_KEY]['viz']['start_time'] = mindir session[SESS_KEY]['viz']['stop_time'] = maxdir session[SESS_KEY]['viz']['jobdir'] = mypath session[SESS_KEY]['viz']['outputdir'] = outputpath try: c.model_key = jobname.split('_')[2] c.grid_key = Gccom.model_info[c.model_key]['grid_key'] session[SESS_KEY]['viz']['model_key'] = c.model_key session[SESS_KEY]['viz']['grid_name'] = Gccom.bath_grid[c.grid_key]['name'] session[SESS_KEY]['viz']['grid_imax'] = Gccom.bath_grid[c.grid_key]['IMax'] session[SESS_KEY]['viz']['grid_jmax'] = Gccom.bath_grid[c.grid_key]['JMax'] session[SESS_KEY]['viz']['grid_kmax'] = Gccom.bath_grid[c.grid_key]['KMax'] except (AttributeError, IndexError) as _: pass # Update session variables session[SESS_KEY][box]['path'] = path session[SESS_KEY][box]['listing'] = listing session.save() c.data = session[SESS_KEY] log.debug("c.data: %s", c.data) return render(self.mako)
def index(self): if not (hasattr(c, 'signed_out') and c.signed_out) and authorized(ValidAuthKitUser()): redirect_to(h.url_for(controller='balances', action='index')) c.action_url = h.url_for(controller='balances') return render_jinja('index.jinja')
def is_admin(): return authorized(HasAuthKitRole("admin"))
def __before__(self, action, **params): c.admin = authorized(HasAuthKitGroup(['admin']))