Ejemplo n.º 1
0
def data(mode):
    """
	#@app.route('/data/', methods=['GET'])
	"""
    check_login()
    try:
        dataId = request.args['dataId']
        workspace_contract = '0x' + dataId.split(':')[3]
    except:
        logging.error('data request malformed')
        return redirect(mode.server + 'user/')

    doc_id = int(dataId.split(':')[5])
    my_data = Document(dataId.split(':')[6])
    if not my_data.relay_get(workspace_contract, doc_id, mode):
        logging.error('document does not exist')
        return redirect(mode.server + 'user/')

    # advanced information about storage location
    (location, link) = (my_data.data_location, my_data.data_location)
    myadvanced = """<b>Data storage</b> : <a class="card-link" href=""" + link + """>""" + location + """</a>"""

    # Display raw verifiable credential
    credential = Document('certificate')
    credential.relay_get_credential(session['workspace_contract'], doc_id,
                                    mode)
    credential_text = json.dumps(credential.__dict__,
                                 sort_keys=True,
                                 indent=4,
                                 ensure_ascii=False)
    return render_template('data_check.html',
                           **session['menu'],
                           verif=myadvanced,
                           credential=credential_text)
Ejemplo n.º 2
0
def certificate_verify(mode) :
	"""		 verify credential data and did

	app.route('/certificate/verify/, methods=['GET']

	"""
	menu = session.get('menu', dict())
	viewer = 'guest' if not session.get('username') else 'user'

	try :
		certificate_id = request.args['certificate_id']
		identity_workspace_contract = '0x'+ certificate_id.split(':')[3]
		credential = Document('certificate')
		doc_id = int(certificate_id.split(':')[5])
		credential.relay_get_credential(identity_workspace_contract, doc_id, mode, loading = 'full')
		credential_text = json.dumps(credential.__dict__, sort_keys=True, indent=4, ensure_ascii=False)
	except :
		logging.error('data not found')
		return jsonify ({'result' : 'certificate not found'})

	# Issuer , Referent
	issuer = """<b>Issuer DID</b> : """ + credential.issuer
	#print(json.dumps(json.loads(didkit.resolveDID(credential.issuer, '{}')), indent=4))

	# User, holder
	user = """<b>User DID</b> : """ + credential.credentialSubject['id']
	#print(json.dumps(json.loads(didkit.resolveDID(credential.credentialSubject['id'], '{}')), indent=4))

	my_verif = "".join([issuer, "<br>", user, '<br>'])

	return render_template('./certificate/verify_certificate.html',
							**menu,
							certificate_id=certificate_id,
							topic = "",
							credential = credential_text,
							verif=my_verif,
							viewer=viewer,
							)
