koa2调用github的登录调用
1、在koa里方法
const config = require('../../config/environment');
const sqlQuery = require('../../util/mysql-async');
const fetch = require('node-fetch');
const moment = require('moment');
const jwt = require('jsonwebtoken');
exports.githubOAuth = async(ctx) => {
const code = ctx.query.code;
let path = 'https://github.com/login/oauth/access_token';
const params = {
client_id: config.oAuth.github.client_id,
client_secret: config.oAuth.github.client_secret,
code: code
};
await fetch(path, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
})
.then(res => {
return res.text();
})
.then(body => {
const args = body.split('&');
let arg = args[0].split('=');
return arg[1];
})
.then(async(token) => {
const url = ' https://api.github.com/user?access_token=' + token;
await fetch(url)
.then(res => {
return res.json();
})
.then(async(res) => {
let userId = 0;
let selectGuest = await sqlQuery(`SELECT * FROM user WHERE role = 'GUEST' AND userName = ?`, [res.login]);
if (selectGuest.length > 0) {
userId = selectGuest[0].id;
await sqlQuery(`UPDATE user SET avatar = ?, email = ? WHERE id = ?`, [res.avatar_url, res.email, userId]);
} else {
let newGuest = {
userName: res.login,
avatar: res.avatar_url,
email: res.email,
role: 'GUEST',
createTime: moment().format('YYYY-MM-DD HH:mm:ss')
};
let insertGuest = await sqlQuery(`INSERT INTO user SET ?`, newGuest);
if (insertGuest.affectedRows > 0) {
userId = insertGuest.insertId;
}
}
if (userId > 0) {
ctx.session.user = res.login;
// 用户token
const userToken = {
name: res.login,
id: userId
};
// 签发token
const token = jwt.sign(userToken, config.tokenSecret, { expiresIn: '2h' });
ctx.body = {
success: 1,
token: token,
userName: res.login,
avatar: res.avatar_url,
message: ''
};
} else {
ctx.body = {
success: 0,
token: '',
message: 'GitHub授权登录失败'
};
}
});
})
.catch(e => {
console.log(e);
ctx.body = {
success: 0,
token: '',
message: 'GitHub授权登录失败'
};
});
};
2、nuxt的前端实现
axios.get(`/oauth/github/github_oauth?code=${this.$route.query.code}`).then(res => {
if (res.data.success === 1) {
let guest = {
userName: res.data.userName,
avatar: res.data.avatar
};
window.localStorage.setItem('GITHUB_LOGIN_TOKEN', res.data.token);
window.localStorage.setItem('GITHUB_LOGIN_GUEST', JSON.stringify(guest));
let redirectUrl = window.localStorage.getItem('GITHUB_LOGIN_REDIRECT_URL');
this.$router.push({ path: redirectUrl });
}
});
3、github的develop的setting
标签云
友情链接 申请友情链接
- 东方财富
- saucxs博客园
- weekly周报
- loveBook
- 前端博客
- 技术交流学习社区
- saucxs
- segmentfault
- saucxs的博客
- haorooms
- luckyscript
- 东方财富期货
- 峰云就她了
- binlive
- songEagle
- 且听风吟
- (TX)Heying Ye
- CG Online Judge
- Chris's Blog
- vueRouter
- 龙恩0707
- 鑫空间,鑫生活
- 木易杨
- MDN-js
- Cherry's Blog
- InterviewMap
- 安安哥的小戏台
- xiaojun1994-cat
- JavaScript-Garden
- junruchen-daily
- 秋天爱美丽
- web-summary-daily
- w3cplus-tb
- 潜行者m
- 于江水
- KieSun-git
- cnodejs
- aerminBlog
- fex_bd
- gwuhaolin-git
- Deboy's Blog
- react-china
- react.docschina
- Vuejs社区
- vuejsDoc
- cdnSocketIo
- shuaihuaCC
- colorize
- stazhu
- 前端学习
- IBM Dev社区
- linux运维笔记
- webpackDoc
- sayskyGithub
- 前端里
- 996.ICU
- electronjs
- CS-Notes
- mqyqingfengBlog
- beego官方
- 编码规范
- 阮一峰个人网站
- sessionstack
- damonareGoUp
- 咀嚼之味
- fe-interview
- xd-tayde/blog
- css-tricks
- ghmagical个人中心
- markyunp6
- hellogithub
- 霜序廿
- rin部落
- 建站素材
- 前端资源网
- CSS开发手册
- web技术交流
- 程新松个人网站
- wangEditor
- 小松博客
- 交流学习社区