Hugo博客添加密码

不要在主题文件夹下进行修改,但是要仿造主题文件夹的目录结构,我采用的是MemE

  1. ~blog/layouts下,新建两个文件夹分别是default/partials/,然后在default/下新建single.html,将主题文件夹中的single.html先复制过去:

    1
    2
    3
    4
    
    <!-- 主题文件夹下的原生single.html -->
    {{ define "main" }}
        {{ partial "pages/post.html" . }}
    {{ end }}
    
  2. partials/下新建password-protection.html,这是一个Hugo局部模板(Partial),复制如下代码:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    
    {{ if ( .Params.password | default "" ) }}
    <div class="post-password">
        <script>
            (function () {
                var correctPassword = "{{ .Params.password }}";
                var userPassword = prompt('Input Password');
                if (userPassword !== correctPassword) {
                    alert('Wrong Password');
                    if (history.length === 1) {
                        window.opener = null;
                        window.open('', '_self');
                        window.close();
                    } else {
                        history.back();
                    }
                }
            })();
        </script>
    </div>
    {{ end }}
    
  3. single.html中引用该模板,时机为显示正文之前:

    1
    2
    3
    4
    
    {{ define "main" }}
     {{ partial "password-protection.html" . }}  <!-- 传递当前文章上下文 -->
     {{ partial "pages/post.html" . }}
    {{ end }}
    

这样实现完成之后有一些弊端,前端加密的安全性先不考虑,我也只是不想有些内容被别人随便能看到。

于我而言最大的弊端是每次更新的时候你都需要重新输入密码,所以可以加入对LocalStorage的支持,验证成功之后就存在LocalStorage中,不需要重复输入:

  1. 支持LocalStorage版本:
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    
    {{ if .Params.password }}
    <div class="post-password">
        <script>
            (function () {
                // 获取之前保存的密码
                var savedPassword = localStorage.getItem("pp");
                var correctPassword = "{{ .Params.password }}";  // Hugo 渲染的密码
    
                // 如果密码已保存且正确,则跳过验证
                if (savedPassword === correctPassword) {
                    return;
                }
    
                // 否则进行密码验证
                var userPassword = prompt('请输入文章密码');
                if (userPassword === correctPassword) {
                    localStorage.setItem("pp", correctPassword);
                } else {
                    alert('密码错误');
                    if (history.length === 1) {
                        window.opener = null;
                        window.open('', '_self');
                        window.close();
                    } else {
                        history.back();
                    }
                }
            })();
        </script>
    </div>
    {{ end }}
    
updatedupdated2025-03-032025-03-03