hexo 接入 gitment 作为评论系统

hexo version: v6.4.1

1. 配置

配置文件在 themes/next.
基本配置如下,主要需要填写正确的github_user, github_repo, client_id, client_secret

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Gitment
# Introduction: https://imsun.net/posts/gitment-introduction/
gitment:
enable: true
mint: true # RECOMMEND, A mint on Gitment, to support count, language and proxy_gateway
count: true # Show comments count in post meta area
lazy: false # Comments lazy loading with a button
cleanly: true # Hide 'Powered by ...' on footer, and more
language: # Force language, or auto switch by theme
github_user: urzz # MUST HAVE, Your Github Username
github_repo: blog-comment # MUST HAVE, The name of the repo you use to store Gitment comments
client_id: *** # MUST HAVE, Github client id for the Gitment
client_secret: *** # EITHER this or proxy_gateway, Github access secret token for the Gitment
proxy_gateway: # Address of api proxy, See: https://github.com/aimingoo/intersect
redirect_protocol: # Protocol of redirect_uri with force_redirect_protocol when mint enabled

2. 使用

配置文件中设置的 github_repo,client_id, client_secret 需要去github上自行创建。(创建一个repo,和一个 OAuth Apps)

配置文件填写正确后,deploy就可以了,不过离真正使用还缺了一点初始化操作。

首先发布之后,需要进行初始化授权,访问博客文章页最下方,点击登入进行OAuth授权。
授权完成之后就可以初始化文章的评论了(每篇文章都需要自行点击初始化文章评论,因为每个文章都会有单独的issue)

3. 安全性

gitment 的使用其实是由一定风险的,因为OAuth需要的client_id、client_secret只能写死在配置文件里面,而这个配置信息会明文显示在html正文中的。

如下:themes/next/layout/_third-party/comments/gitment.swig

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<script type="text/javascript">
function renderGitment(){
var gitment = new {{CommentsClass}}({
id: window.location.pathname,
owner: '{{ theme.gitment.github_user }}',
repo: '{{ theme.gitment.github_repo }}',
{% if theme.gitment.mint %}
lang: "{{ theme.gitment.language }}" || navigator.language || navigator.systemLanguage || navigator.userLanguage,
{% endif %}
oauth: {
{% if theme.gitment.mint and theme.gitment.redirect_protocol %}
redirect_protocol: '{{ theme.gitment.redirect_protocol }}',
{% endif %}
{% if theme.gitment.mint and theme.gitment.proxy_gateway %}
proxy_gateway: '{{ theme.gitment.proxy_gateway }}',
{% else %}
client_secret: '{{ theme.gitment.client_secret }}',
{% endif %}
client_id: '{{ theme.gitment.client_id }}'
}});
gitment.render('gitment-container');
}

可以看到,当配置中的mint为true,以及proxy_gateway不为空时,client_secret就会被渲染到html中。

proxy_gateway 是一个api代理接口,如果配置了这个接口,访问github的access_token请求就会走这个proxy_gateway。

因此如果不想client_secret直接渲染出来,可以自行搭建一个api代理服务,然后将client_secret在代理服务中添加到接口请求中。

gitment的作者已经将这个代理服务开源了,在这里,可以稍作修改:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
app.post('*', upload.array(), (req, res) => {
// 添加下面这行,并协商自己申请的client_secret
req.body.client_secret='*******'
request.post({
url: 'https://github.com/login/oauth/access_token',
form: req.body,
headers: {
'Accept': 'application/json',
'User-Agent': 'gh-oauth-server',
},
}, (error, r, body) => {
if (!error) {
res.send(body)
} else {
res.json({ error })
}
})
})