def send_secret_code (username, code, mode) :
	"""
	if phone exist we send and SMS
	if not we send an email
	return : 'sms' or 'email' or None
	"""
	data = ns.get_data_from_username(username, mode)
	if not data :
		logging.error('cannot send secret code')
		return None
	if not data['phone'] :
		try :
			subject = 'Talao : Email authentification  '
			Talao_message.messageHTML(subject, data['email'], 'code_auth', {'code' : code}, mode)
			logging.info('code sent by email')
			return 'email'
		except :
			logging.error('sms failed, no phone')
			return None
	try :
		sms.send_code(data['phone'], code, mode)
		logging.info('code sent by sms')
		return 'sms'
	except :
		subject = 'Talao : Email authentification  '
		try :
			Talao_message.messageHTML(subject, data['email'], 'code_auth', {'code' : code}, mode)
			logging.info('sms failed, code sent by email')
			return 'email'
		except :
			logging.error('sms failed, email failed')
			return None
def ether_transfer(address_to, value, mode):
    w3 = mode.w3
    # calcul du nonce de l envoyeur de token . Ici le portefeuille TalaoGen
    talaoGen_nonce = w3.eth.getTransactionCount(mode.Talaogen_public_key)
    # build transaction
    eth_value = w3.toWei(str(value), 'milli')
    transaction = {
        'to': address_to,
        'value': eth_value,
        'gas': 50000,
        'gasPrice': w3.toWei(mode.GASPRICE, 'gwei'),
        'nonce': talaoGen_nonce,
        'chainId': mode.CHAIN_ID
    }
    #sign transaction with TalaoGen wallet
    key = mode.Talaogen_private_key
    signed_txn = w3.eth.account.sign_transaction(transaction, key)
    # alert Admin
    address = mode.Talaogen_public_key
    balance = w3.eth.getBalance(address) / 1000000000000000000
    if balance < 0.2:
        Talao_message.message('nameservice', '*****@*****.**',
                              'balance Talaogen < 0.2eth', mode)
    w3.eth.sendRawTransaction(signed_txn.rawTransaction)
    hash = w3.toHex(w3.keccak(signed_txn.rawTransaction))
    receipt = w3.eth.waitForTransactionReceipt(hash, timeout=2000)
    if not receipt['status']:
        return None
    return hash
def cci_password(mode):
	if not session.get('email') :
		return redirect(mode.server + 'create_company_cci/')
	session['password'] = request.form['password']
	session['code'] = str(random.randint(10000, 99999))
	session['code_delay'] = datetime.now() + timedelta(seconds= 180)
	session['try_number'] = 0
	subject = 'Talao : Email authentification  '
	Talao_message.messageHTML(subject, session['email'], 'code_auth', {'code' : session['code']}, mode)
	print("Warning : code sent =" + session['code'])
	return render_template("CCI/create_company_cci_code.html", message_class='text-info', message = '')
Exemple #4
0
def _create_user_step_3(address, private_key, wallet_address,
                        workspace_contract, username, email, password, phone,
                        mode, decentralized):

    # add username to register in local nameservice Database with last check
    if ns.username_exist(username, mode):
        username = username + str(random.randint(1, 100))
    ns.add_identity(username, workspace_contract, email, mode)

    # transfer workspace / alias
    if decentralized:
        email_address = wallet_address
        if not transfer_workspace(address, private_key, wallet_address, mode):
            print('Error : workspace transfer failed')
            return False
        print('Success : workspace ownership tranfered to ' + wallet_address)
    else:
        email_address = address
        if not ns.update_wallet(workspace_contract, wallet_address, mode):
            print('Error : Alias update failed')
            return False
        print('Success : wallet address added as an alias')

    # setup password
    if password:
        ns.update_password(username, password, mode)
        print('Success : password has been updated')

    # setup phone
    if phone:
        ns.update_phone(username, phone, mode)
        print('Success : phone has been updated')

    # If decentralized and if needed, pre-activate the wallet address
    if not has_vault_access(wallet_address, mode) and decentralized:
        ether_transfer(wallet_address, mode.ether2transfer, mode)
        token_transfer(wallet_address, mode.talao_to_transfer, mode)

    # emails sent to admin
    Talao_message.messageLog("", "", username, email, "createidentity.py",
                             email_address, "", workspace_contract, "", email,
                             "", "", mode)
    # an email sent to user
    Talao_message.messageUser("", "", username, email, email_address, "",
                              workspace_contract, mode)

    # Oracle....to lock Talao token  on Ethereum agains private bc
    #if mode.myenv == 'aws' :
    #	ethereum_bridge.lock_ico_token(None, None)
    #	print('transfer Ethereum token done')

    print("Success : create identity process step 3 is over")
    return True
