Example #1
0
    async def alias(self, ctx, original_command: str, new_alias: str):
        command = self.bot.get_command(original_command)
        if command is None:
            await ctx.send(
                f"'{original_command}' is not the name of a command, so you cannot add an alias to it"
            )
            return
        elif not (self.bot.get_command(new_alias) is None):
            await ctx.send(
                f"'{new_alias}' is already a command. You cannot use it as an alias."
            )
            return
        else:
            existing_alias = session.query(Alias).filter(
                Alias.alias == new_alias).one_or_none()
            if existing_alias is None:
                # We actually create the new alias
                alias_record = Alias()
                alias_record.server_id = ctx.guild.id
                alias_record.command = original_command
                alias_record.alias = new_alias
                session.add(alias_record)
                session.commit()

                await ctx.send(
                    f"Added alias '{new_alias}' for command '{original_command}'"
                )
            else:
                await ctx.send(
                    f"'{new_alias}' already exists as an alias for command '{existing_alias.command}'"
                )
Example #2
0
def save_alias(alias, username):
    alias = Alias(
        name=alias,
        owner_key=Employee.get_key_for_username(username),
    )
    alias.put()
    return alias
Example #3
0
    def test_delete_alias(self):
        create_employee(username='******')
        alias = logic.alias.save_alias('jane', 'janed')
        self.assertEqual(Alias.query().count(), 1)

        logic.alias.delete_alias(alias.key.id())

        self.assertEqual(Alias.query().count(), 0)
Example #4
0
    def test_save_alias(self):
        johnd = create_employee(username='******')
        self.assertEqual(Alias.query().count(), 0)

        alias = logic.alias.save_alias('johnny', 'johnd')

        self.assertEqual(Alias.query().count(), 1)
        self.assertEqual(alias.name, 'johnny')
        self.assertEqual(alias.owner_key, johnd.key)
Example #5
0
def create_alias_with_employee_username(
    name='jda',
    username='******',
):
    alias = Alias(
        name=name,
        owner_key=Employee.get_key_for_username(username),
    )
    alias.put()
    return alias
Example #6
0
def create_alias_with_employee_key(
    name='jda',
    employee_key='jd',
):
    alias = Alias(
        name=name,
        owner_key=employee_key,
    )
    alias.put()
    return alias
Example #7
0
def save_alias(name, matches, generator, session):
    new = True
    alias = find_alias(name, session, generator)
    if alias:
        new = False
        for match in matches:
            merge_alias(alias, match, session)

    else:
        for match in matches:
            alias = find_alias(name, session, generator)
            if alias:
                new = False
                merge_alias(alias, match, session)

    if new:
        rec = Alias()
        rec.name = name
        rec.generator = generator
        rec.alias1 = matches[0]
        if len(matches) > 1:
            rec.alias2 = matches[1]
        if len(matches) > 2:
            rec.alias3 = matches[2]
        if len(matches) > 3:
            rec.alias4 = matches[3]
        if len(matches) > 4:
            rec.alias5 = matches[4]
        inner_save_alias(rec, session)
Example #8
0
    def post(self):
        csvfile = self.get_uploads('label-upload')
        key = cgi.escape(self.request.get('label-type'))

        if key and csvfile:
            t = Template.get_by_id(key) or Alias.get_by_id(key)
            if t.__class__ == Alias:
                t = Template.query(Template.aliases == t.key).fetch()[0]
    
            blob = csvfile[0]
            iterator = BlobIterator(blobstore.BlobReader(blob.key()))

            labels = list()
            for row in csv.reader(iterator):
                if row: labels.append(row)
            
            blobstore.delete(blob.key())
            
            template = JINJA_ENVIRONMENT.get_template('labels.html')
            self.response.write(template.render({'key': t.key.string_id(),
                                                 'labels': labels,
                                                 'labels_per_page': int(t.layout.get().nx * t.layout.get().ny),
                                                 'label_barcode': cgi.escape(self.request.get('label-barcode')),
                                                 'label_orientation': cgi.escape(self.request.get('label-orientation')),
                                                 'label_font_size': cgi.escape(self.request.get('label-font-size')),
                                                 }))
        else:
            self.redirect('/') #TODO
