Ejemplo n.º 1
0
def makeQRCode(data, mode):
    """ Make a graphical representation of a QRCODE in unicode."""
    sio = StringIO()
    qr_code = QRCode()
    qr_code.add_data(data)
    qr_code.print_ascii(out=sio, invert=mode == 'text')
    return '\n'.join(line.lstrip() for line in sio.getvalue().split('\n'))
Ejemplo n.º 2
0
def create_qr(data, z=None):

   
    box_size = int(z) < 15 and int(z) or 10
    meta = PngImagePlugin.PngInfo()
    filehash = sha1(data.encode('ascii', 'ignore')).hexdigest()[:12]
    filepath = os.path.join(app.config['UPLOAD_FOLDER'], filehash+'.png')
    
    data = data.encode('utf8')
    meta.add_text('message', data)
    
    if not os.path.exists(filepath):
        qr = QRCode(
            version=4,
            border=4,
            box_size=box_size,
        )

        qr.add_data(data)

        img = qr.make_image()
        img.save(filepath, 'png', pnginfo=meta)
    else :
        img = file(filepath)
    return (img, filepath, filehash)
Ejemplo n.º 3
0
def qrcode_view(request, code, size, size_in_centimeters=False):

    if size_in_centimeters:
        size = int(size)
        if size <= 6:
            size = NORMAL_SIZE
        elif size <= 8:
            size = LARGE_SIZE
        else:
            size = VERY_LARGE_SIZE
        qr = QRCode(
            error_correction=LEVEL[size],
            box_size=SIZE[size],
            border=0,
        )
    else:
        qr = QRCode(
            error_correction=LEVEL[size],
            box_size=SIZE[size],
            border=0,
        )
    qr.add_data(code)
    img = qr.make_image()

    rsp = HttpResponse(content_type='image/png')
    img.save(rsp)

    return rsp
Ejemplo n.º 4
0
def register():
   form = RegistrationForm(request.form)
   if request.method == 'POST' and form.validate_on_submit():
      #user = User(form.first_name.data, form.last_name.data, form.username.data,
      #            form.username.data, form.email.data, form.enrollment.data,
      #            form.college_name.data)
      user = User()
      form.populate_obj(user)
      #user.password = generate_password_hash(user.password)
      user.qr_data = sha1(user.email).hexdigest()

      qr = QRCode(version=10, error_correction=ERROR_CORRECT_H)
      qr.add_data(user.qr_data)
      qr.make() # Generate the QRCode itself
      #im contains a PIL.Image.Image object
      im = qr.make_image()
      # To save it
      im.save("qr.png")
      #db_session.add(user)
      sendmail(user.email)
      db.session.add(user)
      db.session.commit()

      return render_template('register.html',isreg=True)
   return render_template('register.html', form=form, isreg=False)
def register():

	if request.method == 'POST':
		print 'Username: '******'Username']
		print 'Password: '******'Password']

		# Connect to database
		db = sqlite3.connect('google_authenticator.db')
		cursor = db.cursor()

		# Create secret and add user to database
		secret = base64.b32encode(os.urandom(10)).decode('utf-8')
		query = 'INSERT INTO USERS (USER, PASSWORD, GOOGLEAUTH) VALUES (\"' + request.form['Username'] + '\",\"' + request.form['Password'] + '\",\"' + secret + '\");'
		cursor.execute(query)
		db.commit()
		db.close()

		# Create unique QR code given secret, label, and issuer
		auth = OtpAuth(secret)
		secret_uri = auth.to_uri('totp', GALabel, GAIssuer)
		qr = QRCode()
		qr.add_data(secret_uri)
		qr.make()
		img = qr.make_image()
		#img.show()	# Opens tmp QR code image
		print 'Secret: ', secret
		print 'Secret Uri: ', secret_uri

		# Display QR code in web browser
		return redirect(getQRCodeGoogleUrl(secret_uri))

	return "Nothing to see here."
Ejemplo n.º 6
0
def parse_add(datafile, event_id):
  csvFile=open(datafile)
  fileData = reader(csvFile, delimiter=';', quotechar='|')
  for row in fileData:
    user = User()
    user.first_name=row[0]
    user.last_name=row[1]
    user.email=row[2]
    user.college_name=row[3]
    user.qr_data = sha1(user.email).hexdigest()
    #qr = QRCode(version=10, error_correction=ERROR_CORRECT_H)
    qr = QRCode(
       version=6,
       border=4,
       box_size=5,
       error_correction=ERROR_CORRECT_Q
       )

    qr.add_data(user.qr_data)
    qr.make() # Generate the QRCode itself
    #im contains a PIL.Image.Image object
    im = qr.make_image()
    # To save it
    im.save("qr.png")
    #db_session.add(user)
    sendmail(user.email)
    db.session.add(user)
    db.session.commit()
    eu = EventUsers(event_id,user.id)
    db.session.add(eu)
    db.session.commit()