def forgot_password(mode) :
	"""
	@app.route('/forgot_password/', methods = ['GET', 'POST'])
	This function is called from the login view.
	build JWE to store timestamp, username and email, we use Talao RSA key
	"""
	if request.method == 'GET' :
		return render_template('./login/forgot_password_init.html')
	if request.method == 'POST' :
		username = request.form.get('username')
		if not ns.username_exist(username, mode) :
			flash("Username not found", "warning")
			return render_template('./login/login_password.html')
		email= ns.get_data_from_username(username, mode)['email']
		private_rsa_key = privatekey.get_key(mode.owner_talao, 'rsa_key', mode)
		RSA_KEY = RSA.import_key(private_rsa_key)
		public_rsa_key = RSA_KEY.publickey().export_key('PEM').decode('utf-8')
		expired = datetime.timestamp(datetime.now()) + 180 # 3 minutes live
		# build JWE
		jwe = JsonWebEncryption()
		header = {'alg': 'RSA1_5', 'enc': 'A256GCM'}
		json_string = json.dumps({'username' : username, 'email' : email, 'expired' : expired})
		payload = bytes(json_string, 'utf-8')
		token = jwe.serialize_compact(header, payload, public_rsa_key)
		link = mode.server + 'forgot_password_token/?'+ urlencode({'token'  : token.decode('utf-8')}, doseq=True)
		subject = "Renew your password"
		if Talao_message.messageHTML(subject, email, 'forgot_password', {'link': link}, mode):
			flash("You are going to receive an email to renew your password.", "success")
		return render_template('./login/login_password.html')
def create_user(username,
                email,
                mode,
                did='',
                password='',
                firstname=None,
                lastname=None,
                phone=''):

    email = email.lower()

    # Setup user address for repository
    account = mode.w3.eth.account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530' +
                                         email)
    address = account.address
    private_key = account.key.hex()

    # create RSA key as derivative from Ethereum private key
    RSA_key, RSA_private, RSA_public = privatekey.create_rsa_key(
        private_key, mode)

    # Setup a key (symetric) named 'AES' to encrypt private data and to be shared with partnership
    AES_key = get_random_bytes(16)

    # Setup another key named 'SECRET' (symetric) to encrypt secret data
    SECRET_key = get_random_bytes(16)

    # AES key encrypted with RSA key
    cipher_rsa = PKCS1_OAEP.new(RSA_key)
    AES_encrypted = cipher_rsa.encrypt(AES_key)

    # SECRET encrypted with RSA key
    cipher_rsa = PKCS1_OAEP.new(RSA_key)
    SECRET_encrypted = cipher_rsa.encrypt(SECRET_key)

    # Email encrypted with RSA Key
    bemail = bytes(email, 'utf-8')

    # Ether transfer from TalaoGen wallet
    hash = ether_transfer(address, mode.ether2transfer, mode)
    logging.info('ether transfer done')

    # Talao tokens transfer from TalaoGen wallet
    hash = token_transfer(address, mode.talao_to_transfer, mode)
    logging.info('token transfer done')

    # CreateVaultAccess call in the token to declare the identity within the Talao Token smart contract
    hash = createVaultAccess(address, private_key, mode)
    logging.info('create vault acces done')

    # Identity setup
    contract = mode.w3.eth.contract(mode.workspacefactory_contract,
                                    abi=constante.Workspace_Factory_ABI)
    nonce = mode.w3.eth.getTransactionCount(address)
    txn = contract.functions.createWorkspace(1001, 1, 1, RSA_public,
                                             AES_encrypted, SECRET_encrypted,
                                             bemail).buildTransaction({
                                                 'chainId':
                                                 mode.CHAIN_ID,
                                                 'gas':
                                                 7500000,
                                                 'gasPrice':
                                                 mode.w3.toWei(
                                                     mode.GASPRICE, 'gwei'),
                                                 'nonce':
                                                 nonce,
                                             })
    signed_txn = mode.w3.eth.account.signTransaction(txn, private_key)
    mode.w3.eth.sendRawTransaction(signed_txn.rawTransaction)
    transaction_hash = mode.w3.toHex(mode.w3.keccak(signed_txn.rawTransaction))
    if not mode.w3.eth.waitForTransactionReceipt(
            transaction_hash, timeout=2000, poll_latency=1)['status']:
        logging.error('transaction createWorkspace failed')
        return None, None, None
    logging.info('createWorkspace done')

    # workspace_contract address to be read in fondation smart contract
    workspace_contract = ownersToContracts(address, mode)
    logging.info('workspace_contract has been setup = %s', workspace_contract)

    # store RSA key in file ./RSA_key/rinkeby, talaonet ou ethereum
    filename = "./RSA_key/" + mode.BLOCKCHAIN + '/did:talao:' + mode.BLOCKCHAIN + ':' + workspace_contract[
        2:] + ".pem"
    try:
        file = open(filename, "wb")
        file.write(RSA_private)
        file.close()
        logging.info('RSA key stored on disk')
    except:
        logging.error('RSA key not stored on disk')

    # add username to register in local nameservice Database
    if firstname and lastname:
        filename = mode.db_path + 'person.json'
        personal = json.load(open(filename, 'r'))
        personal['lastname']['claim_value'] = lastname
        personal['firstname']['claim_value'] = firstname
        personal = json.dumps(personal, ensure_ascii=False)
    else:
        personal = ''
    if not ns.add_identity(username,
                           workspace_contract,
                           email,
                           mode,
                           phone=phone,
                           password=password,
                           did=did,
                           personal=personal):
        logging.error('add identity in nameservice.db failed')
        return None, None, None
    logging.info('add identity in nameservice.db done')

    # store Ethereum private key in keystore
    if not privatekey.add_private_key(private_key, mode):
        logging.error('add private key in keystore failed')
        return None, None, None
    else:
        logging.info('private key in keystore')

    # key 1 issued to Web Relay to act as agent.
    if not add_key(address, workspace_contract, address, workspace_contract,
                   private_key, mode.relay_address, 1, mode):
        logging.error('add key 1 to web Relay failed')
    else:
        logging.info('key 1 to web Relay has been added')

    # emails send to user and admin
    Talao_message.messageLog(lastname, firstname, username, email,
                             "createidentity.py", address, private_key,
                             workspace_contract, "", email, "", "", mode)
    # By default an email is sent to user
    Talao_message.messageUser(lastname, firstname, username, email, address,
                              private_key, workspace_contract, mode)

    logging.info('end of create identity')
    return address, private_key, workspace_contract