Example #9
0
def name_for_alias(alias_name):
    alias = Alias.query(Alias.name == alias_name).get()
    if alias:
        employee = alias.owner_key.get()
        if employee:
            return employee.username
    else:
        return alias_name
Example #10
0
 def get(self):
     upload_url = blobstore.create_upload_url('/upload')
     
     templates, aliases = Template.query().order(Template.key).fetch(), Alias.query().order(Template.key).fetch()
     #templates.extend(aliases)
     templates = [ t.key.string_id() for t in templates ]
     templates.sort()
     
     template = JINJA_ENVIRONMENT.get_template('form.html')
     self.response.write(template.render({'upload_url': upload_url,
                                          'templates': templates}))
Example #11
0
def check_nonce():
    """
    This function is an agaveflask authentication callback used to process the existence of a query parameter,
    x-nonce, an alternative authentication mechanism to JWT.
    
    When an x-nonce query parameter is provided, the request context is updated with the identity of the user owning
    the actor to which the nonce belongs. Note that the roles of said user will not be calculated so, in particular, 
    any privileged action cannot be taken via a nonce. 
    """
    logger.debug("top of check_nonce")
    try:
        nonce_id = request.args['x-nonce']
    except KeyError:
        raise PermissionsException("No JWT or nonce provided.")
    logger.debug("checking nonce with id: {}".format(nonce_id))
    # the nonce encodes the tenant in its id:
    g.tenant = Nonce.get_tenant_from_nonce_id(nonce_id)
    g.api_server = get_api_server(g.tenant)
    logger.debug("tenant associated with nonce: {}".format(g.tenant))
    # get the actor_id base on the request path
    actor_id, actor_identifier = get_db_id()
    logger.debug("db_id: {}; actor_identifier: {}".format(
        actor_id, actor_identifier))
    level = required_level(request)

    # if the actor_identifier is an alias, then the nonce must be attached to that, so we must pass that in the
    # nonce check:
    if is_hashid(actor_identifier):
        Nonce.check_and_redeem_nonce(actor_id=actor_id,
                                     alias=None,
                                     nonce_id=nonce_id,
                                     level=level)
    else:
        alias_id = Alias.generate_alias_id(tenant=g.tenant,
                                           alias=actor_identifier)
        Nonce.check_and_redeem_nonce(actor_id=None,
                                     alias=alias_id,
                                     nonce_id=nonce_id,
                                     level=level)
    # if we were able to redeem the nonce, update auth context with the actor owner data:
    logger.debug("nonce valid and redeemed.")
    if is_hashid(actor_identifier):
        nonce = Nonce.get_nonce(actor_id=actor_id,
                                alias=None,
                                nonce_id=nonce_id)
    else:
        nonce = Nonce.get_nonce(actor_id=None,
                                alias=alias_id,
                                nonce_id=nonce_id)
    g.user = nonce.owner
    # update roles data with that stored on the nonce:
    g.roles = nonce.roles
    # now, manually call our authorization function:
    authorization()
Example #12
0
def get_alias_id():
    """Get the alias from the request path."""
    path_split = request.path.split("/")
    if len(path_split) < 4:
        logger.error(
            "Unrecognized request -- could not find the alias. path_split: {}".
            format(path_split))
        raise PermissionsException("Not authorized.")
    alias = path_split[3]
    logger.debug("alias: {}".format(alias))
    return Alias.generate_alias_id(g.tenant, alias)
Example #13
0
 def get(self, key):
     key = key.replace('.css', '')
     
     t = Template.get_by_id(key) or Alias.get_by_id(key)
     if t.__class__ == Alias:
         t = Template.query(Template.aliases == t.key).fetch()[0]
     
     template = JINJA_ENVIRONMENT.get_template('css/template.css')
     self.response.headers['Content-Type'] = 'text/css'
     self.response.write(template.render({'name': t.key.string_id(),
                                          'paper_width': t.size[0],
                                          'left_margin': t.left_margin,
                                          'top_margin': t.top_margin,
                                          'label_width': t.label_width,
                                          'label_height': t.label_height,
                                          'label_margin_right': t.label_margin_right
                                          }))