Ejemplo n.º 7
0
def gen_qrcode(name, data):
    fp = open(name, 'w')
    gen = QRCode()
    gen.add_data(data)
    img = gen.make_image()
    io = StringIO()    
    img.save(fp)
    fp.close()
Ejemplo n.º 8
0
def buildQRRegion():
    qr = QRCode(box_size=1,
                border=1,
                image_factory=LPQRImage)
    qr.add_data(sha256("").hexdigest())
    qr.make()

    img = qr.make_image().get_image()
    return img
Ejemplo n.º 9
0
class X4QRCode(object):
    
    def __init__(self, w, h, message, **kwargs):
        self.qrc = QRCode()#w, h, **kwargs)
        self.qrc.add_data(message)
    
    def getPngImage(self, w, h, fgcol, bgcol):
        
        w = int(w)
        h = int(h)
        
        return self.qrc.make_image()
Ejemplo n.º 10
0
 def get(self):
     
     self.set_header(r'Content-Type', r'image/png')
     
     stream = BytesIO()
     
     code = QRCode()
     
     code.add_data(self.get_argument(r'data', r''))
     
     code.make_image().save(stream)
     
     return self.finish(stream.getvalue())
Ejemplo n.º 11
0
 def GenCode(self,uid):
     data = 'http://'+ServerURL+'/tools/static/query.html?id='+uid
     #print data
     
     from qrcode import QRCode
     from StringIO import StringIO
     gen = QRCode()
     gen.add_data(data)
     img = gen.make_image()
     io = StringIO()
     img.save(io)
     io.seek(0)
     
     #image = QImage()
     self.image.loadFromData(io.read())
Ejemplo n.º 12
0
def getQRCodePage( urlPage ):
	qr = QRCode()
	qr.add_data( urlPage )
	qr.make()
	qrcode = '["' + '",\n"'.join(
		[''.join( '1' if v else '0' for v in qr.modules[row] ) for row in six.moves.range(qr.modules_count)]
	) + '"]'
	
	result = StringIO()
	def w( s ):
		result.write( s )
		result.write( '\n' )
	
	w( '<html>' )
	w( '<head>' )
	w( '''<style type="text/css">
body {
  font-family: sans-serif;
  text-align: center;
  }
</style>''' )
	w( '''<script>
function Draw() {
	var qrcode={qrcode};
	var c = document.getElementById("idqrcode");
	var ctx = c.getContext("2d");
	ctx.fillStyle = '#000';
	var s = Math.floor( c.width / qrcode.length );
	for( var y = 0; y < qrcode.length; ++y ) {
		var row = qrcode[y];
		for( var x = 0; x < row.length; ++x ) {
			if( row.charAt(x) == '1' )
				ctx.fillRect( x*s, y*s, s, s );
		}
	}
}
'''.replace('{qrcode}', qrcode) )
	w( '</script>' )
	w( '</head>' )
	w( '<body onload="Draw();">' )
	w( '<h1 style="margin-top: 32px;">Share Race Results</h1>' )
	w( '<canvas id="idqrcode" width="360" height="360"></canvas>' )
	w( '<h2>Scan the QRCode.<br/>Follow it to the Race Results page.</h2>' )
	w( '<h2>{}</h2>'.format(urlPage) )
	w( 'Powered by <a href="http://www.sites.google.com/site/crossmgrsoftware">CrossMgr</a>.' )
	w( '</body>' )
	w( '</html>' )
	return result.getvalue().encode()
Ejemplo n.º 13
0
    def print_qr(self, data):

        qr = QRCode(version=None,
                    error_correction=ERROR_CORRECT_H,
                    box_size=20
                   )
        qr.add_data(data)

        qr.make(fit=True) # Generate the QRCode itself

        # im contains a PIL.Image.Image object
        im = qr.make_image()
        prntr = Popen(["lp", "-s", "-d%s" % self.printer_name], stdin = PIPE, stdout = None, stderr = None)
        ## To send it to the printer
        im.save(prntr.stdin)
        # wait for process to do its stuff 
        prntr.communicate()
