create account

Función para validar PubKey de Hive y usarla en un sistema de autenticación como Keychain by enrique89

View this thread on: hive.blogpeakd.comecency.com
· @enrique89 ·
$23.22
Función para validar PubKey de Hive y usarla en un sistema de autenticación como Keychain
![hivedev.png](https://files.peakd.com/file/peakd-hive/enrique89/23tS2pRFD9hBUXraqu9SFSVeKs13dcbfidbT1CwJcVHPjFaPsL2PFRLGzNjeRz6rCvsJm.png)

<br>

¡Hola, Hivers desarrolladores de la comunidad hispana! Hoy quiero compartir con ustedes una función para validar si una clave pública está asociada a un nombre de usuario en Hive.

Esta función se puede utilizar en cualquier otra que requiera validar el ingreso de un usuario a una aplicación. Por ejemplo, puedes emplearla junto con Keychain, si necesitas validar la información después de que el usuario ingrese y necesites dar acceso a una aplicación.

### Análisis de Códigos
Entradas:

**key:** Una cadena que representa la clave pública a verificar.
**Hive username:** Una cadena que representa el nombre de usuario que debe verificarse con la clave pública.

**Flujo:**

- Construir una carga útil de solicitud JSON-RPC con la clave pública y el nombre de usuario proporcionado.
- Comprobar si el nombre de usuario está asociado a la clave pública en la respuesta.
- Retornar True si se encuentra el nombre de usuario; de lo contrario, Retornar False.

**Salida:**

- Lanza un error si ninguna de las API responde correctamente.
- Esta función es útil para autenticar usuarios en aplicaciones que utilizan la blockchain de Hive, comprobando si una clave pública dada está realmente asociada con un nombre de usuario específico en la blockchain.

Yo uso Fetch para hacer la petición en TS:



```
const apiUrls = [
  "https://api.hive.blog",
  "https://anyx.io",
  "https://api.openhive.network",
  "https://rpc.mahdiyari.info",
  "https://api.deathwing.me",
  "https://hive-api.3speak.tv",
];

async function checkPubkey(key: string, username: string): Promise<boolean> {
  const data = {
    jsonrpc: "2.0",
    method: "account_by_key_api.get_key_references",
    params: { keys: [key] },
    id: 1,
  };

  for (const apiUrl of apiUrls) {
    try {
      const response = await fetch(apiUrl, {
        method: "POST",
        body: JSON.stringify(data),
        headers: { "Content-Type": "application/json" },
      });

      if (!response.ok) {
        console.warn(
          `HTTP error! status: ${response.status} for URL: ${apiUrl}`
        );
        continue;
      }

      const json = await response.json();
      const findAccount = json.result.accounts[0]?.includes(username);

      return findAccount ?? false;
    } catch (error) {
      console.error(`Error al realizar la solicitud a ${apiUrl}:`, error);
    }
  }

  throw new Error(
    "No se pudo realizar la solicitud en ninguna de las APIs disponibles."
  );
}

export { checkPubkey };


```




En Python sería así usando requests: 


```
import requests

def verify_hive_user(public_key, username):
    url = 'https://api.hive.blog'
    payload = {
        'jsonrpc': '2.0',
        'method': 'account_by_key_api.get_key_references',
        'params': {
            'keys': [public_key]
        },
        'id': 1
    }
    
    try:
        response = requests.post(url, json=payload)
        response.raise_for_status()  
        data = response.json()
        
        accounts = data.get('result', {}).get('accounts', [])
        
        return any(account[0] == username for account in accounts)
    except requests.RequestException as error:
        raise ValueError('Error verificando el usuario en Hive:', error)

# Ejemplo de uso
public_key = 'STM7qDF7hhEmQeq4JzS9oRQnfvfsqJPUN6wZwyMbSUDiG8JhtkJx2'
username = 'enrique89'
print(verify_hive_user(public_key, username))


```

<br>

Prueba estas funciones en tus aplicaciones y puedes mejorar el código. 

Saludos.
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 112 others
properties (23)
authorenrique89
permlinkfuncion-para-validar-pubkey-de-hive-y-usarla-en-un-sistema-de-autenticacion-como-keychain
categoryspanish
json_metadata{"app":"peakd/2024.6.2","format":"markdown","tags":["spanish"],"users":[],"image":["https://files.peakd.com/file/peakd-hive/enrique89/23tS2pRFD9hBUXraqu9SFSVeKs13dcbfidbT1CwJcVHPjFaPsL2PFRLGzNjeRz6rCvsJm.png"]}
created2024-06-10 02:43:12
last_update2024-06-10 02:43:12
depth0
children2
last_payout2024-06-17 02:43:12
cashout_time1969-12-31 23:59:59
total_payout_value11.621 HBD
curator_payout_value11.598 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length3,607
author_reputation664,568,480,404,036
root_title"Función para validar PubKey de Hive y usarla en un sistema de autenticación como Keychain"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id134,443,928
net_rshares64,490,933,215,017
author_curate_reward""
vote details (176)
@ertytux ·
Justo lo que necesitaba para la miniaplicación de Telegram, pronto....., Gracias Miles!!!
-> https://t.me/HiveCuBaP2P_Bot
properties (22)
authorertytux
permlinkre-enrique89-2024610t72012256z
categoryspanish
json_metadata{"tags":["spanish"],"app":"ecency/3.2.0-vision","format":"markdown+html"}
created2024-06-10 11:20:12
last_update2024-06-10 11:20:12
depth1
children0
last_payout2024-06-17 11:20:12
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length121
author_reputation32,476,975,605,274
root_title"Función para validar PubKey de Hive y usarla en un sistema de autenticación como Keychain"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id134,455,978
net_rshares0
@hivebuzz ·
Congratulations @enrique89! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)

<table><tr><td><img src="https://images.hive.blog/60x70/https://hivebuzz.me/@enrique89/upvotes.png?202406200312"></td><td>You distributed more than 73000 upvotes.<br>Your next target is to reach 74000 upvotes.</td></tr>
</table>

<sub>_You can view your badges on [your board](https://hivebuzz.me/@enrique89) and compare yourself to others in the [Ranking](https://hivebuzz.me/ranking)_</sub>
<sub>_If you no longer want to receive notifications, reply to this comment with the word_ `STOP`</sub>

properties (22)
authorhivebuzz
permlinknotify-1718853214
categoryspanish
json_metadata{"image":["https://hivebuzz.me/notify.t6.png"]}
created2024-06-20 03:13:33
last_update2024-06-20 03:13:33
depth1
children0
last_payout2024-06-27 03:13:33
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length636
author_reputation370,425,965,330,661
root_title"Función para validar PubKey de Hive y usarla en un sistema de autenticación como Keychain"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id134,722,588
net_rshares0