这是一个最简单的区块链小程序“ Hello Blockstack ”的搭建过程,这个程序不需要后端 api,也不需要用户进行注册数据库。
在这篇教程中我们会用到下面的工具:
npm to manage dependencies and scripts
browserify to compile node code into browser-ready code
blockstack.js to authenticate the user and work with the user's identity/profile information
第一步:安装 yeoman
npm install -g yo generator-blockstack
第二步:给程序创建一个新的目录
mkdir hello-blockstack && cd hello-blockstack yo blockstack
第三步:运行
npm run start
主要的代码注释和理解:
主要的文件是 app.js (在 /public 文件夹里面),代码被包括在监听事件里面,直到 dom 内容加载完成
document.addEventListener("DOMContentLoaded", function(event) { })
在这个里面,我们有一个 signin handler 来处理用户的请求和进入
document.getElementById('signin-button').addEventListener('click', function() { blockstack.redirectUserToSignIn() })
我们也有一个 signout handler 来进行处理用户的退出
document.getElementById('signout-button').addEventListener('click', function() { blockstack.signUserOut(window.location.origin) })
下一步,我们有一个函数来显示用户的简历
function showProfile(profile) {
var person = new blockstack.Person(profile) document.getElementById('heading-name').innerHTML = person.name() document.getElementById('avatar-image').setAttribute('src', person.avatarUrl()) document.getElementById('section-1').style.display = 'none' document.getElementById('section-2').style.display = 'block'
}
在三种状态下可以让用户登录:
The user is already signed in
The user has a sign in request that is pending
The user is signed out
代码表达方式:
if (blockstack.isUserSignedIn()) { // Show the user's profile } else if (blockstack.isSignInPending()) { // Sign the user in } else { // Do nothing }
在用户请求的过程中:
if (blockstack.isUserSignedIn()) {
var profile = blockstack.loadUserData().profile showProfile(profile) } else if (blockstack.isSignInPending()) { blockstack.handlePendingSignIn().then(function(userData) { window.location = window.location.origin })
}
程序显示样式的控制文件:
控制这个程序显示样式的文件是 (/public/manifest.json)
{ "name": "Hello, Blockstack", "start_url": "localhost:5000", "description": "A simple demo of Blockstack Auth", "icons": [{ "src": "https://helloblockstack.com/icon-192x192.png", "sizes": "192x192", "type": "image/png" }] }
源代码实现:
git init
git add . && git commit -m "first commit"
然后去 github 添加一个新的 repo
git remote add origin [email protected]:YOUR_USERNAME_HERE/hello-blockstack.git
git push origin master