Ejemplo n.º 14
0
 def generate_qrcode(self, product_id="", url='weixin://wxpay/bizpayurl'):
     kwargs = {}
     kwargs.update({
         'appid': self.appid,
         'mch_id': self.mch_id,
         'time_stamp': str(int(time())),
         'nonce_str': uuid4().hex,
         'product_id': product_id,
     })
     kwargs.update({'sign': self.generate_sign(kwargs)})
     scheme, netloc, path, params, query, fragment = urlparse.urlparse(url)
     query = urllib.urlencode(kwargs)
     url = urlparse.urlunparse((scheme, netloc, path,
                                params, query, fragment))
     qr = QRCode(version=1)
     logger.debug(url)
     qr.add_data(url)
     return qr.make_image()
Ejemplo n.º 15
0
def gen_qrcode(filename,qrdata):
    
    fp = open(filename, 'w')
    
    #564be177d52c9e7a68b2c83d
    
    gen = QRCode()
    gen.add_data(qrdata)
    img = gen.make_image()
    io = StringIO()
    #img.save(io)
    img.save(fp)
    
    #img.show()
    #io.seek(0)
    #response = make_response(io.read())
    #response.headers['content-Type'] = 'image/jpeg'
   
    fp.close()
Ejemplo n.º 16
0
def generate_qr_code_response(request):
    user = request.user

    qrcode = QRCode(
        error_correction=ERROR_CORRECT_H,
        box_size=4,
        border=4
    )

    uri = generate_uri('totp', bytes(user.secret), user.email, 'keybar')

    qrcode.add_data(uri)
    qrcode.make(fit=True)
    img = qrcode.make_image()

    stream = io.BytesIO()
    img.save(stream)

    return HttpResponse(stream.getvalue(), content_type='image/png')
Ejemplo n.º 17
0
 def _gen_code_img(data_url, img_seed_name):
     from qrcode import QRCode, constants
     qr = QRCode(
         version=1,
         error_correction=constants.ERROR_CORRECT_L,
         box_size=10,
         border=4,
     )
     
     full_url = "http://" + QRCodeManager.HOST + data_url
     qr.add_data(full_url)
     qr.make(fit=True)
     img = qr.make_image()
     
     img_name = "qrcode_" + img_seed_name + ".png"
     img_path = settings.MEDIA_ROOT + "qrcodes/" + img_name
     img_url = settings.MEDIA_URL + "qrcodes/" + img_name
     
     img.save(img_path, 'PNG')
      
     return img_url
Ejemplo n.º 18
0
def adduser(event_id=1):
   form = RegistrationForm(request.form)
   eventdata = db.session.query(Events).filter_by(id = event_id).all()
   if request.method == 'POST' and form.validate_on_submit():
      #user = User(form.first_name.data, form.last_name.data, form.username.data,
      #            form.username.data, form.email.data, form.enrollment.data,
      #            form.college_name.data)
      user = User()

      form.populate_obj(user)
      #user.password = generate_password_hash(user.password)
      user.qr_data = sha1(user.email).hexdigest()

      #qr = QRCode(version=10, error_correction=ERROR_CORRECT_H)

      qr = QRCode(
         version=6,
         border=4,
         box_size=5,
         error_correction=ERROR_CORRECT_Q
         )

      qr.add_data(user.qr_data)
      qr.make() # Generate the QRCode itself
      #im contains a PIL.Image.Image object
      im = qr.make_image()
      # To save it
      im.save("qr.png")
      #db_session.add(user)
      sendmail(user.email)
      db.session.add(user)
      db.session.commit()
      eu = EventUsers(event_id,user.id)
      db.session.add(eu)
      db.session.commit()
      event_d = db.session.query(Events).filter_by(id = event_id).all()
      cnt = db.session.query(EventUsers).filter_by(event_id = event_id).count()
      return render_template('eventdetails.html', event_id=event_id, eventdata=event_d[0],cnt=cnt)
   return render_template('adduser.html', form=form, isreg=False,event_id=event_id, event=eventdata[0])
