基于区块链的毕业设计Welcome to @oneclickdapp/ethereum-auth 👋 – 欢迎使用@oneclickdapp/ethereum auth👋

本文提供基于区块链的毕业设计国外最新区块链项目源码下载,包括solidity,eth,fabric等blockchain区块链,基于区块链的毕业设计Welcome to @oneclickdapp/ethereum-auth 👋 – 欢迎使用@oneclickdapp/ethereum auth👋 是一篇很好的国外资料

Welcome to @oneclickdapp/ethereum-auth 👋

Welcome to @oneclickdapp/ethereum-auth 👋 - 欢迎使用@oneclickdapp/ethereum auth👋

Ethereum auth provider for RedwoodJS

Looking to implement your own custom Redwood Auth? You may this tutorial helpful.

Demo

Demo source code

Welcome to @oneclickdapp/ethereum-auth 👋 - 欢迎使用@oneclickdapp/ethereum auth👋

Quick Start

const ethereum = new EthereumAuthClient({   makeRequest,   debug: process.NODE_ENV !== "development",   infuraId: process.env.INFURA_ID });  const { logIn, logOut, getCurrentUser, client } = useAuth();  // Trigger authentication await logIn("walletConnect");

If this is your first time using Redwood Auth, you should check out the official Redwood auth docs

Setup

If you haven’t created a redwood app yet, you can do so now. See my introductory blog post for more help getting started.

yarn create redwood-app myDapp

First let’s do some scaffolding and install the necessary packages. This is where the 🧙‍♂️ magic happens!

cd myDapp yarn rw setup auth ethereum

Next we need to update our models. Add address to the User model, and create a new AuthDetail model.

// api/db/schema.prisma model User {   id         String     @id @default(uuid())   address    String     @unique   authDetail AuthDetail }  model AuthDetail {   id        String   @id @default(uuid())   nonce     String   timestamp DateTime @default(now()) }

Now lets use the generator for our new models. We only need the sdl for AuthDetail.

yarn rw generate scaffold user yarn rw generate sdl AuthDetail

You can delete the service for authDetails, since it won’t be used.

Awesomesauce. Let’s spin up our database!

yarn rw db save yarn rw db up

We’re halfway there. Now let’s create a new service to verify Ethereum signatures. We’ll start by creating the sdl ethereumAuth.js.

// api/src/graphql/ethereumAuth.js export const schema = gql`   type Mutation {     authChallenge(input: AuthChallengeInput!): AuthChallengeResult     authVerify(input: AuthVerifyInput!): AuthVerifyResult   }    input AuthChallengeInput {     address: String!   }    type AuthChallengeResult {     message: String!   }    input AuthVerifyInput {     signature: String!     address: String!   }    type AuthVerifyResult {     token: String!   } `;

Next create a new service named ethereumAuth, and paste in this code.

// api/src/services/ethereumAuth/ethereumAuth.js import { AuthenticationError } from "@redwoodjs/api";  import { bufferToHex } from "ethereumjs-util"; import { recoverPersonalSignature } from "eth-sig-util"; import jwt from "jsonwebtoken";  import { db } from "src/lib/db";  const NONCE_MESSAGE =   "Please prove you control this wallet by signing this random text: ";  const getNonceMessage = nonce => NONCE_MESSAGE + nonce;  export const authChallenge = async ({ input: { address: addressRaw } }) => {   const nonce = Math.floor(Math.random() * 1000000).toString();   const address = addressRaw.toLowerCase();   await db.user.upsert({     where: { address },     update: {       authDetail: {         update: {           nonce,           timestamp: new Date()         }       }     },     create: {       address,       authDetail: {         create: {           nonce         }       }     }   });    return { message: getNonceMessage(nonce) }; };  export const authVerify = async ({   input: { signature, address: addressRaw } }) => {   try {     const address = addressRaw.toLowerCase();     const authDetails = await db.user       .findOne({         where: { address }       })       .authDetail();     if (!authDetails) throw new Error("No authentication started");      const { nonce, timestamp } = authDetails;     const startTime = new Date(timestamp);     if (new Date() - startTime > 5 * 60 * 1000)       throw new Error(         "The challenge must have been generated within the last 5 minutes"       );     const signerAddress = recoverPersonalSignature({       data: bufferToHex(Buffer.from(getNonceMessage(nonce), "utf8")),       sig: signature     });     if (address !== signerAddress.toLowerCase())       throw new Error("invalid signature");      const token = jwt.sign({ address }, process.env.ETHEREUM_JWT_SECRET, {       expiresIn: "5h"     });     return { token };   } catch (e) {     throw new Error(e);   } };

