🧑‍💻 Hive dApps & dPackages development - hive-authentication package 📦 usage guide 📝

in HiveDevs20 days ago

🐝 What’s the Buzz About?

Hello Hive community members! 🎉

  • You may have seen me mention the hive-authentication package in earlier posts, but never with this much jazz.
  • That’s because it was, well, marinating like a fine curry. 🍛
  • But now—it’s piping hot and ready for YOU to spice up your projects!
  • No more waiting! Time to fire it up in your ReactJS apps. 🚀

react-js-projects-only

⚠️ Quick Note:
This is strictly for ReactJS projects! No plain vanilla, no Angular, no Vue—just pure ReactJS flavor.


🔎 Where To Find It?

npmjs


🤔 Why Use hive-authentication?

but why though?

  • Need to verify proof-challenge signed by a hive user from your backend? ✅
  • Want to let users login with a private posting key (as the last resort)? ✅
  • Fancy custom local storage per user? ✅
  • Don’t need any of this? No worries—stick to @aioha and party on! 🎈

Now you know the “why”—let’s jump in!

alright let's do it


🛠️ How to Implement in ReactJS

Step 1: Install

npm install hive-authentication

Step 2: Initialize in App.tsx

Open up App.tsx and set up your authentication flow! 🔥

import { initAioha } from '@aioha/aioha'
import { AiohaProvider } from '@aioha/react-provider'

const aioha = initAioha(
  {
    hivesigner: {
      app: 'hive-auth-demo.app',
      callbackURL: window.location.origin + '/hivesigner.html',
      scope: ['login', 'vote']
    },
    hiveauth: {
      name: 'Hive Authentication Demo',
      description: 'A demo app for testing Hive authentication'
    }
  }
)

function App() {
    return (
        <AiohaProvider aioha={aioha}>
            <div>Your App goes here</div>
        </AiohaProvider>
    );
}   

Step 3: Add the Magic AuthButton

import { AuthButton, useAuthStore } from 'hive-authentication';
import 'hive-authentication/build.css';
import { useAioha } from "@aioha/react-provider";

function YourComponent() {
    const { currentUser, loggedInUsers } = useAuthStore();
    const { aioha } = useAioha();

    useEffect(() => {
        const unsubscribe = useAuthStore.subscribe((state) => {
            console.log('Store state changed:', state);
        });
        return unsubscribe;
    }, []);

    return (
        <div>
          <h1>My App</h1>
          <AuthButton 
            onAuthenticate={handleAuthenticate}
            aioha={aioha}
            shouldShowSwitchUser = {true} // Optional true
            onClose={() => {
              console.log("AuthButton dialog closed");
            }}
          />
          
          {currentUser && (
            <p>Welcome, {currentUser.username}!</p>
          )}
        </div>
    );
}

Step 4: Call Your Backend Like a Pro

const handleAuthenticate = async (hiveResult: HiveAuthResult): Promise<string> => {
    console.log('Hive authentication result:', hiveResult);

    try {
      const response = await fetch("https://beta-api.distriator.com/login", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          challenge: hiveResult.challenge,
          username: hiveResult.username,
          pubkey: hiveResult.publicKey,
          proof: hiveResult.proof,
        }),
      });

      if (!response.ok) {
        throw new Error(`Server authentication failed: ${response.status} ${response.statusText}`);
      }

      const data = await response.json();
      console.log('Server response:', data);

      // Return your server response as JSON string
      return JSON.stringify(data);
    } catch (error) {
      console.error("Authentication error:", error);
      throw error;
    }
  };

Wait for the useEffect state change message—voila, it works!

that's it gif


🎉 Done & Dusted

Yep, that’s pretty much it. Easy as pie. 🥧
Give it a spin and let me know how it powers up your Hive projects!


🦾 More Power to Hive (and You!)

  • More power to Hive community members!
  • More power to open-source contributors!
  • More power to Hive blockchain!
  • Hive to the moon and beyond 🚀🌕

🙌 Support & Love

  • Tried this package? Drop your feedback in the comments! 💬
  • Liked my work? Upvote this post! 👍
  • Want to keep seeing new stuff? Vote me as Hive Witness 😎
  • Love me? Tip me on this post!
  • See you in the next update—BYE BYE! 👋

📝 Final Note


🚀 My Contributions to ♦️ Hive Ecosystem

ContributionToHiveEcosystem
Hive Witness NodeHive API Node3Speak Video Encoder Node Operator (highest number of nodes)3Speak Mobile App Developer
Podcast App Developer3Shorts App Developer3Speak Support & Maintenance TeamDistriator Developer
CheckinWithXYZHive InboxHiFindHive Donate App
Contributed to HiveAuth Mobile AppEcency ↔ 3Speak IntegrationEcency ↔ InLeo IntegrationEcency ↔ Actifit Integration
Hive Stats AppVote for Witness AppHiveFlutterKitNew 3Speak App

🙌 Support Back

❤️ Appreciate my work? Consider supporting @threespeak & @sagarkothari88! ❤️