Ejemplo n.º 19
0
    def _getAnswer(self):
        config = Config.getInstance()
        checkin_app_client_id = config.getCheckinAppClientId()
        if checkin_app_client_id is None:
            raise NoReportError(_("indico-checkin client_id is not defined in the Indico configuration"))
        checkin_app = OAuthApplication.find_first(client_id=checkin_app_client_id)
        if checkin_app is None:
            raise NoReportError(
                _("indico-checkin is not registered as an OAuth application with client_id {}").format(
                    checkin_app_client_id
                )
            )

        # QRCode (Version 6 with error correction L can contain up to 106 bytes)
        qr = QRCode(version=6, error_correction=constants.ERROR_CORRECT_M, box_size=4, border=1)

        baseURL = config.getBaseSecureURL() if config.getBaseSecureURL() else config.getBaseURL()
        qr_data = {
            "event_id": self._conf.getId(),
            "title": self._conf.getTitle(),
            "date": format_date(self._conf.getAdjustedStartDate()),
            "server": {
                "baseUrl": baseURL,
                "consumerKey": checkin_app.client_id,
                "auth_url": url_for("oauth.oauth_authorize", _external=True),
                "token_url": url_for("oauth.oauth_token", _external=True),
            },
        }
        json_qr_data = json.dumps(qr_data)
        qr.add_data(json_qr_data)
        qr.make(fit=True)
        qr_img = qr.make_image()

        output = StringIO()
        qr_img._img.save(output, format="png")
        im_data = output.getvalue()

        return "data:image/png;base64,{0}".format(base64.b64encode(im_data))
Ejemplo n.º 20
0
def generate(key_type, key, user, issuer, counter=None, **kwargs):
    r"""
    Generate a QR code suitable for Google Authenticator.

    See: https://code.google.com/p/google-authenticator/wiki/KeyUriFormat

    :param str key_type: the auth type, either ``totp`` or ``hotp``
    :param str key: the secret key
    :param str user: the username
    :param str issuer: issuer name
    :param counter: initial counter value (HOTP only)
    :type counter: :func:`int` or :data:`None`
    :param \*\*kwargs: Arguments passed to the :class:`qrcode.QRCode`
                       constructor
    :returns: an image object
    :rtype: :class:`qrcode.image.base.BaseImage`
    """
    qr = QRCode(**kwargs)
    oath_uri = uri.generate(key_type, key, user, issuer, counter)
    qr.add_data(oath_uri)
    if kwargs.get('version') is None:
        qr.make(fit=True)
    return qr.make_image()
Ejemplo n.º 21
0
def generate_ticket_qr_code(registration):
    """Generate a Pillow `Image` with a QR Code encoding a check-in ticket.

    :param registration: corresponding `Registration` object
    """
    qr = QRCode(
        version=17,
        error_correction=constants.ERROR_CORRECT_Q,
        box_size=3,
        border=1
    )
    qr_data = {
        "registrant_id": registration.id,
        "checkin_secret": registration.ticket_uuid,
        "event_id": unicode(registration.event.id),
        "server_url": config.BASE_URL,
        "version": 1
    }
    signals.event.registration.generate_ticket_qr_code.send(registration, ticket_data=qr_data)
    json_qr_data = json.dumps(qr_data)
    qr.add_data(json_qr_data)
    qr.make(fit=True)
    return qr.make_image()._img
Ejemplo n.º 22
0
def create_pdf(name, orderid, ticketid, event, tickettype):
    packet = StringIO.StringIO()
    # create a new PDF with Reportlab
    can = canvas.Canvas(packet)
    qr = QRCode(version=1, error_correction=ERROR_CORRECT_L, box_size=50, border=4, )
    qr.add_data(uuid.uuid4())
    qr.make(fit=True)  # Generate the QRCode itself
    # im contains a PIL.Image.Image object
    im = qr.make_image()
    im.save(os.path.join(settings.PDF_LOCATION, 'qr', "qr" + str(ticketid) + ".jpg"), 'JPEG')
    can.drawImage(os.path.join(settings.PDF_LOCATION, 'qr', 'qr' + str(ticketid) + ".jpg"), 150, 50, 125, 125)
    os.remove(os.path.join(settings.PDF_LOCATION, 'qr', 'qr' + str(ticketid) + ".jpg"))
    terms = Terms.objects.get(id=1).terms
    terms = terms.replace('\r\n', 'SPLIT')
    terms = terms.split("SPLIT")
    x = 150
    for line in terms:
        can.drawString(300, x, line)
        x -= 15
    can.drawString(20, 150, str(name))
    can.drawString(20, 135, "OrderNr: " + str(orderid))
    can.drawString(20, 120, "TicketNr: " + str(ticketid))
    can.drawString(20, 30, "Type: " + str(tickettype))
    can.line(290, 160, 290, 5)
    can.drawString(110, 150, "")
    can.save()
    # move to the beginning of the StringIO buffer
    packet.seek(0)
    new_pdf = PdfFileReader(packet)
    # read your existing PDF
    existing_pdf = PdfFileReader(file(event.template.path, "rb"))
    output = PdfFileWriter()
    # add the "watermark" (which is the new pdf) on the existing page
    page = existing_pdf.getPage(0)
    page.mergePage(new_pdf.getPage(0))
    output.addPage(page)
    return output