Ejemplo n.º 3
0
def issue_credential_workflow(mode):
    """
    @route /company/issue_credential_workflow/?id=xxxx
    call = (created, user_name, reviewer_name, issuer_name, status, credential, id)
    update = update_verifiable_credential(id, host_name, reviewer_username, issuer_username, status, credential, mode)
    """
    if request.method == 'GET':
        session['credential_id'] = request.args['id']
        credential = company.Credential(session['host'], mode)
        session['call'] = credential.get_by_id(session['credential_id'])

        # credential cannot be updated if already signed
        field = "disabled" if session['call'][4] == 'signed' or session[
            'role'] in ['admin', 'creator'] else ""

        # credential is loaded  as dict
        my_credential = json.loads(session['call'][5])['credentialSubject']

        if my_credential["credentialCategory"] != 'experience':
            flash('view not yet available', 'warning')
            return redirect(mode.server + 'company/dashboard/')

        skills_str = ""
        for skill in my_credential['skills']:
            skills_str += skill['description'] + ','
        return render_template(
            './issuer/issue_experience_credential_workflow.html',
            credential_id=request.args['id'],
            picturefile=session['picture'],
            clipboard=mode.server + "board/?did=" + session['did'],
            **my_credential,
            scoreRecommendation=my_credential["reviewRecommendation"]
            ["reviewRating"]["ratingValue"],
            questionRecommendation=my_credential["reviewRecommendation"]
            ["reviewBody"],
            scoreSchedule=my_credential["reviewSchedule"]["reviewRating"]
            ["ratingValue"],
            questionSchedule=my_credential["reviewSchedule"]["reviewBody"],
            scoreCommunication=my_credential["reviewCommunication"]
            ["reviewRating"]["ratingValue"],
            questionCommunication=my_credential["reviewCommunication"]
            ["reviewBody"],
            scoreDelivery=my_credential["reviewDelivery"]["reviewRating"]
            ["ratingValue"],
            questionDelivery=my_credential["reviewDelivery"]["reviewBody"],
            skills_str=skills_str,
            field=field,
        )

    if request.method == 'POST':
        # credential is removed from database
        if request.form['exit'] == 'delete':
            credential = company.Credential(session['host'], mode)
            credential.delete(session['credential_id'])
            del session['credential_id']
            del session['call']
            return redirect(mode.server + 'company/dashboard/')

        # nothing is done
        if request.form['exit'] == 'back':
            del session['credential_id']
            del session['call']
            return redirect(mode.server + 'company/dashboard/')

        # get form data to update credential
        my_credential = json.loads(session['call'][5])
        get_form_data(my_credential, request.form)

        # update without review and signature
        if request.form.get('exit') == 'update':
            credential = company.Credential(session['host'], mode)
            credential.update(
                session['credential_id'],
                session['call'][2],
                session['call'][3],
                session['call'][4],
                json.dumps(my_credential),
            )

        # credential has been signed by issuer
        elif request.form.get('exit') == 'sign':
            # sign credential with company key
            manager_workspace_contract = ns.get_data_from_username(
                session['username'], mode)['identity_workspace_contract']
            my_credential['credentialSubject'][
                'managerSignature'] = json.loads(
                    ns.get_personal(manager_workspace_contract,
                                    mode))['signature']
            my_credential["issuanceDate"] = datetime.utcnow().replace(
                microsecond=0).isoformat() + "Z"
            my_credential['issuer'] = ns.get_did(session['workspace_contract'],
                                                 mode)
            signed_credential = vc_signature.sign(my_credential,
                                                  session['private_key_value'],
                                                  my_credential['issuer'])
            if not signed_credential:
                flash('Operation failed ', 'danger')
                logging.error('credential signature failed')
                del session['credential_id']
                del session['call']
                return redirect(mode.server + 'company/dashboard/')

            # update local company database
            credential = company.Credential(session['host'], mode)
            credential.update(
                session['credential_id'],
                session['call'][2],
                session['employee'],
                "signed",
                signed_credential,
            )

            # ulpoad credential to repository with company key signature
            subject_username = session['call'][1]
            subject = ns.get_data_from_username(subject_username, mode)
            my_certificate = Document('certificate')
            doc_id = my_certificate.add(session['address'],
                                        session['workspace_contract'],
                                        subject['address'],
                                        subject['workspace_contract'],
                                        session['private_key_value'],
                                        json.loads(signed_credential),
                                        mode,
                                        privacy='public',
                                        synchronous=False)[0]
            if not doc_id:
                flash('Operation failed ', 'danger')
                logging.error('certificate to repository failed')
            else:
                flash('The credential has been added to the user repository',
                      'success')
            """
            # send an email to user
            link = mode.server + 'guest/certificate/?certificate_id=did:talao:' + mode.BLOCKCHAIN + ':' + subject['workspace_contract'][2:] + ':document:' + str(doc_id)
            try :
                Talao_message.messageHTML('Your professional credential has been issued.', subject['email'], 'certificate_issued', {'username': session['name'], 'link': link}, mode)
            except :
                logging.error('email to subject failed')
            """
            # store signed credential on server
            try:
                filename = session['credential_id'] + '_credential.jsonld'
                path = "./signed_credentials/"
                with open(path + filename, 'w') as outfile:
                    json.dump(json.loads(signed_credential),
                              outfile,
                              indent=4,
                              ensure_ascii=False)
            except:
                logging.error('signed credential not stored')

            # send email to user
            try:
                signature = '\r\n\r\n\r\n\r\nThe Talao team.\r\nhttps://talao.io/'
                text = "\r\nHello\r\nYou will find attached your professional credential signed by your issuer." + signature
                Talao_message.message_file(subject['email'], text,
                                           "Your professional credential",
                                           [filename], path, mode)
            except:
                logging.error('email credential to subject failed')

        # credential has been reviewed
        elif request.form['exit'] == 'validate':
            # update local database
            credential = company.Credential(session['host'], mode)
            credential.update(
                session['credential_id'],
                session['employee'],
                session['call'][3],
                "reviewed",
                json.dumps(my_credential, ensure_ascii=False),
            )
            # send an email to issuer to go forward
            issuer_email = ns.get_data_from_username(
                session['referent'] + '.' + session['host'], mode)['email']
            subject_name = my_credential['credentialSubject']['name']
            subject = 'You have received a professional credential from ' + subject_name + ' to issue'
            try:
                Talao_message.messageHTML(subject, issuer_email,
                                          'request_certificate', {
                                              'name': subject_name,
                                              'link': 'https://talao.co'
                                          }, mode)
            except:
                logging.error('email error')

            flash('Credential has been reviewed and validated', 'success')

        # all exits except delete and back
        del session['credential_id']
        del session['call']
        return redirect(mode.server + 'company/dashboard/')
