OAuth登录流程
1.github 官网,登录
Settings -> Developer settings -> OAuth Apps -> New GitHub App
2.在管理页面设置
- 设置回调方法
- Authorization callback URL: http://127.0.0.1:7001/auth/github/callback
- 默认github登录成功后,会附带参数code ,10分钟有效 (2)复制获取 client_id 和 client_secret
3.跑代码
- 获取code:使用github.com/login/oauth… 登录获取 code,参数 client_id
- 获取token:使用github.com/login/oauth… 使用,参数code + client_id + client_secret
- 获取用户信息:api.github.com/user 参数 access_token=token
Webhooks 自动响应部署
1. 进入自己的项目设置
2. 点击settings -> Manage webhook
- Payload URL : www.soxstudio.top:3003/webhooks
- Content type : application/json
- Secret : 自定义密钥
3. 触发方式:
- Just the push event (推送时候生效)
- Send me everything. (用于调试)
4. Recent Deliveries
点击redeliver 测试响应
实战
1.创建webhooks.js (对应的服务端代码)
var http = require('http')
var createHandler = require('github-webhook-handler')
var handler = createHandler({ path: '/webhooks', secret: 'myHashSecret' })
// 上面的 secret 保持和 GitHub 后台设置的一致
function run_cmd(cmd, args, callback) {
var spawn = require('child_process').spawn;
var child = spawn(cmd, args);
var resp = "";
child.stdout.on('data', function (buffer) { resp += buffer.toString(); });
child.stdout.on('end', function () { callback(resp) });
}
http.createServer(function (req, res) {
handler(req, res, function (err) {
res.statusCode = 404
res.end('no such location')
})
}).listen(3003,() =>{
console.log('WebHooks Listern at 3003');
})
handler.on('error', function (err) {
console.error('Error:', err.message)
})
//测试是否响应
handler.on('*', function (event) {
console.log('Received *', event.payload.action);
})
handler.on('push', function (event) {
console.log('Received a push event for %s to %s',
event.payload.repository.name,
event.payload.ref);
// 分支判断 如果是主干直接构建
if(event.payload.ref === 'refs/heads/master'){
//开始构建
console.info('WebHooks Listern at 3003');
//通过下面命令实现部署docker
run_cmd('sh', ['./deploy-dev.sh'], function(text){ console.log(text) });
}
})
2.创建 deploy-dev.sh (自动部署脚本)
#开始部署
echo Deploy Project
# 获取最新版代码
git pull
# 强制重新编译容器
docker-compose down
docker-compose up -d --force-recreate --build
3. 通过pm2启动
pm2 start webhooks.js --watch 启动