Ejemplo n.º 23
0
    def _getAnswer(self):

        consumers = dict((consumer.getName(), consumer) for consumer in ConsumerHolder().getList())

        if "indico-checkin" not in consumers:
            raise NoReportError(_("There is no indico-checkin consumer key for OAuth"))

        # QRCode (Version 6 with error correction L can contain up to 106 bytes)
        qr = QRCode(
            version=6,
            error_correction=constants.ERROR_CORRECT_M,
            box_size=4,
            border=1
        )

        oauth_checkin = consumers["indico-checkin"]
        config = Config.getInstance()
        baseURL = config.getBaseSecureURL() if config.getBaseSecureURL() else config.getBaseURL()
        qr_data = {"event_id": self._conf.getId(),
                   "title": self._conf.getTitle(),
                   "date": format_date(self._conf.getAdjustedStartDate()),
                   "server": {"baseUrl": baseURL,
                              "consumerKey": oauth_checkin.getId(),
                              "consumerSecret": oauth_checkin.getSecret(),
                              }
                   }
        json_qr_data = json.dumps(qr_data)
        qr.add_data(json_qr_data)
        qr.make(fit=True)
        qr_img = qr.make_image()

        output = StringIO()
        qr_img._img.save(output, format="png")
        im_data = output.getvalue()

        return 'data:image/png;base64,{0}'.format(base64.b64encode(im_data))
Ejemplo n.º 24
0
 def _str2qr(self, str):
     qr = QRCode()
     qr.border = 1
     qr.add_data(str)
     mat = qr.get_matrix()
     self._printQR(mat)  # qr.print_tty() or qr.print_ascii()
Ejemplo n.º 25
0
 def make_code(self, code):
     q = QRCode()
     q.add_data(code)
     stream = FakeStream()
     q.print_ascii(stream)
     return self.template % u''.join(stream).replace('\n', self.eol)
Ejemplo n.º 26
0
def qrcode(msg):
    qr = QRCode()
    qr.add_data(msg)
    return qr
Ejemplo n.º 27
0
 def get_qr_code(self) -> Tuple[str, QRCode]:
     content = str(uuid.uuid4())
     qr = QRCode()
     qr.add_data(content)
     return content, qr
Ejemplo n.º 28
0
def qrcode(address):
    qr = QRCode()
    qr.add_data("bitcoin:%s" % (address))
    return qr
Ejemplo n.º 29
0
 def _generate_image(self):
     qr = QRCode(error_correction=ERROR_CORRECT_L)
     qr.add_data(self.url)
     return qr.make_image()
Ejemplo n.º 30
0
    def initialize(self):
        self.logNotify("Initializing LibreSelery")

        self.seleryPackageInfo = os_utils.getPackageInfo("libreselery")
        if self.seleryPackageInfo:
            self.log("LibreSelery version [%s]" %
                     self.seleryPackageInfo["version"])
        else:
            # when project is executed locally without installation, seleryPackageInfo is empty
            self.log("LibreSelery version [undefined]")

        self.log("Preparing Configuration")
        # find all configs in potentially given config directory
        foundConfigs = []
        if self.config.config_dir:
            for root, dirs, files in os.walk(self.config.config_dir):
                for f in files:
                    ext = os.path.splitext(f)[1]
                    if ext == ".yml":
                        foundConfigs.append(os.path.join(root, f))
        # group all found configs together with individually given configuration paths from user on top
        self.config.config_paths = foundConfigs + self.config.config_paths
        # apply yaml config to our configuration if possible
        self.log("Loading configurations" % self.config.config_paths)
        [print(" -- %s" % path) for path in self.config.config_paths]
        [self.loadYaml(path) for path in self.config.config_paths]

        # finalize our configuration settings
        self.config.finalize()

        # load the README file and check if wallet address for donation matches the configured wallet address. Before payout this address is also matched against the address of the coinbase user
        extractor = URLExtract()
        fundingPath = self._getFile("README.md")
        if fundingPath is not None:
            self.log("Loading funding file [%s] for bitcoin wallet" %
                     fundingPath)
            mdfile = open(os.path.join(self.seleryDir, "README.md"), "r")
            mdstring = mdfile.read()
            urls = extractor.find_urls(mdstring)
            badge_string = "https://badgen.net/badge/LibreSelery-Donation/"
            for url in urls:
                if badge_string in url:
                    self.config.bitcoin_address = url.split(badge_string, 1)[1]
                    self.log("Found bitcoin address [%s]" %
                             self.config.bitcoin_address)
        else:
            self.log(
                "Using bitcoin address from configuration file for validation check [%s]"
                % self.config.bitcoin_address)

        # Create a new QR code based on the configured wallet address
        self.log("Creating QR code PNG image for funders")
        wallet_qrcode = QRCode(error_correction=1)
        wallet_qrcode.add_data(self.config.bitcoin_address)
        wallet_qrcode.best_fit()
        wallet_qrcode.makeImpl(False, 6)
        wallet_image = wallet_qrcode.make_image()
        wallet_image.save(
            os.path.join(self.config.result_dir, "public",
                         "wallet_qrcode.png"))

        # load tooling url
        if self.config.include_tooling_and_runtime and self.config.tooling_path:
            with open(self.config.tooling_path) as f:
                self.config.toolrepos = yaml.safe_load(f)
            if self.config.toolrepos is not None:
                self.log("Tooling file loaded [%s]" % self.config.toolrepos)
            else:
                self.log("No tooling urls found")
        else:
            self.log("Tooling not included")

        # load our environment variables
        self.loadEnv()

        self.logNotify("Initialized")
        self.log(str(self.getConfig()))
