예제 #1
0
 def do_genca(self, inp):
     '''Create a new CA'''
     cert, key = gen_ca_interactive()
     desc = input("Please enter an description: ")
     ca = CA(desc, cert, key)
     session.add(ca)
     session.commit()
예제 #2
0
def parsiraj (studij):
    res = requests.get(studij.url)
    soup = bs4.BeautifulSoup(res.text, 'html.parser')

    divs = soup.select('.appointment > div.h4 > span')
    styles = soup.select('.appointment[style]')
    scripts = soup.select('script')
    lines = scripts[18].string.split("\n")
    appointments = {}
    for idx, line in enumerate(lines):
        #print(line)
        if line.startswith("FActivityArray") and "[\"id\"]" in line:
            id = line.replace(";", "").split(" = ")[1].replace("\"", "").replace("\r", "")

            startDateTime = lines[idx + 5].replace(";", "").split(" = ")[1].replace("\"", "").replace("\r", "")
            starTime1 = lines[idx + 5].replace(";", "").split(" = ")[1].replace("\"", "").replace("\r", "").split(',')[1].split(":")

            startTime=starTime1[0]+":"+starTime1[1]

            endDateTime = lines[idx + 4].replace(";", "").split(" = ")[1].replace("\"", "").replace("\r", "")
            endTime1 = lines[idx + 4].replace(";", "").split(" = ")[1].replace("\"", "").replace("\r", "").split(',')[1].split(":")
            endTime=endTime1[0]+":"+endTime1[1]
            startDateTime =  datetime.strptime(startDateTime, "%Y-%m-%d,%H:%M:%S").date()
            month=startDateTime.month;
            day=startDateTime.day;
            startDateTime2=str(day) +"."+str(month)
            endDateTime = datetime.strptime(endDateTime, "%Y-%m-%d,%H:%M:%S")



            appointments[id] = {
                'id': id,
                'date': startDateTime2,
                'duration': 1,
                'endDateTime': endTime,
                'startTime': startTime,
                'studiji.id': studij.godina
            }

    for id, div in enumerate(divs):
        style = {}
        for attr in styles[id]['style'].split(";"):
            if (len(attr.split(":")) == 2):
                key, value = attr.split(":")
                style[key] = value
        termin = Termin()
        appointment = appointments[divs[id]['id'].replace("_vertraulich", "")]
        termin.title = divs[id].text
        termin.date = appointment['date']
        termin.duration = appointment['duration']
        termin.startTime = appointment['startTime']
        termin.endTime = appointment['endDateTime']
        termin.studiji_id = studij.id
        session.add(termin)
        session.commit()
예제 #3
0
    def do_importca(self, inp):
        '''Import an CA'''
        # Get the key and cert from file
        key, cert = self._load_key_and_cert_from_file()

        # Enrich with description
        desc = input("Please enter an description: ")

        # Creat DB-Object and commit
        ca = CA(desc, cert, key)
        session.add(ca)
        session.commit()
예제 #4
0
    def do_importcert(self, inp):
        '''Import an Cert'''

        # Get ca_id to export by user and extract from db
        self._print_cas()
        ca_id = input("CA to use for signing: ")
        ca = session.query(CA).filter(CA.id == ca_id).one()

        # Get the key and cert from file
        key, cert = self._load_key_and_cert_from_file()

        # Creat DB-Object and commit
        desc = input("Please enter an description: ")
        cert = CERT(desc, cert, key, ca)
        session.add(cert)
        session.commit()
예제 #5
0
    def do_gencert(self, inp):
        '''Add an CERT to an CA'''
        # Print existing CAs
        self._print_cas()

        # Get ca_id to export by user
        ca_id = input("CA to use for signing: ")

        # Extract from the DB
        ca = session.query(CA).filter(CA.id == ca_id).one()

        # Generate CERT, create an DB-Obj and add to session
        cert, key = gen_cert(ca=ca)
        desc = input("Please enter an description: ")
        cert = CERT(desc, cert, key, ca)
        session.add(cert)
        session.commit()