Last step, we need to create a secret for issuing jwt tokens.

openssl rand -base64 48

Add the result as ETHEREUM_JWT_SECRET to your .env file.

Done! You can use your shiny new Ethereum auth. For a full example see https://github.com/oneclickdapp/redwood-ethereum-login-demo. In the meantime, here’s a quick snippet to get you started.

// web/src/pages/LoginPage/LoginPage.js import { Link, routes, navigate } from "@redwoodjs/router"; import { useAuth } from "@redwoodjs/auth"; import { useParams } from "@redwoodjs/router";  const LoginPage = () => {   const { logIn } = useAuth();   const { redirectTo } = useParams();    const onLogin = async () => {     await logIn();     navigate(redirectTo || routes.home());   };    return (     <>       <h1>LoginPage</h1>       <p>         You must have an ethereum wallet, such as MetaMask, installed in your         browser       </p>       <button onClick={onLogin}>Log in with Ethereum</button>     </>   ); };  export default LoginPage;

Wallet Connect

You must pass an optional rpc or infuraId to use Wallet Connect.

ethereum = new EthereumAuthClient({   makeRequest,   // Note: you must set NODE_ENV manually when using Netlify   debug: process.NODE_ENV !== "development",   infuraId: process.env.INFURA_ID   // For rpc see https://docs.walletconnect.org/quick-start/dapps/web3-provider#provider-options });

Then pass the type “walletConnect” when you unlock

const { logIn, logOut, getCurrentUser } = useAuth()  const onClickWalletConnect = async () => {   await logIn("walletConnect")

Additional Resources

Now that you’ve completed setup, you might find these resources useful. More docs/examples are welcome here!

  • Tutorial II Role-based access control (RBAC) https://redwoodjs.com/tutorial2/role-based-authorization-control-rbac
  • Cookbook RBAC https://redwoodjs.com/cookbook/role-based-access-control-rbac

Contributing

Basic

If you’re only editing this package, then you just link @oneclickdapp/ethereum-auth in your test redwood app.

yarn link @oneclickdapp/ethereum-auth

Advanced

If you’re changes affect how internal stuff in RedwoodJS uses this package, then you’ll need to do a bit more work. Things that may be affected include decoders in @redwoodjs/api, frontend tooling in @redwoodjs/auth, and CLI generators in @redwoodjs/cli. Unfortunately, yarn link will not work for redwood local development. Please follow the guide here https://github.com/redwoodjs/redwood/blob/main/CONTRIBUTING.md#local-development for more help.

# In the redwood repo yarn build:watch  # Then in your example redwood app yarn rwt copy:watch ../redwood

TODO

  • Add support for walletconnect
  • Allow direct access to the ethers provider on the client.
  • Export typescript types here for the user object, instead of declaring them inside @redwoodjs/auth
  • Add support for walletlink

Publishing

yarn publish --dry-run

Author

👤 Patrick Gallagher blockchainbuddha@gmail.com

  • Website: https://patrickgallagher.dev
    • Twitter: @pi0neerpat
    • GitHub: @pi0neerpat

Show your support

Give a ⭐️ if this project helped you!


This README was generated with ❤️ by readme-md-generator

cleanup docs


欢迎使用@oneclickdapp/ethereum auth👋

RedwoodJS的以太坊eth身份验证提供商想实现自己的自定义Redwood身份验证吗?你可能会对本教程有所帮助。

演示源代码

如果这是您第一次使用Redwood Auth,您应该查看官方的Redwood Auth文档

✨ 演示

如果您还没有创建Redwood应用程序,现在就可以这样做。请参阅我的介绍性博客文章,以获取更多入门帮助。

Welcome to @oneclickdapp/ethereum-auth 👋 - 欢迎使用@oneclickdapp/ethereum auth👋

快速入门

const ethereum = new EthereumAuthClient({   makeRequest,   debug: process.NODE_ENV !== "development",   infuraId: process.env.INFURA_ID });  const { logIn, logOut, getCurrentUser, client } = useAuth();  // Trigger authentication await logIn("walletConnect");

首先,让我们搭建一些脚手架并安装必要的软件包。这就是🧙‍♂️✨ 神奇发生了!

设置

接下来我们需要更新我们的模型。向用户模型添加地址,并创建新的AuthDetail模型。

yarn create redwood-app myDapp

现在让我们为新型号使用发电机。我们只需要sdl的细节。

cd myDapp yarn rw setup auth ethereum

您可以删除authDetails服务,因为它不会被使用。

// api/db/schema.prisma model User {   id         String     @id @default(uuid())   address    String     @unique   authDetail AuthDetail }  model AuthDetail {   id        String   @id @default(uuid())   nonce     String   timestamp DateTime @default(now()) }

辣酱。让我们启动数据库!我们已经到一半了。现在,让我们创建一个新服务来验证以太坊eth签名。我们将从创建sdl开始以太坊ethAuth.js.

yarn rw generate scaffold user yarn rw generate sdl AuthDetail

接下来创建一个名为ethereumAuth的新服务,并粘贴到该代码中。

最后一步,我们需要为发行jwt令牌创建一个秘密。

yarn rw db save yarn rw db up

将结果作为以太坊ethJWTu机密添加到.env文件中。

// api/src/graphql/ethereumAuth.js export const schema = gql`   type Mutation {     authChallenge(input: AuthChallengeInput!): AuthChallengeResult     authVerify(input: AuthVerifyInput!): AuthVerifyResult   }    input AuthChallengeInput {     address: String!   }    type AuthChallengeResult {     message: String!   }    input AuthVerifyInput {     signature: String!     address: String!   }    type AuthVerifyResult {     token: String!   } `;

完成!你可以使用你闪亮的新以太坊eth认证。有关完整示例,请参见https://github.com/oneclickdapp/redwood-ethereum-login-demo。同时,这里有一个简短的片段让你开始。

// api/src/services/ethereumAuth/ethereumAuth.js import { AuthenticationError } from "@redwoodjs/api";  import { bufferToHex } from "ethereumjs-util"; import { recoverPersonalSignature } from "eth-sig-util"; import jwt from "jsonwebtoken";  import { db } from "src/lib/db";  const NONCE_MESSAGE =   "Please prove you control this wallet by signing this random text: ";  const getNonceMessage = nonce => NONCE_MESSAGE + nonce;  export const authChallenge = async ({ input: { address: addressRaw } }) => {   const nonce = Math.floor(Math.random() * 1000000).toString();   const address = addressRaw.toLowerCase();   await db.user.upsert({     where: { address },     update: {       authDetail: {         update: {           nonce,           timestamp: new Date()         }       }     },     create: {       address,       authDetail: {         create: {           nonce         }       }     }   });    return { message: getNonceMessage(nonce) }; };  export const authVerify = async ({   input: { signature, address: addressRaw } }) => {   try {     const address = addressRaw.toLowerCase();     const authDetails = await db.user       .findOne({         where: { address }       })       .authDetail();     if (!authDetails) throw new Error("No authentication started");      const { nonce, timestamp } = authDetails;     const startTime = new Date(timestamp);     if (new Date() - startTime > 5 * 60 * 1000)       throw new Error(         "The challenge must have been generated within the last 5 minutes"       );     const signerAddress = recoverPersonalSignature({       data: bufferToHex(Buffer.from(getNonceMessage(nonce), "utf8")),       sig: signature     });     if (address !== signerAddress.toLowerCase())       throw new Error("invalid signature");      const token = jwt.sign({ address }, process.env.ETHEREUM_JWT_SECRET, {       expiresIn: "5h"     });     return { token };   } catch (e) {     throw new Error(e);   } };

您必须传递可选的rpc或infuraId才能使用Wallet Connect。

openssl rand -base64 48

然后在解锁时传递类型“walletConnect”

现在您已经完成了安装,您可能会发现这些资源很有用。这里欢迎更多的文档/示例!

// web/src/pages/LoginPage/LoginPage.js import { Link, routes, navigate } from "@redwoodjs/router"; import { useAuth } from "@redwoodjs/auth"; import { useParams } from "@redwoodjs/router";  const LoginPage = () => {   const { logIn } = useAuth();   const { redirectTo } = useParams();    const onLogin = async () => {     await logIn();     navigate(redirectTo || routes.home());   };    return (     <>       <h1>LoginPage</h1>       <p>         You must have an ethereum wallet, such as MetaMask, installed in your         browser       </p>       <button onClick={onLogin}>Log in with Ethereum</button>     </>   ); };  export default LoginPage;

钱包连接

如果您只编辑此软件包,则只需在测试红木应用程序中链接@oneclickdapp/ethereum auth。

ethereum = new EthereumAuthClient({   makeRequest,   // Note: you must set NODE_ENV manually when using Netlify   debug: process.NODE_ENV !== "development",   infuraId: process.env.INFURA_ID   // For rpc see https://docs.walletconnect.org/quick-start/dapps/web3-provider#provider-options });

如果您的更改会影响RedwoodJS中内部的东西如何使用这个包,那么您需要做更多的工作。可能受到影响的内容包括@redwoodjs/api中的解码器、@redwoodjs/auth中的前端工具以及@redwoodjs/CLI中的CLI生成器。不幸的是,纱线链接将不工作的红杉当地发展。请按照这里的指南走https://github.com/redwoodjs/redwood/blob/main/contribution.md#本地-寻求更多帮助。

const { logIn, logOut, getCurrentUser } = useAuth()  const onClickWalletConnect = async () => {   await logIn("walletConnect")

其他资源

👤 帕特里克·加拉赫blockchainfoddha@gmail.com

  • 教程II基于角色的访问控制(RBAC)https://redwoodjs.com/tutorial2/role-based-authorization-control-rbac
  • 食谱RBAChttps://redwoodjs.com/cookbook/role-based-access-control-rbac

贡献

基本

给一个⭐️如果这个项目对你有帮助!

yarn link @oneclickdapp/ethereum-auth

高级

此自述文件是使用❤️ 通过自述md generator

# In the redwood repo yarn build:watch  # Then in your example redwood app yarn rwt copy:watch ../redwood

TODO

  • 添加对walletconnect的支持
  • 允许直接访问客户端上的以太网提供程序。
  • 在此处为用户对象导出typescript类型,而不是在@redwoodjs/auth中声明这些类型添加对walletlink的支持
  • 网站:https://patrickgallagher.dev推特:@pi0neerpat GitHub:@pi0neerpat

发布

yarn publish --dry-run

作者

👤 Patrick Gallagher blockchainbuddha@gmail.com

  • 推特:@pi0neerpat

展示您的支持

Give a ⭐️ if this project helped you!


This README was generated with ❤️ by readme-md-generator

cleanup docs

部分转自网络,侵权联系删除区块链源码网

www.interchains.cc

https://www.interchains.cc/20375.html

区块链毕设网(www.interchains.cc)全网最靠谱的原创区块链毕设代做网站 部分资料来自网络,侵权联系删除! 最全最大的区块链源码站 ! QQ3039046426
区块链知识分享网, 以太坊dapp资源网, 区块链教程, fabric教程下载, 区块链书籍下载, 区块链资料下载, 区块链视频教程下载, 区块链基础教程, 区块链入门教程, 区块链资源 » 基于区块链的毕业设计Welcome to @oneclickdapp/ethereum-auth 👋 – 欢迎使用@oneclickdapp/ethereum auth👋

提供最优质的资源集合

立即查看 了解详情