Ejemplo n.º 4
0
def show_certificate(mode):
	"""
	# display experience certificate for anybody. Stand alone routine
	# #route /guest/certificate
	# @route /certificate/
	"""
	menu = session.get('menu', dict())
	viewer = 'guest' if not session.get('username') else 'user'

	try  :
		certificate_id = request.args['certificate_id']
		method = certificate_id.split(':')[1]

		# translator for repository claim
		if method in ['web', 'tz', 'ethr'] :
			did = 'did:' + method + ':' + certificate_id.split(':')[2]
			private_key = '0x' + PBKDF2(did.encode(), SALT, 32, count=1000000, hmac_hash_module=SHA512).hex()
			address = helpers.ethereum_pvk_to_address(private_key)
			workspace_contract = ownersToContracts(address, mode)
			claim_id = certificate_id.split(':')[4]
			credential = Claim()
			credential.get_by_id( mode.relay_workspace_contract, None, workspace_contract, claim_id, mode)
			return jsonify(credential.claim_value)

		# standard
		elif method == 'talao' :
			try :
				doc_id = int(certificate_id.split(':')[5])
				identity_workspace_contract = '0x'+ certificate_id.split(':')[3]
			except :
				content = json.dumps({'message' : 'request malformed'})
				return Response(content, status=406, mimetype='application/json')
		else :
			content = json.dumps({'message' : 'method not supported'})
			return Response(content, status=406, mimetype='application/json')

	except :
		content = json.dumps({'message' : 'request malformed'})
		return Response(content, status=406, mimetype='application/json')

	try :
		self_claim = certificate_id.split(':')[6]
	except:
		self_claim = None

	if session.get('certificate_id') != request.args['certificate_id'] :
		certificate = Document('certificate')
		if not certificate.relay_get(identity_workspace_contract, doc_id, mode) :
			content = json.dumps({'message' : 'This credential does not exist or it has been deleted'})
			return Response(content, status=406, mimetype='application/json')
		if certificate.privacy != 'public' :
			content = json.dumps({'message' : 'This credential is private'})
			return Response(content, status=406, mimetype='application/json')
		session['displayed_certificate'] = certificate.__dict__

	if self_claim == "experience" :
		description = session['displayed_certificate']['description'].replace('\r\n','<br>')

		my_badge = ''
		for skill in session['displayed_certificate']['skills'] :
			skill_to_display = skill.replace(" ", "").capitalize().strip(',')
			my_badge +=  """<span class="badge badge-pill badge-secondary" style="margin: 4px; padding: 8px;"> """+ skill_to_display + """</span>"""
		return render_template('./certificate/self_claim.html',
							**menu,
							type = 'Experience',
							certificate_id= certificate_id,
							company = session['displayed_certificate']['company']['name'],
							email = session['displayed_certificate']['company']['contact_email'],
							tel = session['displayed_certificate']['company']['contact_phone'],
							contact_name = session['displayed_certificate']['company']['contact_name'],
							start_date = session['displayed_certificate']['start_date'],
							end_date = session['displayed_certificate']['end_date'],
							description = description,
							badge = my_badge,
							viewer=viewer,
							title = session['displayed_certificate']['title'],
							)

	if self_claim == "skills" :
		description = ""
		print (session['displayed_certificate'])
		for skill in session['displayed_certificate']['description'] :
			description += skill["skill_name"] + " "
		return render_template('./certificate/self_claim.html',
							**menu,
							type = 'Skill',
							certificate_id= certificate_id,
							description = description,
							viewer=viewer,
							)

	if self_claim == "education" :
		description = session['displayed_certificate']['description'].replace('\r\n','<br>')

		my_badge = ''
		for skill in session['displayed_certificate']['skills'] :
			skill_to_display = skill.replace(" ", "").strip(',')
			if skill_to_display :
				my_badge = my_badge + """<span class="badge badge-pill badge-secondary" style="margin: 4px; padding: 8px;"> """+ skill_to_display.capitalize() + """</span>"""
		return render_template('./certificate/self_claim.html',
							**menu,
							type = 'Education',
							certificate_id= certificate_id,
							company = session['displayed_certificate']['organization']['name'],
							email = session['displayed_certificate']['organization']['contact_email'],
							tel = session['displayed_certificate']['organization']['contact_phone'],
							contact_name = session['displayed_certificate']['organization']['contact_name'],
							start_date = session['displayed_certificate']['start_date'],
							end_date = session['displayed_certificate']['end_date'],
							description = description,
							badge = my_badge,
							viewer=viewer,
							title = session['displayed_certificate']['title'],
							link = session['displayed_certificate']['certificate_link']
							)

	# Experience Credential Display
	if session['displayed_certificate']['credentialSubject']['credentialCategory'] == 'experience' :
		yellow_star = "color: rgb(251,211,5); font-size: 12px;" # yellow
		black_star = "color: rgb(0,0,0);font-size: 12px;" # black

		# Icon "fa-star" treatment
		score = []
		context = dict()
		score.append(int(session['displayed_certificate']['credentialSubject']['reviewRecommendation']['reviewRating']['ratingValue']))
		score.append(int(session['displayed_certificate']['credentialSubject']['reviewDelivery']['reviewRating']['ratingValue']))
		score.append(int(session['displayed_certificate']['credentialSubject']['reviewSchedule']['reviewRating']['ratingValue']))
		score.append(int(session['displayed_certificate']['credentialSubject']['reviewCommunication']['reviewRating']['ratingValue']))
		for q in range(0,4) :
			for i in range(0,score[q]) :
				context["star"+str(q)+str(i)] = yellow_star
			for i in range(score[q],5) :
				context ["star"+str(q)+str(i)] = black_star

		if session['displayed_certificate']['credentialSubject']['skills'] :
			skills = session['displayed_certificate']['credentialSubject']['skills']
			my_badge = ""
			for skill in skills :
				if skill['description'] :
					my_badge += """<span class="badge badge-pill badge-secondary" style="margin: 4px; padding: 8px;"> """+ skill['description'].strip(' ').capitalize() + """</span>"""
		else :
			my_badge = ""

		# if there is no signature one uses Picasso signature
		signature = session['displayed_certificate']['credentialSubject']['managerSignature']
		if not signature :
			signature = 'QmS9TTtjw1Fr5oHkbW8gcU7TnnmDvnFVUxYP9BF36kgV7u'

		# if there is no logo one uses default logo
		logo = session['displayed_certificate']['credentialSubject']['companyLogo']
		if not logo  :
			logo = 'QmXKeAgNZhLibNjYJFHCiXFvGhqsqNV2sJCggzGxnxyhJ5'

		# upload signature and logo on server
		if not path.exists(mode.uploads_path + signature) :
			url = 'https://gateway.pinata.cloud/ipfs/'+ signature
			response = requests.get(url, stream=True)
			with open(mode.uploads_path + signature, 'wb') as out_file:
				shutil.copyfileobj(response.raw, out_file)
			del response

		if not path.exists(mode.uploads_path + logo) :
			url = 'https://gateway.pinata.cloud/ipfs/'+ logo
			response = requests.get(url, stream=True)
			with open(mode.uploads_path + logo, 'wb') as out_file:
				shutil.copyfileobj(response.raw, out_file)
			del response

		return render_template('./certificate/experience_certificate.html',
							**menu,
							managerName=session['displayed_certificate']['credentialSubject']['managerName'],
							companyName=session['displayed_certificate']['credentialSubject']['companyName'],
							badge=my_badge,
							title = session['displayed_certificate']['credentialSubject']['title'],
							subject_name = session['displayed_certificate']['credentialSubject']['name'],
							description=session['displayed_certificate']['credentialSubject']['description'],
							start_date=session['displayed_certificate']['credentialSubject']['startDate'],
							end_date=session['displayed_certificate']['credentialSubject']['endDate'],
							signature=signature,
							logo=logo,
							certificate_id=certificate_id,
							viewer=viewer,
							**context)

	# Recommendation Certificate Display
	if session['displayed_certificate']['type'] == 'recommendation' :
		issuer_picture = session['displayed_certificate'].get('logo')
		if session['displayed_certificate']['issuer']['category'] == 1001 :
			issuer_picture = session['displayed_certificate'].get('picture')
		else :
			issuer_picture = session['displayed_certificate'].get('logo')

		issuer_title = "" if not session['displayed_certificate'].get('title')  else session['displayed_certificate']['title']
		if issuer_picture  :
			if not path.exists(mode.uploads_path + issuer_picture) :
				logging.info('picture already on disk')
				url='https://gateway.pinata.cloud/ipfs/'+ issuer_picture
				response = requests.get(url, stream=True)
				with open(mode.uploads_path + issuer_picture, 'wb') as out_file:
					shutil.copyfileobj(response.raw, out_file)
				del response

		description = """ " """ + session['displayed_certificate']['description'] + """ " """
		return render_template('./certificate/recommendation_certificate.html',
							**menu,
							#identity_firstname=identity_profil['firstname'],
							#identity_lastname=identity_profil['lastname'],
							description=description,
							issuer_picture=issuer_picture,
							issuer_title=issuer_title,
							issuer_firstname=session['displayed_certificate']['issuer']['firstname'] if session['displayed_certificate']['issuer']['category']== 1001 else "",
							issuer_lastname=session['displayed_certificate']['issuer']['lastname']if session['displayed_certificate']['issuer']['category']== 1001 else "",
							relationship=session['displayed_certificate']['relationship'],
							certificate_id=certificate_id,
							#identity_username=identity_username,
							#issuer_username=issuer_username,
							viewer=viewer
							)

	# Skill Certificate Display
	if session['displayed_certificate']['type'] == 'skill' :
		issuer_picture = session['displayed_certificate'].get('picture')
		issuer_title = "" if not session['displayed_certificate'].get('title') else session['displayed_certificate']['title']

		description = session['displayed_certificate']['description'].replace('\r\n','<br>')

		signature = session['displayed_certificate']['signature']
		logo = session['displayed_certificate']['logo']
		# if there is no signature one uses Picasso signature
		if not signature  :
			signature = 'QmS9TTtjw1Fr5oHkbW8gcU7TnnmDvnFVUxYP9BF36kgV7u'
		# if there is no logo one uses default logo
		if not logo  :
			logo = 'QmXKeAgNZhLibNjYJFHCiXFvGhqsqNV2sJCggzGxnxyhJ5'

		if not path.exists(mode.uploads_path + signature) :
				url = 'https://gateway.pinata.cloud/ipfs/'+ signature
				response = requests.get(url, stream=True)
				with open(mode.uploads_path + signature, 'wb') as out_file:
					shutil.copyfileobj(response.raw, out_file)
				del response

		if not path.exists(mode.uploads_path + logo) :
			url = 'https://gateway.pinata.cloud/ipfs/'+ logo
			response = requests.get(url, stream=True)
			with open(mode.uploads_path + logo, 'wb') as out_file:
				shutil.copyfileobj(response.raw, out_file)
			del response

		return render_template('./certificate/skill_certificate.html',
							**menu,
							manager= session['displayed_certificate']['manager'],
							#identity_firstname=identity_profil['firstname'],
							#identity_lastname=identity_profil['lastname'],
							#identity_name =identity_profil['firstname'] + ' ' + identity_profil['lastname'],
							description=description,
							issuer_picture=issuer_picture,
							signature=signature,
							logo=logo,
							certificate_id=certificate_id,
							title=session['displayed_certificate']['title'],
							#issuer_name=session['displayed_certificate']['issuer']['name'],
							viewer=viewer
							)
	# agreement certificate display
	if session['displayed_certificate']['type'] == 'agreement':
		description = session['displayed_certificate']['description'].replace('\r\n','<br>')

		signature = session['displayed_certificate']['issued_by'].get('signature')
		logo = session['displayed_certificate']['issued_by'].get('logo')

		# if there is no signature or no logo , view is reduced see html else we download file rom ipfs if needed
		if signature and logo :
			if not path.exists(mode.uploads_path + signature) :
				url = 'https://gateway.pinata.cloud/ipfs/'+ signature
				response = requests.get(url, stream=True)
				with open(mode.uploads_path + signature, 'wb') as out_file:
					shutil.copyfileobj(response.raw, out_file)
				del response

			if not path.exists(mode.uploads_path + logo) :
				url = 'https://gateway.pinata.cloud/ipfs/'+ logo
				response = requests.get(url, stream=True)
				with open(mode.uploads_path + logo, 'wb') as out_file:
					shutil.copyfileobj(response.raw, out_file)
				del response

		if session['displayed_certificate']['service_product_group'] :
			products = session['displayed_certificate']['service_product_group'].replace(' ', '').split(",")
			service_product_group = ""
			for product in products:
				service_product_group = service_product_group + """<li class="text-dark my-2 mx-5">""" + product.capitalize() + "</li>"
		else :
			service_product_group = None

		return render_template('./certificate/agreement_certificate.html',
							**menu,
							date_of_issue = session['displayed_certificate']['date_of_issue'],
							date_of_validity = session['displayed_certificate']['valid_until'],
							location = session['displayed_certificate']['location'],
							description=description,
							logo=logo,
							issued_to_name = session['displayed_certificate']['issued_to'].get('name', ''),
							issuer_name = session['displayed_certificate']['issued_by'].get('name',''),
							issuer_siret = session['displayed_certificate']['issued_by'].get('siret', ''),
							title = session['displayed_certificate']['title'],
							signature=signature,
							viewer=viewer,
							standard=session['displayed_certificate']['standard'],
							registration_number = session['displayed_certificate']['registration_number'],
							service_product_group = service_product_group,
							certificate_id=certificate_id,
							)

	# if reference credential display
	if session['displayed_certificate']['credentialSubject']['credentialCategory'] == 'reference' :
		yellow_star = "color: rgb(251,211,5); font-size: 12px;" # yellow
		black_star = "color: rgb(0,0,0);font-size: 12px;" # black

		description = session['displayed_certificate'].get('description','Unknown').replace('\r\n','<br>')

		signature = session['displayed_certificate']['credentialSubject']['managerSignature']
		logo = session['displayed_certificate']['credentialSubject']['companyLogo']

		if signature and logo :
			if not path.exists(mode.uploads_path + signature) :
				url = 'https://gateway.pinata.cloud/ipfs/'+ signature
				response = requests.get(url, stream=True)
				with open(mode.uploads_path + signature, 'wb') as out_file:
					shutil.copyfileobj(response.raw, out_file)
				del response

			if not path.exists(mode.uploads_path + logo) :
				url = 'https://gateway.pinata.cloud/ipfs/'+ logo
				response = requests.get(url, stream=True)
				with open(mode.uploads_path + logo, 'wb') as out_file:
					shutil.copyfileobj(response.raw, out_file)
				del response
		skills_str = ""
		try :
			for skill in session['displayed_certificate']['credentialSubject']['offers']['skills'] :
				skills_str += skill['description'] + ','
		except :
			logging.warning('skills not found')
		return render_template('./certificate/reference_certificate.html',
							**menu,
							issued_to_name = session['displayed_certificate']['credentialSubject']['name'],
							issuanceDate = session['displayed_certificate']['issuanceDate'][:10],
							startDate = session['displayed_certificate']['credentialSubject']['offers']['startDate'],
							endDate = session['displayed_certificate']['credentialSubject']['offers']['endDate'],
							price = session['displayed_certificate']['credentialSubject']['offers']['price'],
							currency = session['displayed_certificate']['credentialSubject']['offers']['priceCurrency'],
							description=session['displayed_certificate']['credentialSubject']['offers']['description'],
							review= session['displayed_certificate']['credentialSubject']['review']['reviewBody'],
							location=session['displayed_certificate']['credentialSubject']['offers']['location'],
							logo=logo,
							issuer_name = session['displayed_certificate']['credentialSubject']['companyName'],
							title = session['displayed_certificate']['credentialSubject']['offers']['title'],
							signature=signature,
							manager = session['displayed_certificate']['credentialSubject']['companyName'],
							certificate_id=certificate_id,
							viewer=viewer,
							skills=skills_str
							)

	else :
		# clean up to get a standard credential
		del session['displayed_certificate']['topic']
		del session['displayed_certificate']['doc_id']
		del session['displayed_certificate']['data_location']
		del session['displayed_certificate']['privacy']
		return jsonify(session['displayed_certificate'])