Ejemplo n.º 31
0
 def qrcode(self):
     qrcode = QRCode(error_correction=self.LEVELS[self.level], version=self.size)
     qrcode.add_data(self.data)
     qrcode.make()
     return qrcode
Ejemplo n.º 32
0
    while True:
        option = input(options)
        try:
            if int(option) == 1:
                connections = api_handler.connections()
                log_msg(f"{json.dumps(connections, indent=4, sort_keys=True)}",
                        color=LOG_COLOR)
                log_msg(f"Total connections:",
                        len(connections["results"]),
                        color=LOG_COLOR)
            elif int(option) == 2:
                invitation_id, invitation = api_handler.create_invitation(
                    alias=alias, multi_use=False, auto_accept=True)
                qr = QRCode(border=1)
                qr.add_data(json.dumps(invitation))
                log_msg(
                    f"Use the following JSON to accept the invite from another demo agent. Or use the QR code to connect from a mobile agent.",
                    color=LOG_COLOR)
                log_msg(f"Invitation Data:",
                        json.dumps(invitation),
                        color=LOG_COLOR)
                qr.print_ascii(invert=True)

            elif int(option) == 3:
                invitation = input("Invite details: ")
                auto_accept = input("Auto accept invitation? n/y: ")
                if auto_accept == "y":
                    auto_accept = True
                else:
                    auto_accept = False
Ejemplo n.º 33
0
def qrcode(msg):
    qr = QRCode()
    qr.add_data(msg)
    return qr