Example #14
0
def home(request):
    try:
        x = "%s" % request.POST["alias"]
        count = 0
        for char in x:
            if char == ' ':
                count += 1
            else:
                count += 100000
        if count == 0:
            return render(request, "enter.html")
    except:
        return HttpResponse("hi")
    try:
        count = 0
        all_A = Alias.objects.all()
        for A in all_A:
            if A.name == x:
                A.logins += 1
                A.last_login = datetime.now(tz)
                A.save()
                current_A = A
                count += 1
        if count == 0:
            new_A = Alias()
            new_A.name = x
            new_A.date = datetime.now(tz)
            new_A.last_login = datetime.now(tz)
            new_A.logins = 1
            new_A.save()
            current_A = new_A
        latest_habla = Habla.objects.order_by('-id')[0:5]
        latest_habla = list(reversed(latest_habla))[0:5]
        show_habla = [(h.text, h.date) for h in latest_habla]
        context = {"alias": current_A, "habla": show_habla}
    except:
        return HttpResponse("hi2")
    try:
        return render(request, "home.html", context)
    except:
        return HttpResponse("hi3")
Example #15
0
File: web.py Project: sharan1/love
def aliases():
    return render_template(
        'aliases.html',
        aliases=Alias.query().fetch(),
    )
Example #16
0
def get_alias(alias):
    return Alias.query(Alias.name == alias).get()
def read_zipcodes(input_file):
    """Reads in zip code information from a database csv defined by input_file
       and returns a list of locations and a list of aliases"""

    location_list = []
    alias_list = []

    with open(input_file, encoding='ISO-8859-1') as file_descriptor:
        reader = csv.reader(file_descriptor)

        for (zip_code, mail_type, primary_city, aliases, _, state, _, _, _,
             latitude, longitude, _, country, _, estimated_population,
             _) in reader:

            # Skip the line containing the column definitions
            if reader.line_num == 1:
                continue

            # Do not handle any zip codes outside of the US
            if country != 'US':
                logging.debug('line #{}: country equal to {}'.format(
                    reader.line_num, country))
                continue

            # Do not handle military zip codes since they are often international
            if mail_type == 'MILITARY':
                logging.debug('line #{}: country equal to {}'.format(
                    reader.line_num, mail_type))
                continue

            if state not in states:
                logging.debug(
                    'line #{}: state identifier of {} is invalid.'.format(
                        reader.line_num, state))
                continue
            else:
                # All strings in the database are lowercase. Let's work with lowercase from the beginning.
                state = state.lower()

            if latitude:
                latitude = float(latitude)
            else:
                logging.error('line #{}: Latitude not present.'.format(
                    reader.line_num))
            if longitude:
                longitude = float(longitude)
            else:
                logging.error('line #{}: longitude not present.'.format(
                    reader.line_num))

            if not zip_code:
                logging.error('line #{}: zipcode not present.'.format(
                    reader.line_num))

            if primary_city:
                # All strings in the database are lowercase. Let's work with lowercase from the beginning.
                primary_city = primary_city.strip().lower()
            else:
                logging.error('line #{}: primary_city not present.'.format(
                    reader.line_num))

            if estimated_population:
                estimated_population = int(estimated_population)
            else:
                logging.debug(
                    'line #{}: estimated populated not present. Marking as 0'.
                    format(reader.line_num))
                estimated_population = 0

            if aliases:
                aliases = [city.strip().lower() for city in aliases.split(',')]
                for city in aliases:
                    alias_list.append(
                        Alias(reader.line_num, zip_code, city, state,
                              estimated_population))

            # There are some extra fields in here... that data is in case we want to calculate which zip codes are within
            # an xxx radius of other zip codes. That functionality is not included in this script.
            location_list.append(
                Location(reader.line_num, zip_code, latitude, longitude,
                         primary_city, state, estimated_population))

    return location_list, alias_list
Example #18
0
def delete_alias(alias_id):
    alias = Alias.get_by_id(alias_id)
    alias.key.delete()