Ejemplo n.º 5
0
def update_skills(mode):
    check_login()
    if request.method == 'GET':
        if session['skills']:
            skills = session['skills']['description']
            #description = [{'skill_code' : 'consulting' ,'skill_name' : 'consulting', 'skill_level' : 'intermediate', 'skill_domain' : 'industry'},]
            skills_row = ""
            for counter, skill in enumerate(skills, 0):
                #skill_level = 'Intermed.' if skill['skill_level'] == 'Intermediate' else skill['skill_level']
                skill_level = skill['skill_level']
                form_row = """
					<div class="form-row">
						  <div class="col-4 col-sm-4 col-lg-4 col-xl-4">
                            <div class="form-group">
								<p> """ + skill['skill_name'] + """</p>
							</div>
                         </div>
                        <!--   <div class="col-3 col-sm-3 col-lg-3 col-xl-3">
                             <div class="form-group">
								<p>""" + skill['skill_domain'] + """</p>
							</div>
                         </div>
                        -->
                           <div class="col-4 col-sm-4 col-lg-4 col-xl-4">
                            <div class="form-group">
								<p> """ + skill_level + """</p>
							</div>
                         </div>
                           <div class="col-4 col-sm-4 col-lg-4 col-xl-4">
                             <div class="form-group">
								<div class="text-center">
									<button title="Delete first if you want to update." class="btn btn-secondary btn-sm" name="choice" value=""" + str(
                    counter) + """ type="submit">Delete</button></div>
								</div>
							</div>
                     </div>"""
                skills_row = form_row + skills_row
        else:
            skills_row = ""

        return render_template('update_skills.html',
                               **session['menu'],
                               skills_row=skills_row)

    if request.method == 'POST':
        # add a skill
        if request.form['choice'] == 'add':
            skill_code = unidecode.unidecode(
                request.form['skill_name'].lower())
            skill_code = skill_code.replace(" ", "")
            skill_code = skill_code.replace("-", "")
            skill = {
                'skill_code': skill_code,
                'skill_name': request.form['skill_name'].capitalize(),
                'skill_level': request.form['skill_level'],
                'skill_domain': ""
            }
            if not session['skills']:
                session['skills'] = dict()
                session['skills']['description'] = []
                session['skills']['version'] = 1
            for one_skill in session['skills']['description']:
                if one_skill['skill_code'] == skill_code:
                    flash('Skill alreday added', 'warning')
                    return redirect(mode.server + 'user/update_skills/')
            if not skill_code:
                return redirect(mode.server + 'user/update_skills/')
            else:
                session['skills']['description'].append(skill)
                return redirect(mode.server + 'user/update_skills/')

        # update the skill document
        elif request.form['choice'] == 'update':

            # case update before add first time
            if not session['skills']:
                return redirect(mode.server + 'user/')

            # create new document
            my_skills = Document('skills')
            skill_data = {
                'version': session['skills']['version'],
                'description': session['skills']['description']
            }
            data = my_skills.relay_add(session['workspace_contract'],
                                       skill_data, mode)
            if not data[0]:
                flash('Transaction failed', 'danger')
                return redirect(mode.server + 'user/')

            doc_id = data[0]
            session['skills'][
                'id'] = 'did:talao:' + mode.BLOCKCHAIN + ':' + session[
                    'workspace_contract'][2:] + ':document:' + str(doc_id)
            if session['type'] == 'person':
                flash('Your skills have been updated', 'success')
            else:
                flash('Your competencies have been updated', 'success')
            return redirect(mode.server + 'user/')

        # delete the skill
        else:
            counter = request.form['choice']
            del session['skills']['description'][int(counter)]
            return redirect(mode.server + 'user/update_skills/')