예제 #6
0
def remove_favorite(user: User, post: Post):
    """
    Removes a favorite from a user
    This will not succeed if the user is not stored in the database
    Or if the user did not have the favorite

    :param user: the user
    :param post: the post
    :return: True if removing succeeds, False if not
    """
    db_post = session.query(DBPost).get(
        (user.id, post.post_id, post.board_url.short_url))

    session.delete(db_post)
    session.commit()
    logging.info(
        f'Removed favorite, user={user}, post_id={post.post_id}, url={post.board_url}'
    )
예제 #7
0
def father():
    if request.method == 'POST':
        data = request.json
        logging.debug('Received data on /father: {}'.format(data))
        father = Father(data['name'], data['last_name'])
        session.add(father)
        session.commit()
        return Response(status=200)

    else:
        ret = []
        for elem in session.query(Father).all():
            tmp = {}
            tmp['name'] = elem.name
            tmp['last_name'] = elem.last_name
            ret.append(tmp)

        # ret = "{}; {}".format(ret, entry.name)
        return json.dumps(ret)
예제 #8
0
def store_favorite(user: User, post: Post) -> bool:
    """
    Stores a favorite for a user
    This might fail if the user already has the post as a favorite

    :param user: the user
    :param post: the post
    :return: True if storing the favorite succeeds, False if not
    """
    if post.is_error() or exists(user, post):
        return False

    db_post = DBPost(user_id=user.id,
                     post_id=post.post_id,
                     url=post.board_url.short_url,
                     saved_at=datetime.now())
    session.add(db_post)
    session.commit()

    logging.info(
        f'Stored favorite, user={user}, post_id={post.post_id}, url={post.board_url}'
    )
    return True
    def __init__(self, args):

        if args.store_db:
            # Only import if db-storage is requested
            from db.model import session, CA, CERT

        print("[+] Reading JSON")
        f = open(args.json, 'r')
        try:
            ca_json = json.loads(f.read())
            f.close()
        except json.decoder.JSONDecodeError as e:
            print("[!] Your Json is broken!")
            print(e)
            f.close()
            sys.exit()
        print("[+] JSON ok")

        # Generate key and cert for CA
        print("[+] Generating CA")
        ca_cert, ca_key = gen_ca_noninter(
            countryName=ca_json['ca']['countryName'],
            stateOrProvinceName=ca_json['ca']['stateOrProvinceName'],
            localityName=ca_json['ca']['localityName'],
            organizationName=ca_json['ca']['organizationName'],
            organizationUnitName=ca_json['ca']['organizationUnitName'],
            commonName=ca_json['ca']['commonName'],
            emailAddress=ca_json['ca']['emailAddress'],
            serialNumber=ca_json['ca']['serialNumber'],
            validityStartInSeconds=ca_json['ca']['validityStartInSeconds'],
            validityEndInSeconds=ca_json['ca']['validityEndInSeconds'])

        path = args.out_path

        # TODO(--store-db not yet defined)
        # Export ca
        self._write_to_disk(path, "", ca_json['ca']['commonName'] + ".key",
                            ca_key)
        self._write_to_disk(path, "", ca_json['ca']['commonName'] + ".crt",
                            ca_cert)

        if args.store_db:
            ca = CA("Imported vis JSON", ca_cert, ca_key)
            session.add(ca)
            session.commit()

        # Generate certificates
        print("[+] Generating Certs")
        password = ''.join(
            random.choice(string.ascii_letters) for i in range(30))
        print("[*] The password for the pk12-files is: {}".format(password))
        for cert_req in ca_json['ca']['certs']:
            # Generate Cert
            cert, key = gen_cert(ca_key=ca_key,
                                 ca_cert=ca_cert,
                                 commonName=cert_req['commonName'])

            # Export
            # Save crt
            subfix = ca_json['ca']['commonName']
            self._write_to_disk(path, subfix, cert_req['commonName'] + ".crt",
                                cert)
            # Save Key
            self._write_to_disk(path, subfix, cert_req['commonName'] + ".key",
                                key)

            # Save pk12
            pk12 = create_pkcs12(key, cert, password)
            self._write_to_disk(path, subfix, cert_req['commonName'] + ".p12",
                                pk12)

            if args.store_db:
                cert = CERT("Imported vis JSON", cert, key, ca)
                session.add(cert)
                session.commit()