def create_company(email, username, did, mode, siren=None, name=None) :

	global relay_address

	# wallet init
	account = mode.w3.eth.account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530')
	address = account.address
	private_key = account.privateKey.hex()
	logging.info('adresse = %s', address)
	logging.info('Success : private key = %s', private_key)

	# calculate RSA key
	RSA_key, RSA_private, RSA_public = privatekey.create_rsa_key(private_key, mode)

	# création de la cle AES
	AES_key = get_random_bytes(16)
	# création de la cle SECRET
	SECRET_key = get_random_bytes(16)
	# encryption de la cle AES avec la cle RSA
	cipher_rsa = PKCS1_OAEP.new(RSA_key)
	AES_encrypted=cipher_rsa.encrypt(AES_key)
	# encryption de la cle SECRET avec la cle RSA
	cipher_rsa = PKCS1_OAEP.new(RSA_key)
	SECRET_encrypted=cipher_rsa.encrypt(SECRET_key)
	# Email to bytes
	bemail = bytes(email , 'utf-8')

	try :
		# Transaction pour le transfert des nethers depuis le portfeuille TalaoGen
		h1 = ether_transfer(address, mode.ether2transfer, mode)
		logging.info('ether transfer done')
		# Transaction pour le transfert des tokens Talao depuis le portfeuille TalaoGen
		h2 = token_transfer(address, mode.talao_to_transfer, mode)
		logging.info('token transfer done')
		# Transaction pour l'acces dans le token Talao par createVaultAccess
		h3 = createVaultAccess(address, private_key, mode)
		logging.info('create vault access done')
		# Transaction pour la creation du workspace :
		bemail = bytes(email , 'utf-8')
		h4 = createWorkspace(address, private_key, RSA_public, AES_encrypted, SECRET_encrypted, bemail, mode, user_type=2001)
		logging.info('create create workspace done')
	except :
		logging.error('transaction failed')
		return None, None, None
	if not (h1 and h2 and h3 and h4) :
		logging.error('transaction failed')
		return None, None, None

	# lecture de l'adresse du workspace contract dans la fondation
	workspace_contract = ownersToContracts(address, mode)
	logging.info( 'workspace contract = %s', workspace_contract)

	# store RSA key in file ./RSA_key/rinkeby, talaonet ou ethereum
	filename = "./RSA_key/" + mode.BLOCKCHAIN + '/did:talao:' + mode.BLOCKCHAIN + ':'  + workspace_contract[2:] + ".pem"
	try :
		file = open(filename,"wb")
		file.write(RSA_private)
		file.close()
		logging.info('RSA key stored on disk')
	except :
		logging.error(' RSA key not stored on disk')

	# add private key in keystore
	if privatekey.add_private_key(private_key, mode) :
		logging.info('private key added in keystore ')
	else :
		logging.error('add private key failed')
		return None, None, None

	# update resolver and create local database for this company
	if not ns.add_identity(username, workspace_contract, email, mode, did=did) :
		logging.error('add identity in nameservice failed')
		return None, None, None

	# create database for manager within the company
	if not ns.init_host(username, mode) :
		logging.error('add company in nameservice failed')

	# For setup of new chain one need to first create workspaces for Relay and Talao
	if username != 'relay' and username != 'talao' :
		# management key (1) issued to Relay
		add_key(address, workspace_contract, address, workspace_contract, private_key, mode.relay_address, 1, mode)

	if username == 'relay' :
		# one stores relay address for Talao workspace setup
		relay_address = address
	if username == 'talao' :
		add_key(address, workspace_contract, address, workspace_contract, private_key, relay_address, 1, mode)

	# send messages
	Talao_message.messageLog("no lastname","no firstname", username, email, 'Company created by Talao', address, private_key, workspace_contract, "", email, "", "", mode)
	# one sends an email by default
	Talao_message.messageUser("no lastname", "no firstname", username, email, address, private_key, workspace_contract, mode)

	logging.info('end of of create company')
	return address, private_key, workspace_contract