Ejemplo n.º 6
0
def credential_list(mode):
    """ request GET , arguments
    @app.route('/api/v1/credential', methods=['GET'], defaults={'mode' : mode})
    "siret" : required, only siren is used (9 first numbers)
    "data : optionam to get content
    """
    print(request.args)
    data = request.args.get('data')
    try:
        siren = request.args['siret'][:9]
    except:
        logging.info('request malformed %s', request.args)
        return make_response(
            jsonify(
                message=
                "Malformed request syntax or invalid request message parameters.",
                category="error",
                status=400), 400)

    username = directory.search_siren(siren, mode)
    if not username or not ns.username_exist(username, mode):
        logging.info('username not found for siren = %s', siren)
        return make_response(
            jsonify(message="SIRET not found.", category="error", status=404),
            404)

    try:
        workspace_contract = ns.get_data_from_username(
            username, mode)['workspace_contract']
        contract = mode.w3.eth.contract(workspace_contract,
                                        abi=constante.workspace_ABI)
        doc_list = contract.functions.getDocuments().call()
    except:
        logging.error('talaonet call failed')
        return make_response(
            jsonify(message="Internal server error.",
                    category="error",
                    status=500), 200)

    result = []

    if data:
        for doc_id in doc_list:
            if contract.functions.getDocument(doc_id).call()[0] == 20000:
                credential = Document('credential')
                credential.relay_get_credential(workspace_contract, doc_id,
                                                mode)
                result.append(credential.__dict__)
        message = "Credential data"
    else:
        for doc_id in doc_list:
            if contract.functions.getDocument(doc_id).call(
            )[0] == 20000:  # doctype for public credential
                link = mode.server + 'certificate/?certificate_id=did:talao:talaonet:' + workspace_contract[
                    2:] + ':document:' + str(doc_id)
                result.append(link)
        message = "Credential link list"

    return make_response(
        jsonify(message=message, category="success", data=result, status=200),
        200)