Ejemplo n.º 34
0
async def main(
    start_port: int,
    no_auto: bool = False,
    revocation: bool = False,
    tails_server_base_url: str = None,
    show_timing: bool = False,
):

    genesis = await default_genesis_txns()
    if not genesis:
        print("Error retrieving ledger genesis transactions")
        sys.exit(1)

    agent = None

    try:
        log_status(
            "#1 Provision an agent and wallet, get back configuration details")
        agent = FaberAgent(
            start_port,
            start_port + 1,
            genesis_data=genesis,
            no_auto=no_auto,
            tails_server_base_url=tails_server_base_url,
            timing=show_timing,
        )
        await agent.listen_webhooks(start_port + 2)
        await agent.register_did()

        with log_timer("Startup duration:"):
            await agent.start_process()
        log_msg("Admin URL is at:", agent.admin_url)
        log_msg("Endpoint URL is at:", agent.endpoint)

        # Create a schema
        with log_timer("Publish schema/cred def duration:"):
            log_status("#3/4 Create a new schema/cred def on the ledger")
            version = format("%d.%d.%d" % (
                random.randint(1, 101),
                random.randint(1, 101),
                random.randint(1, 101),
            ))
            (
                _,  # schema id
                credential_definition_id,
            ) = await agent.register_schema_and_creddef(
                "degree schema",
                version,
                ["name", "date", "degree", "age", "timestamp"],
                support_revocation=revocation,
                revocation_registry_size=TAILS_FILE_COUNT,
            )

        # TODO add an additional credential for Student ID

        with log_timer("Generate invitation duration:"):
            # Generate an invitation
            log_status(
                "#7 Create a connection to alice and print out the invite details"
            )
            connection = await agent.admin_POST(
                "/connections/create-invitation")

        agent.connection_id = connection["connection_id"]

        qr = QRCode()
        qr.add_data(connection["invitation_url"])
        log_msg(
            "Use the following JSON to accept the invite from another demo agent."
            " Or use the QR code to connect from a mobile agent.")
        log_msg(json.dumps(connection["invitation"]),
                label="Invitation Data:",
                color=None)
        qr.print_ascii(invert=True)

        log_msg("Waiting for connection...")
        await agent.detect_connection()

        exchange_tracing = False
        options = ("    (1) Issue Credential\n"
                   "    (2) Send Proof Request\n"
                   "    (3) Send Message\n")
        if revocation:
            options += "    (4) Revoke Credential\n" "    (5) Publish Revocations\n"
        options += "    (T) Toggle tracing on credential/proof exchange\n"
        options += "    (X) Exit?\n[1/2/3/{}T/X] ".format(
            "4/5/6/" if revocation else "")
        async for option in prompt_loop(options):
            if option is not None:
                option = option.strip()

            if option is None or option in "xX":
                break

            elif option in "tT":
                exchange_tracing = not exchange_tracing
                log_msg(">>> Credential/Proof Exchange Tracing is {}".format(
                    "ON" if exchange_tracing else "OFF"))
            elif option == "1":
                log_status("#13 Issue credential offer to X")

                # TODO define attributes to send for credential
                agent.cred_attrs[credential_definition_id] = {
                    "name": "Alice Smith",
                    "date": "2018-05-28",
                    "degree": "Maths",
                    "age": "24",
                    "timestamp": str(int(time.time())),
                }

                cred_preview = {
                    "@type":
                    CRED_PREVIEW_TYPE,
                    "attributes":
                    [{
                        "name": n,
                        "value": v
                    } for (n, v) in
                     agent.cred_attrs[credential_definition_id].items()],
                }
                offer_request = {
                    "connection_id": agent.connection_id,
                    "cred_def_id": credential_definition_id,
                    "comment":
                    f"Offer on cred def id {credential_definition_id}",
                    "auto_remove": False,
                    "credential_preview": cred_preview,
                    "trace": exchange_tracing,
                }
                await agent.admin_POST("/issue-credential/send-offer",
                                       offer_request)
                # TODO issue an additional credential for Student ID

            elif option == "2":
                log_status("#20 Request proof of degree from alice")
                req_attrs = [
                    {
                        "name": "name",
                        "restrictions": [{
                            "issuer_did": agent.did
                        }]
                    },
                    {
                        "name": "date",
                        "restrictions": [{
                            "issuer_did": agent.did
                        }]
                    },
                ]
                if revocation:
                    req_attrs.append(
                        {
                            "name": "degree",
                            "restrictions": [{
                                "issuer_did": agent.did
                            }],
                            "non_revoked": {
                                "to": int(time.time() - 1)
                            },
                        }, )
                else:
                    req_attrs.append({
                        "name":
                        "degree",
                        "restrictions": [{
                            "issuer_did": agent.did
                        }]
                    })
                if SELF_ATTESTED:
                    # test self-attested claims
                    req_attrs.append({"name": "self_attested_thing"}, )
                req_preds = [
                    # test zero-knowledge proofs
                    {
                        "name": "age",
                        "p_type": ">=",
                        "p_value": 18,
                        "restrictions": [{
                            "issuer_did": agent.did
                        }],
                    }
                ]
                indy_proof_request = {
                    "name": "Proof of Education",
                    "version": "1.0",
                    "requested_attributes": {
                        f"0_{req_attr['name']}_uuid": req_attr
                        for req_attr in req_attrs
                    },
                    "requested_predicates": {
                        f"0_{req_pred['name']}_GE_uuid": req_pred
                        for req_pred in req_preds
                    },
                }

                if revocation:
                    indy_proof_request["non_revoked"] = {
                        "to": int(time.time())
                    }
                proof_request_web_request = {
                    "connection_id": agent.connection_id,
                    "proof_request": indy_proof_request,
                    "trace": exchange_tracing,
                }
                await agent.admin_POST("/present-proof/send-request",
                                       proof_request_web_request)

            elif option == "3":
                msg = await prompt("Enter message: ")
                await agent.admin_POST(
                    f"/connections/{agent.connection_id}/send-message",
                    {"content": msg})
            elif option == "4" and revocation:
                rev_reg_id = (
                    await prompt("Enter revocation registry ID: ")).strip()
                cred_rev_id = (
                    await prompt("Enter credential revocation ID: ")).strip()
                publish = json.dumps(
                    (await prompt("Publish now? [Y/N]: ", default="N")
                     ).strip() in ("yY"))
                try:
                    await agent.admin_POST("/issue-credential/revoke"
                                           f"?publish={publish}"
                                           f"&rev_reg_id={rev_reg_id}"
                                           f"&cred_rev_id={cred_rev_id}")
                except ClientError:
                    pass
            elif option == "5" and revocation:
                try:
                    resp = await agent.admin_POST(
                        "/issue-credential/publish-revocations", {})
                    agent.log(
                        "Published revocations for {} revocation registr{} {}".
                        format(
                            len(resp["rrid2crid"]),
                            "y" if len(resp) == 1 else "ies",
                            json.dumps([k for k in resp["rrid2crid"]],
                                       indent=4),
                        ))
                except ClientError:
                    pass

        if show_timing:
            timing = await agent.fetch_timing()
            if timing:
                for line in agent.format_timing(timing):
                    log_msg(line)

    finally:
        terminated = True
        try:
            if agent:
                await agent.terminate()
        except Exception:
            LOGGER.exception("Error terminating agent:")
            terminated = False

    await asyncio.sleep(0.1)

    if not terminated:
        os._exit(1)
Ejemplo n.º 35
0
def generate_qr_as_pil_image(data):
    qr = QRCode(error_correction=ERROR_CORRECT_L, box_size=5, border=1)
    qr.add_data(data)
    qr.make()
    return qr.make_image()
    async def make_agent_POST_request(
        self,
        command: BackchannelCommand,
    ) -> Tuple[int, str]:
        print("make_agent_POST_request:", command)

        operation = command.operation
        data = command.data
        record_id = command.record_id

        if command.topic == "connection":
            if operation == "receive-invitation":
                self.connection_state = "invited"
                print(
                    "================================================================="
                )

                message_bytes = json.dumps(data).encode("ascii")
                base64_bytes = base64.b64encode(message_bytes)
                base64_message = base64_bytes.decode("ascii")
                invitation_url = data["serviceEndpoint"] + "?c_i=" + base64_message

                qr = QRCode(border=1)
                qr.add_data(invitation_url)
                log_msg(
                    "Use the following JSON to accept the invite from another demo agent."
                    " Or use the QR code to connect from a mobile agent."
                )
                log_msg(json.dumps(data), label="Invitation Data:", color=None)
                qr.print_ascii(invert=True)
                log_msg("If you can't scan the QR code here is the url.")
                print("Invitation url:", invitation_url)
                print(
                    "================================================================="
                )

                return (
                    200,
                    json.dumps(
                        {
                            "result": "ok",
                            "connection_id": "1",
                            "state": self.connection_state,
                        }
                    ),
                )

            elif (
                operation == "accept-invitation"
                or operation == "accept-request"
                or operation == "remove"
                or operation == "start-introduction"
                or operation == "send-ping"
            ):
                self.connection_state = "requested"
                return (
                    200,
                    json.dumps(
                        {
                            "result": "ok",
                            "connection_id": "1",
                            "state": self.connection_state,
                        }
                    ),
                )

        elif command.topic == "issue-credential":
            if operation == "send-request":
                print(
                    "================================================================="
                )
                print("Please respond to the Credential Offer!")
                print(
                    "================================================================="
                )
                return (
                    200,
                    '{"result": "ok", "thread_id": "1", "state": "request-sent"}',
                )
            elif operation == "store":
                return (
                    200,
                    json.dumps(
                        {
                            "result": "ok",
                            "thread_id": "1",
                            "credential_id": record_id,
                            "state": "done",
                        }
                    ),
                )
            else:
                return (200, '{"result": "ok", "thread_id": "1", "state": "N/A"}')

        elif command.topic == "proof":
            if operation == "send-presentation":
                print(
                    "================================================================="
                )
                print("Please respond to the Proof Request!")
                print(
                    "================================================================="
                )
                return (
                    200,
                    '{"result": "ok", "thread_id": "1", "state": "presentation-sent"}',
                )
            else:
                return (200, '{"result": "ok", "thread_id": "1", "state": "N/A"}')

        return (501, "501: Not Implemented\n\n")