Initial commit
This commit is contained in:
commit
ab1f8a2bf4
54
.github/workflows/docker-image-amd64.yml
vendored
Normal file
54
.github/workflows/docker-image-amd64.yml
vendored
Normal file
@ -0,0 +1,54 @@
|
|||||||
|
name: Publish Docker image (amd64)
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- '*'
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
name:
|
||||||
|
description: 'reason'
|
||||||
|
required: false
|
||||||
|
jobs:
|
||||||
|
push_to_registries:
|
||||||
|
name: Push Docker image to multiple registries
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
packages: write
|
||||||
|
contents: read
|
||||||
|
steps:
|
||||||
|
- name: Check out the repo
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Save version info
|
||||||
|
run: |
|
||||||
|
git describe --tags > VERSION
|
||||||
|
|
||||||
|
- name: Log in to Docker Hub
|
||||||
|
uses: docker/login-action@v2
|
||||||
|
with:
|
||||||
|
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||||
|
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Log in to the Container registry
|
||||||
|
uses: docker/login-action@v2
|
||||||
|
with:
|
||||||
|
registry: ghcr.io
|
||||||
|
username: ${{ github.actor }}
|
||||||
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Extract metadata (tags, labels) for Docker
|
||||||
|
id: meta
|
||||||
|
uses: docker/metadata-action@v4
|
||||||
|
with:
|
||||||
|
images: |
|
||||||
|
justsong/gin-template
|
||||||
|
ghcr.io/${{ github.repository }}
|
||||||
|
|
||||||
|
- name: Build and push Docker images
|
||||||
|
uses: docker/build-push-action@v3
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
push: true
|
||||||
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta.outputs.labels }}
|
61
.github/workflows/docker-image-arm64.yml
vendored
Normal file
61
.github/workflows/docker-image-arm64.yml
vendored
Normal file
@ -0,0 +1,61 @@
|
|||||||
|
name: Publish Docker image (arm64)
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- '*'
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
name:
|
||||||
|
description: 'reason'
|
||||||
|
required: false
|
||||||
|
jobs:
|
||||||
|
push_to_registries:
|
||||||
|
name: Push Docker image to multiple registries
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
packages: write
|
||||||
|
contents: read
|
||||||
|
steps:
|
||||||
|
- name: Check out the repo
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Save version info
|
||||||
|
run: |
|
||||||
|
git describe --tags > VERSION
|
||||||
|
|
||||||
|
- name: Set up QEMU
|
||||||
|
uses: docker/setup-qemu-action@v2
|
||||||
|
|
||||||
|
- name: Set up Docker Buildx
|
||||||
|
uses: docker/setup-buildx-action@v2
|
||||||
|
|
||||||
|
- name: Log in to Docker Hub
|
||||||
|
uses: docker/login-action@v2
|
||||||
|
with:
|
||||||
|
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||||
|
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Log in to the Container registry
|
||||||
|
uses: docker/login-action@v2
|
||||||
|
with:
|
||||||
|
registry: ghcr.io
|
||||||
|
username: ${{ github.actor }}
|
||||||
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Extract metadata (tags, labels) for Docker
|
||||||
|
id: meta
|
||||||
|
uses: docker/metadata-action@v4
|
||||||
|
with:
|
||||||
|
images: |
|
||||||
|
justsong/gin-template
|
||||||
|
ghcr.io/${{ github.repository }}
|
||||||
|
|
||||||
|
- name: Build and push Docker images
|
||||||
|
uses: docker/build-push-action@v3
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
platforms: linux/amd64,linux/arm64
|
||||||
|
push: true
|
||||||
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta.outputs.labels }}
|
29
.github/workflows/github-pages.yml
vendored
Normal file
29
.github/workflows/github-pages.yml
vendored
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
name: Build GitHub Pages
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
name:
|
||||||
|
description: 'Reason'
|
||||||
|
required: false
|
||||||
|
jobs:
|
||||||
|
build-and-deploy:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout 🛎️
|
||||||
|
uses: actions/checkout@v2 # If you're using actions/checkout@v2 you must set persist-credentials to false in most cases for the deployment to work correctly.
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
|
- name: Install and Build 🔧 # This example project is built using npm and outputs the result to the 'build' folder. Replace with the commands required to build your project, or remove this step entirely if your site is pre-built.
|
||||||
|
env:
|
||||||
|
CI: ""
|
||||||
|
run: |
|
||||||
|
cd web
|
||||||
|
npm install
|
||||||
|
npm run build
|
||||||
|
|
||||||
|
- name: Deploy 🚀
|
||||||
|
uses: JamesIves/github-pages-deploy-action@releases/v3
|
||||||
|
with:
|
||||||
|
ACCESS_TOKEN: ${{ secrets.ACCESS_TOKEN }}
|
||||||
|
BRANCH: gh-pages # The branch the action should deploy to.
|
||||||
|
FOLDER: web/build # The folder the action should deploy.
|
49
.github/workflows/linux-release.yml
vendored
Normal file
49
.github/workflows/linux-release.yml
vendored
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
name: Linux Release
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- '*'
|
||||||
|
jobs:
|
||||||
|
release:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
- uses: actions/setup-node@v3
|
||||||
|
with:
|
||||||
|
node-version: 16
|
||||||
|
- name: Build Frontend
|
||||||
|
env:
|
||||||
|
CI: ""
|
||||||
|
run: |
|
||||||
|
cd web
|
||||||
|
npm install
|
||||||
|
REACT_APP_VERSION=$(git describe --tags) npm run build
|
||||||
|
cd ..
|
||||||
|
- name: Set up Go
|
||||||
|
uses: actions/setup-go@v3
|
||||||
|
with:
|
||||||
|
go-version: '>=1.18.0'
|
||||||
|
- name: Build Backend (amd64)
|
||||||
|
run: |
|
||||||
|
go mod download
|
||||||
|
go build -ldflags "-s -w -X 'gin-template/common.Version=$(git describe --tags)' -extldflags '-static'" -o gin-template
|
||||||
|
|
||||||
|
- name: Build Backend (arm64)
|
||||||
|
run: |
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install gcc-aarch64-linux-gnu
|
||||||
|
CC=aarch64-linux-gnu-gcc CGO_ENABLED=1 GOOS=linux GOARCH=arm64 go build -ldflags "-s -w -X 'gin-template/common.Version=$(git describe --tags)' -extldflags '-static'" -o gin-template-arm64
|
||||||
|
|
||||||
|
- name: Release
|
||||||
|
uses: softprops/action-gh-release@v1
|
||||||
|
if: startsWith(github.ref, 'refs/tags/')
|
||||||
|
with:
|
||||||
|
files: |
|
||||||
|
gin-template
|
||||||
|
gin-template-arm64
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
40
.github/workflows/macos-release.yml
vendored
Normal file
40
.github/workflows/macos-release.yml
vendored
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
name: macOS Release
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- '*'
|
||||||
|
jobs:
|
||||||
|
release:
|
||||||
|
runs-on: macos-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
- uses: actions/setup-node@v3
|
||||||
|
with:
|
||||||
|
node-version: 16
|
||||||
|
- name: Build Frontend
|
||||||
|
env:
|
||||||
|
CI: ""
|
||||||
|
run: |
|
||||||
|
cd web
|
||||||
|
npm install
|
||||||
|
REACT_APP_VERSION=$(git describe --tags) npm run build
|
||||||
|
cd ..
|
||||||
|
- name: Set up Go
|
||||||
|
uses: actions/setup-go@v3
|
||||||
|
with:
|
||||||
|
go-version: '>=1.18.0'
|
||||||
|
- name: Build Backend
|
||||||
|
run: |
|
||||||
|
go mod download
|
||||||
|
go build -ldflags "-X 'gin-template/common.Version=$(git describe --tags)'" -o gin-template-macos
|
||||||
|
- name: Release
|
||||||
|
uses: softprops/action-gh-release@v1
|
||||||
|
if: startsWith(github.ref, 'refs/tags/')
|
||||||
|
with:
|
||||||
|
files: gin-template-macos
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
43
.github/workflows/windows-release.yml
vendored
Normal file
43
.github/workflows/windows-release.yml
vendored
Normal file
@ -0,0 +1,43 @@
|
|||||||
|
name: Windows Release
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- '*'
|
||||||
|
jobs:
|
||||||
|
release:
|
||||||
|
runs-on: windows-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
shell: bash
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
- uses: actions/setup-node@v3
|
||||||
|
with:
|
||||||
|
node-version: 16
|
||||||
|
- name: Build Frontend
|
||||||
|
env:
|
||||||
|
CI: ""
|
||||||
|
run: |
|
||||||
|
cd web
|
||||||
|
npm install
|
||||||
|
REACT_APP_VERSION=$(git describe --tags) npm run build
|
||||||
|
cd ..
|
||||||
|
- name: Set up Go
|
||||||
|
uses: actions/setup-go@v3
|
||||||
|
with:
|
||||||
|
go-version: '>=1.18.0'
|
||||||
|
- name: Build Backend
|
||||||
|
run: |
|
||||||
|
go mod download
|
||||||
|
go build -ldflags "-s -w -X 'gin-template/common.Version=$(git describe --tags)'" -o gin-template.exe
|
||||||
|
- name: Release
|
||||||
|
uses: softprops/action-gh-release@v1
|
||||||
|
if: startsWith(github.ref, 'refs/tags/')
|
||||||
|
with:
|
||||||
|
files: gin-template.exe
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
6
.gitignore
vendored
Normal file
6
.gitignore
vendored
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
.idea
|
||||||
|
.vscode
|
||||||
|
upload
|
||||||
|
*.exe
|
||||||
|
*.db
|
||||||
|
build
|
31
Dockerfile
Normal file
31
Dockerfile
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
FROM node:16 as builder
|
||||||
|
|
||||||
|
WORKDIR /build
|
||||||
|
COPY ./web .
|
||||||
|
COPY ./VERSION .
|
||||||
|
RUN npm install
|
||||||
|
RUN REACT_APP_VERSION=$(cat VERSION) npm run build
|
||||||
|
|
||||||
|
FROM golang AS builder2
|
||||||
|
|
||||||
|
ENV GO111MODULE=on \
|
||||||
|
CGO_ENABLED=1 \
|
||||||
|
GOOS=linux
|
||||||
|
|
||||||
|
WORKDIR /build
|
||||||
|
COPY . .
|
||||||
|
COPY --from=builder /build/build ./web/build
|
||||||
|
RUN go mod download
|
||||||
|
RUN go build -ldflags "-s -w -X 'gin-template/common.Version=$(cat VERSION)' -extldflags '-static'" -o gin-template
|
||||||
|
|
||||||
|
FROM alpine
|
||||||
|
|
||||||
|
RUN apk update \
|
||||||
|
&& apk upgrade \
|
||||||
|
&& apk add --no-cache ca-certificates tzdata \
|
||||||
|
&& update-ca-certificates 2>/dev/null || true
|
||||||
|
ENV PORT=3000
|
||||||
|
COPY --from=builder2 /build/gin-template /
|
||||||
|
EXPOSE 3000
|
||||||
|
WORKDIR /data
|
||||||
|
ENTRYPOINT ["/gin-template"]
|
21
LICENSE
Normal file
21
LICENSE
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2022 JustSong
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
95
README.en.md
Normal file
95
README.en.md
Normal file
@ -0,0 +1,95 @@
|
|||||||
|
<p align="right">
|
||||||
|
<a href="./README.md">中文</a> | <strong>English</strong>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://github.com/songquanpeng/gin-template"><img src="https://raw.githubusercontent.com/songquanpeng/gin-template/main/web/public/logo.png" width="150" height="150" alt="gin-template logo"></a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div align="center">
|
||||||
|
|
||||||
|
# Gin Template
|
||||||
|
|
||||||
|
_✨ Template for Gin & React projects ✨_
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://raw.githubusercontent.com/songquanpeng/gin-template/main/LICENSE">
|
||||||
|
<img src="https://img.shields.io/github/license/songquanpeng/gin-template?color=brightgreen" alt="license">
|
||||||
|
</a>
|
||||||
|
<a href="https://github.com/songquanpeng/gin-template/releases/latest">
|
||||||
|
<img src="https://img.shields.io/github/v/release/songquanpeng/gin-template?color=brightgreen&include_prereleases" alt="release">
|
||||||
|
</a>
|
||||||
|
<a href="https://github.com/songquanpeng/gin-template/releases/latest">
|
||||||
|
<img src="https://img.shields.io/github/downloads/songquanpeng/gin-template/total?color=brightgreen&include_prereleases" alt="release">
|
||||||
|
</a>
|
||||||
|
<a href="https://goreportcard.com/report/github.com/songquanpeng/go-file">
|
||||||
|
<img src="https://goreportcard.com/badge/github.com/songquanpeng/gin-template" alt="GoReportCard">
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://github.com/songquanpeng/gin-template/releases">Download</a>
|
||||||
|
·
|
||||||
|
<a href="https://github.com/songquanpeng/gin-template/blob/main/README.en.md#deployment">Tutorial</a>
|
||||||
|
·
|
||||||
|
<a href="https://github.com/songquanpeng/gin-template/issues">Feedback</a>
|
||||||
|
·
|
||||||
|
<a href="https://gin-template.vercel.app/">Demo</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
## Features
|
||||||
|
+ [x] Built-in user management.
|
||||||
|
+ [x] Built-in file management.
|
||||||
|
+ [x] [GitHub OAuth](https://github.com/settings/applications/new).
|
||||||
|
+ [x] WeChat official account authorization (need [wechat-server](https://github.com/songquanpeng/wechat-server)).
|
||||||
|
+ [x] Email verification & password reset.
|
||||||
|
+ [x] Request rate limiting.
|
||||||
|
+ [x] Static files caching.
|
||||||
|
+ [x] Mobile friendly UI.
|
||||||
|
+ [x] Token based authorization.
|
||||||
|
+ [x] Use GitHub Actions to build releases & Docker images.
|
||||||
|
+ [x] Cloudflare Turnstile user validation.
|
||||||
|
|
||||||
|
## Deployment
|
||||||
|
### Manual deployment
|
||||||
|
1. Download built binary from [GitHub Releases](https://github.com/songquanpeng/gin-template/releases/latest) or build from source:
|
||||||
|
```shell
|
||||||
|
git clone https://github.com/songquanpeng/gin-template.git
|
||||||
|
go mod download
|
||||||
|
go build -ldflags "-s -w" -o gin-template
|
||||||
|
````
|
||||||
|
2. Run it:
|
||||||
|
```shell
|
||||||
|
chmod u+x gin-template
|
||||||
|
./gin-template --port 3000 --log-dir ./logs
|
||||||
|
```
|
||||||
|
3. Visit [http://localhost:3000/](http://localhost:3000/) and login. The username for the initial account is `root` and the password is `123456`.
|
||||||
|
|
||||||
|
### Deploy with Docker
|
||||||
|
Execute: `docker run -d --restart always -p 3000:3000 -v /home/ubuntu/data/gin-template:/data -v /etc/ssl/certs:/etc/ssl/certs:ro justsong/gin-template`
|
||||||
|
|
||||||
|
Data will be saved in `/home/ubuntu/data/gin-template`.
|
||||||
|
|
||||||
|
## Configurations
|
||||||
|
The system works out of the box.
|
||||||
|
|
||||||
|
You can configure the system by set environment variables or specify command line arguments.
|
||||||
|
|
||||||
|
After the system starts, use `root` user to log in to the system and do further configuration.
|
||||||
|
|
||||||
|
### Environment Variables
|
||||||
|
1. `REDIS_CONN_STRING`: when set, Redis will be used as the storage for request rate limitation instead of memory storage.
|
||||||
|
+ Example: `REDIS_CONN_STRING=redis://default:redispw@localhost:49153`
|
||||||
|
2. `SESSION_SECRET`: when set, a fixed session key will be used so that the logged-in users' cookie remains valid across system reboots.
|
||||||
|
+ Example: `SESSION_SECRET=random_string`
|
||||||
|
3. `SQL_DSN`: when set, the target SQL database will be used instead of SQLite.
|
||||||
|
+ Example: `SQL_DSN=root:123456@tcp(localhost:3306)/gin-template`
|
||||||
|
|
||||||
|
### Command line Arguments
|
||||||
|
1. `--port <port_number>`: specify the port number, the default value is `3000`.
|
||||||
|
+ Example: `--port 3000`
|
||||||
|
2. `--log-dir <log_dir>`: specify the log dir, if not set, the log won't be saved.
|
||||||
|
+ Example: `--log-dir ./logs`
|
||||||
|
3. `--version`: print the version and exit.
|
97
README.md
Normal file
97
README.md
Normal file
@ -0,0 +1,97 @@
|
|||||||
|
<p align="right">
|
||||||
|
<strong>中文</strong> | <a href="./README.en.md">English</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://github.com/songquanpeng/gin-template"><img src="https://raw.githubusercontent.com/songquanpeng/gin-template/main/web/public/logo.png" width="150" height="150" alt="gin-template logo"></a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div align="center">
|
||||||
|
|
||||||
|
# Gin 项目模板
|
||||||
|
|
||||||
|
_✨ 用于 Gin & React 项目的模板 ✨_
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://raw.githubusercontent.com/songquanpeng/gin-template/main/LICENSE">
|
||||||
|
<img src="https://img.shields.io/github/license/songquanpeng/gin-template?color=brightgreen" alt="license">
|
||||||
|
</a>
|
||||||
|
<a href="https://github.com/songquanpeng/gin-template/releases/latest">
|
||||||
|
<img src="https://img.shields.io/github/v/release/songquanpeng/gin-template?color=brightgreen&include_prereleases" alt="release">
|
||||||
|
</a>
|
||||||
|
<a href="https://github.com/songquanpeng/gin-template/releases/latest">
|
||||||
|
<img src="https://img.shields.io/github/downloads/songquanpeng/gin-template/total?color=brightgreen&include_prereleases" alt="release">
|
||||||
|
</a>
|
||||||
|
<a href="https://goreportcard.com/report/github.com/songquanpeng/gin-template">
|
||||||
|
<img src="https://goreportcard.com/badge/github.com/songquanpeng/gin-template" alt="GoReportCard">
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://github.com/songquanpeng/gin-template/releases">程序下载</a>
|
||||||
|
·
|
||||||
|
<a href="https://github.com/songquanpeng/gin-template#部署">部署教程</a>
|
||||||
|
·
|
||||||
|
<a href="https://github.com/songquanpeng/gin-template/issues">意见反馈</a>
|
||||||
|
·
|
||||||
|
<a href="https://gin-template.vercel.app/">在线演示</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
## 功能
|
||||||
|
+ [x] 内置用户管理
|
||||||
|
+ [x] 内置文件管理
|
||||||
|
+ [x] [GitHub 开放授权](https://github.com/settings/applications/new)
|
||||||
|
+ [x] 微信公众号授权(需要 [wechat-server](https://github.com/songquanpeng/wechat-server))
|
||||||
|
+ [x] 邮箱验证以及通过邮件进行密码重置
|
||||||
|
+ [x] 请求频率限制
|
||||||
|
+ [x] 静态文件缓存
|
||||||
|
+ [x] 移动端适配
|
||||||
|
+ [x] 基于令牌的鉴权
|
||||||
|
+ [x] 使用 GitHub Actions 自动打包可执行文件与 Docker 镜像
|
||||||
|
+ [x] Cloudflare Turnstile 用户校验
|
||||||
|
|
||||||
|
## 部署
|
||||||
|
### 手动部署
|
||||||
|
1. 从 [GitHub Releases](https://github.com/songquanpeng/gin-template/releases/latest) 下载可执行文件或者从源码编译:
|
||||||
|
```shell
|
||||||
|
git clone https://github.com/songquanpeng/gin-template.git
|
||||||
|
go mod download
|
||||||
|
go build -ldflags "-s -w" -o gin-template
|
||||||
|
````
|
||||||
|
2. 运行:
|
||||||
|
```shell
|
||||||
|
chmod u+x gin-template
|
||||||
|
./gin-template --port 3000 --log-dir ./logs
|
||||||
|
```
|
||||||
|
3. 访问 [http://localhost:3000/](http://localhost:3000/) 并登录。初始账号用户名为 `root`,密码为 `123456`。
|
||||||
|
|
||||||
|
更加详细的部署教程[参见此处](https://iamazing.cn/page/how-to-deploy-a-website)。
|
||||||
|
|
||||||
|
### 基于 Docker 进行部署
|
||||||
|
执行:`docker run -d --restart always -p 3000:3000 -v /home/ubuntu/data/gin-template:/data -v /etc/ssl/certs:/etc/ssl/certs:ro justsong/gin-template`
|
||||||
|
|
||||||
|
数据将会保存在宿主机的 `/home/ubuntu/data/gin-template` 目录。
|
||||||
|
|
||||||
|
## 配置
|
||||||
|
系统本身开箱即用。
|
||||||
|
|
||||||
|
你可以通过设置环境变量或者命令行参数进行配置。
|
||||||
|
|
||||||
|
等到系统启动后,使用 `root` 用户登录系统并做进一步的配置。
|
||||||
|
|
||||||
|
### 环境变量
|
||||||
|
1. `REDIS_CONN_STRING`:设置之后将使用 Redis 作为请求频率限制的存储,而非使用内存存储。
|
||||||
|
+ 例子:`REDIS_CONN_STRING=redis://default:redispw@localhost:49153`
|
||||||
|
2. `SESSION_SECRET`:设置之后将使用固定的会话密钥,这样系统重新启动后已登录用户的 cookie 将依旧有效。
|
||||||
|
+ 例子:`SESSION_SECRET=random_string`
|
||||||
|
3. `SQL_DSN`:设置之后将使用指定数据库而非 SQLite。
|
||||||
|
+ 例子:`SQL_DSN=root:123456@tcp(localhost:3306)/gin-template`
|
||||||
|
|
||||||
|
### 命令行参数
|
||||||
|
1. `--port <port_number>`: 指定服务器监听的端口号,默认为 `3000`。
|
||||||
|
+ 例子:`--port 3000`
|
||||||
|
2. `--log-dir <log_dir>`: 指定日志文件夹,如果没有设置,日志将不会被保存。
|
||||||
|
+ 例子:`--log-dir ./logs`
|
||||||
|
3. `--version`: 打印系统版本号并退出。
|
85
common/constants.go
Normal file
85
common/constants.go
Normal file
@ -0,0 +1,85 @@
|
|||||||
|
package common
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
var StartTime = time.Now().Unix() // unit: second
|
||||||
|
var Version = "v0.0.0" // this hard coding will be replaced automatically when building, no need to manually change
|
||||||
|
var SystemName = "项目模板"
|
||||||
|
var ServerAddress = "http://localhost:3000"
|
||||||
|
var Footer = ""
|
||||||
|
|
||||||
|
// Any options with "Secret", "Token" in its key won't be return by GetOptions
|
||||||
|
|
||||||
|
var SessionSecret = uuid.New().String()
|
||||||
|
var SQLitePath = "gin-template.db"
|
||||||
|
|
||||||
|
var OptionMap map[string]string
|
||||||
|
var OptionMapRWMutex sync.RWMutex
|
||||||
|
|
||||||
|
var ItemsPerPage = 10
|
||||||
|
|
||||||
|
var PasswordLoginEnabled = true
|
||||||
|
var PasswordRegisterEnabled = true
|
||||||
|
var EmailVerificationEnabled = false
|
||||||
|
var GitHubOAuthEnabled = false
|
||||||
|
var WeChatAuthEnabled = false
|
||||||
|
var TurnstileCheckEnabled = false
|
||||||
|
var RegisterEnabled = true
|
||||||
|
|
||||||
|
var SMTPServer = ""
|
||||||
|
var SMTPAccount = ""
|
||||||
|
var SMTPToken = ""
|
||||||
|
|
||||||
|
var GitHubClientId = ""
|
||||||
|
var GitHubClientSecret = ""
|
||||||
|
|
||||||
|
var WeChatServerAddress = ""
|
||||||
|
var WeChatServerToken = ""
|
||||||
|
var WeChatAccountQRCodeImageURL = ""
|
||||||
|
|
||||||
|
var TurnstileSiteKey = ""
|
||||||
|
var TurnstileSecretKey = ""
|
||||||
|
|
||||||
|
const (
|
||||||
|
RoleGuestUser = 0
|
||||||
|
RoleCommonUser = 1
|
||||||
|
RoleAdminUser = 10
|
||||||
|
RoleRootUser = 100
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
FileUploadPermission = RoleGuestUser
|
||||||
|
FileDownloadPermission = RoleGuestUser
|
||||||
|
ImageUploadPermission = RoleGuestUser
|
||||||
|
ImageDownloadPermission = RoleGuestUser
|
||||||
|
)
|
||||||
|
|
||||||
|
// All duration's unit is seconds
|
||||||
|
// Shouldn't larger then RateLimitKeyExpirationDuration
|
||||||
|
var (
|
||||||
|
GlobalApiRateLimitNum = 60
|
||||||
|
GlobalApiRateLimitDuration int64 = 3 * 60
|
||||||
|
|
||||||
|
GlobalWebRateLimitNum = 60
|
||||||
|
GlobalWebRateLimitDuration int64 = 3 * 60
|
||||||
|
|
||||||
|
UploadRateLimitNum = 10
|
||||||
|
UploadRateLimitDuration int64 = 60
|
||||||
|
|
||||||
|
DownloadRateLimitNum = 10
|
||||||
|
DownloadRateLimitDuration int64 = 60
|
||||||
|
|
||||||
|
CriticalRateLimitNum = 20
|
||||||
|
CriticalRateLimitDuration int64 = 20 * 60
|
||||||
|
)
|
||||||
|
|
||||||
|
var RateLimitKeyExpirationDuration = 20 * time.Minute
|
||||||
|
|
||||||
|
const (
|
||||||
|
UserStatusEnabled = 1 // don't use 0, 0 is the default value!
|
||||||
|
UserStatusDisabled = 2 // also don't use 0
|
||||||
|
)
|
14
common/crypto.go
Normal file
14
common/crypto.go
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
package common
|
||||||
|
|
||||||
|
import "golang.org/x/crypto/bcrypt"
|
||||||
|
|
||||||
|
func Password2Hash(password string) (string, error) {
|
||||||
|
passwordBytes := []byte(password)
|
||||||
|
hashedPassword, err := bcrypt.GenerateFromPassword(passwordBytes, bcrypt.DefaultCost)
|
||||||
|
return string(hashedPassword), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func ValidatePasswordAndHash(password string, hash string) bool {
|
||||||
|
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
|
||||||
|
return err == nil
|
||||||
|
}
|
14
common/email.go
Normal file
14
common/email.go
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
package common
|
||||||
|
|
||||||
|
import "gopkg.in/gomail.v2"
|
||||||
|
|
||||||
|
func SendEmail(subject string, receiver string, content string) error {
|
||||||
|
m := gomail.NewMessage()
|
||||||
|
m.SetHeader("From", SMTPAccount)
|
||||||
|
m.SetHeader("To", receiver)
|
||||||
|
m.SetHeader("Subject", subject)
|
||||||
|
m.SetBody("text/html", content)
|
||||||
|
d := gomail.NewDialer(SMTPServer, 587, SMTPAccount, SMTPToken)
|
||||||
|
err := d.DialAndSend(m)
|
||||||
|
return err
|
||||||
|
}
|
32
common/embed-file-system.go
Normal file
32
common/embed-file-system.go
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
package common
|
||||||
|
|
||||||
|
import (
|
||||||
|
"embed"
|
||||||
|
"github.com/gin-contrib/static"
|
||||||
|
"io/fs"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Credit: https://github.com/gin-contrib/static/issues/19
|
||||||
|
|
||||||
|
type embedFileSystem struct {
|
||||||
|
http.FileSystem
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e embedFileSystem) Exists(prefix string, path string) bool {
|
||||||
|
_, err := e.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func EmbedFolder(fsEmbed embed.FS, targetPath string) static.ServeFileSystem {
|
||||||
|
efs, err := fs.Sub(fsEmbed, targetPath)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return embedFileSystem{
|
||||||
|
FileSystem: http.FS(efs),
|
||||||
|
}
|
||||||
|
}
|
78
common/init.go
Normal file
78
common/init.go
Normal file
@ -0,0 +1,78 @@
|
|||||||
|
package common
|
||||||
|
|
||||||
|
import (
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
Port = flag.Int("port", 3000, "the listening port")
|
||||||
|
PrintVersion = flag.Bool("version", false, "print version and exit")
|
||||||
|
LogDir = flag.String("log-dir", "", "specify the log directory")
|
||||||
|
//Host = flag.String("host", "localhost", "the server's ip address or domain")
|
||||||
|
//Path = flag.String("path", "", "specify a local path to public")
|
||||||
|
//VideoPath = flag.String("video", "", "specify a video folder to public")
|
||||||
|
//NoBrowser = flag.Bool("no-browser", false, "open browser or not")
|
||||||
|
)
|
||||||
|
|
||||||
|
// UploadPath Maybe override by ENV_VAR
|
||||||
|
var UploadPath = "upload"
|
||||||
|
|
||||||
|
//var ExplorerRootPath = UploadPath
|
||||||
|
//var ImageUploadPath = "upload/images"
|
||||||
|
//var VideoServePath = "upload"
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
flag.Parse()
|
||||||
|
|
||||||
|
if *PrintVersion {
|
||||||
|
fmt.Println(Version)
|
||||||
|
os.Exit(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
if os.Getenv("SESSION_SECRET") != "" {
|
||||||
|
SessionSecret = os.Getenv("SESSION_SECRET")
|
||||||
|
}
|
||||||
|
if os.Getenv("SQLITE_PATH") != "" {
|
||||||
|
SQLitePath = os.Getenv("SQLITE_PATH")
|
||||||
|
}
|
||||||
|
if os.Getenv("UPLOAD_PATH") != "" {
|
||||||
|
UploadPath = os.Getenv("UPLOAD_PATH")
|
||||||
|
//ExplorerRootPath = UploadPath
|
||||||
|
//ImageUploadPath = path.Join(UploadPath, "images")
|
||||||
|
//VideoServePath = UploadPath
|
||||||
|
}
|
||||||
|
if *LogDir != "" {
|
||||||
|
var err error
|
||||||
|
*LogDir, err = filepath.Abs(*LogDir)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(*LogDir); os.IsNotExist(err) {
|
||||||
|
err = os.Mkdir(*LogDir, 0777)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//if *Path != "" {
|
||||||
|
// ExplorerRootPath = *Path
|
||||||
|
//}
|
||||||
|
//if *VideoPath != "" {
|
||||||
|
// VideoServePath = *VideoPath
|
||||||
|
//}
|
||||||
|
//
|
||||||
|
//ExplorerRootPath, _ = filepath.Abs(ExplorerRootPath)
|
||||||
|
//VideoServePath, _ = filepath.Abs(VideoServePath)
|
||||||
|
//ImageUploadPath, _ = filepath.Abs(ImageUploadPath)
|
||||||
|
//
|
||||||
|
if _, err := os.Stat(UploadPath); os.IsNotExist(err) {
|
||||||
|
_ = os.Mkdir(UploadPath, 0777)
|
||||||
|
}
|
||||||
|
//if _, err := os.Stat(ImageUploadPath); os.IsNotExist(err) {
|
||||||
|
// _ = os.Mkdir(ImageUploadPath, 0777)
|
||||||
|
//}
|
||||||
|
}
|
44
common/logger.go
Normal file
44
common/logger.go
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
package common
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func SetupGinLog() {
|
||||||
|
if *LogDir != "" {
|
||||||
|
commonLogPath := filepath.Join(*LogDir, "common.log")
|
||||||
|
errorLogPath := filepath.Join(*LogDir, "error.log")
|
||||||
|
commonFd, err := os.OpenFile(commonLogPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal("failed to open log file")
|
||||||
|
}
|
||||||
|
errorFd, err := os.OpenFile(errorLogPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal("failed to open log file")
|
||||||
|
}
|
||||||
|
gin.DefaultWriter = io.MultiWriter(os.Stdout, commonFd)
|
||||||
|
gin.DefaultErrorWriter = io.MultiWriter(os.Stderr, errorFd)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func SysLog(s string) {
|
||||||
|
t := time.Now()
|
||||||
|
_, _ = fmt.Fprintf(gin.DefaultWriter, "[SYS] %v | %s \n", t.Format("2006/01/02 - 15:04:05"), s)
|
||||||
|
}
|
||||||
|
|
||||||
|
func SysError(s string) {
|
||||||
|
t := time.Now()
|
||||||
|
_, _ = fmt.Fprintf(gin.DefaultErrorWriter, "[SYS] %v | %s \n", t.Format("2006/01/02 - 15:04:05"), s)
|
||||||
|
}
|
||||||
|
|
||||||
|
func FatalLog(v ...any) {
|
||||||
|
t := time.Now()
|
||||||
|
_, _ = fmt.Fprintf(gin.DefaultErrorWriter, "[FATAL] %v | %v \n", t.Format("2006/01/02 - 15:04:05"), v)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
70
common/rate-limit.go
Normal file
70
common/rate-limit.go
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
package common
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type InMemoryRateLimiter struct {
|
||||||
|
store map[string]*[]int64
|
||||||
|
mutex sync.Mutex
|
||||||
|
expirationDuration time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *InMemoryRateLimiter) Init(expirationDuration time.Duration) {
|
||||||
|
if l.store == nil {
|
||||||
|
l.mutex.Lock()
|
||||||
|
if l.store == nil {
|
||||||
|
l.store = make(map[string]*[]int64)
|
||||||
|
l.expirationDuration = expirationDuration
|
||||||
|
if expirationDuration > 0 {
|
||||||
|
go l.clearExpiredItems()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
l.mutex.Unlock()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *InMemoryRateLimiter) clearExpiredItems() {
|
||||||
|
for {
|
||||||
|
time.Sleep(l.expirationDuration)
|
||||||
|
l.mutex.Lock()
|
||||||
|
now := time.Now().Unix()
|
||||||
|
for key := range l.store {
|
||||||
|
queue := l.store[key]
|
||||||
|
size := len(*queue)
|
||||||
|
if size == 0 || now-(*queue)[size-1] > int64(l.expirationDuration.Seconds()) {
|
||||||
|
delete(l.store, key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
l.mutex.Unlock()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request parameter duration's unit is seconds
|
||||||
|
func (l *InMemoryRateLimiter) Request(key string, maxRequestNum int, duration int64) bool {
|
||||||
|
l.mutex.Lock()
|
||||||
|
defer l.mutex.Unlock()
|
||||||
|
// [old <-- new]
|
||||||
|
queue, ok := l.store[key]
|
||||||
|
now := time.Now().Unix()
|
||||||
|
if ok {
|
||||||
|
if len(*queue) < maxRequestNum {
|
||||||
|
*queue = append(*queue, now)
|
||||||
|
return true
|
||||||
|
} else {
|
||||||
|
if now-(*queue)[0] >= duration {
|
||||||
|
*queue = (*queue)[1:]
|
||||||
|
*queue = append(*queue, now)
|
||||||
|
return true
|
||||||
|
} else {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
s := make([]int64, 0, maxRequestNum)
|
||||||
|
l.store[key] = &s
|
||||||
|
*(l.store[key]) = append(*(l.store[key]), now)
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
39
common/redis.go
Normal file
39
common/redis.go
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
package common
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"github.com/go-redis/redis/v8"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
var RDB *redis.Client
|
||||||
|
var RedisEnabled = true
|
||||||
|
|
||||||
|
// InitRedisClient This function is called after init()
|
||||||
|
func InitRedisClient() (err error) {
|
||||||
|
if os.Getenv("REDIS_CONN_STRING") == "" {
|
||||||
|
RedisEnabled = false
|
||||||
|
SysLog("REDIS_CONN_STRING not set, Redis is not enabled")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
opt, err := redis.ParseURL(os.Getenv("REDIS_CONN_STRING"))
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
RDB = redis.NewClient(opt)
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
_, err = RDB.Ping(ctx).Result()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func ParseRedisOption() *redis.Options {
|
||||||
|
opt, err := redis.ParseURL(os.Getenv("REDIS_CONN_STRING"))
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return opt
|
||||||
|
}
|
141
common/utils.go
Normal file
141
common/utils.go
Normal file
@ -0,0 +1,141 @@
|
|||||||
|
package common
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"html/template"
|
||||||
|
"log"
|
||||||
|
"net"
|
||||||
|
"os/exec"
|
||||||
|
"runtime"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
func OpenBrowser(url string) {
|
||||||
|
var err error
|
||||||
|
|
||||||
|
switch runtime.GOOS {
|
||||||
|
case "linux":
|
||||||
|
err = exec.Command("xdg-open", url).Start()
|
||||||
|
case "windows":
|
||||||
|
err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
|
||||||
|
case "darwin":
|
||||||
|
err = exec.Command("open", url).Start()
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
log.Println(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetIp() (ip string) {
|
||||||
|
ips, err := net.InterfaceAddrs()
|
||||||
|
if err != nil {
|
||||||
|
log.Println(err)
|
||||||
|
return ip
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, a := range ips {
|
||||||
|
if ipNet, ok := a.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
|
||||||
|
if ipNet.IP.To4() != nil {
|
||||||
|
ip = ipNet.IP.String()
|
||||||
|
if strings.HasPrefix(ip, "10") {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(ip, "172") {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(ip, "192.168") {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ip = ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var sizeKB = 1024
|
||||||
|
var sizeMB = sizeKB * 1024
|
||||||
|
var sizeGB = sizeMB * 1024
|
||||||
|
|
||||||
|
func Bytes2Size(num int64) string {
|
||||||
|
numStr := ""
|
||||||
|
unit := "B"
|
||||||
|
if num/int64(sizeGB) > 1 {
|
||||||
|
numStr = fmt.Sprintf("%.2f", float64(num)/float64(sizeGB))
|
||||||
|
unit = "GB"
|
||||||
|
} else if num/int64(sizeMB) > 1 {
|
||||||
|
numStr = fmt.Sprintf("%d", int(float64(num)/float64(sizeMB)))
|
||||||
|
unit = "MB"
|
||||||
|
} else if num/int64(sizeKB) > 1 {
|
||||||
|
numStr = fmt.Sprintf("%d", int(float64(num)/float64(sizeKB)))
|
||||||
|
unit = "KB"
|
||||||
|
} else {
|
||||||
|
numStr = fmt.Sprintf("%d", num)
|
||||||
|
}
|
||||||
|
return numStr + " " + unit
|
||||||
|
}
|
||||||
|
|
||||||
|
func Seconds2Time(num int) (time string) {
|
||||||
|
if num/31104000 > 0 {
|
||||||
|
time += strconv.Itoa(num/31104000) + " 年 "
|
||||||
|
num %= 31104000
|
||||||
|
}
|
||||||
|
if num/2592000 > 0 {
|
||||||
|
time += strconv.Itoa(num/2592000) + " 个月 "
|
||||||
|
num %= 2592000
|
||||||
|
}
|
||||||
|
if num/86400 > 0 {
|
||||||
|
time += strconv.Itoa(num/86400) + " 天 "
|
||||||
|
num %= 86400
|
||||||
|
}
|
||||||
|
if num/3600 > 0 {
|
||||||
|
time += strconv.Itoa(num/3600) + " 小时 "
|
||||||
|
num %= 3600
|
||||||
|
}
|
||||||
|
if num/60 > 0 {
|
||||||
|
time += strconv.Itoa(num/60) + " 分钟 "
|
||||||
|
num %= 60
|
||||||
|
}
|
||||||
|
time += strconv.Itoa(num) + " 秒"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func Interface2String(inter interface{}) string {
|
||||||
|
switch inter.(type) {
|
||||||
|
case string:
|
||||||
|
return inter.(string)
|
||||||
|
case int:
|
||||||
|
return fmt.Sprintf("%d", inter.(int))
|
||||||
|
case float64:
|
||||||
|
return fmt.Sprintf("%f", inter.(float64))
|
||||||
|
}
|
||||||
|
return "Not Implemented"
|
||||||
|
}
|
||||||
|
|
||||||
|
func UnescapeHTML(x string) interface{} {
|
||||||
|
return template.HTML(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
func IntMax(a int, b int) int {
|
||||||
|
if a >= b {
|
||||||
|
return a
|
||||||
|
} else {
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetUUID() string {
|
||||||
|
code := uuid.New().String()
|
||||||
|
code = strings.Replace(code, "-", "", -1)
|
||||||
|
return code
|
||||||
|
}
|
||||||
|
|
||||||
|
func Max(a int, b int) int {
|
||||||
|
if a >= b {
|
||||||
|
return a
|
||||||
|
} else {
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
}
|
9
common/validate.go
Normal file
9
common/validate.go
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
package common
|
||||||
|
|
||||||
|
import "github.com/go-playground/validator/v10"
|
||||||
|
|
||||||
|
var Validate *validator.Validate
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
Validate = validator.New()
|
||||||
|
}
|
77
common/verification.go
Normal file
77
common/verification.go
Normal file
@ -0,0 +1,77 @@
|
|||||||
|
package common
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type verificationValue struct {
|
||||||
|
code string
|
||||||
|
time time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
EmailVerificationPurpose = "v"
|
||||||
|
PasswordResetPurpose = "r"
|
||||||
|
)
|
||||||
|
|
||||||
|
var verificationMutex sync.Mutex
|
||||||
|
var verificationMap map[string]verificationValue
|
||||||
|
var verificationMapMaxSize = 10
|
||||||
|
var VerificationValidMinutes = 10
|
||||||
|
|
||||||
|
func GenerateVerificationCode(length int) string {
|
||||||
|
code := uuid.New().String()
|
||||||
|
code = strings.Replace(code, "-", "", -1)
|
||||||
|
if length == 0 {
|
||||||
|
return code
|
||||||
|
}
|
||||||
|
return code[:length]
|
||||||
|
}
|
||||||
|
|
||||||
|
func RegisterVerificationCodeWithKey(key string, code string, purpose string) {
|
||||||
|
verificationMutex.Lock()
|
||||||
|
defer verificationMutex.Unlock()
|
||||||
|
verificationMap[purpose+key] = verificationValue{
|
||||||
|
code: code,
|
||||||
|
time: time.Now(),
|
||||||
|
}
|
||||||
|
if len(verificationMap) > verificationMapMaxSize {
|
||||||
|
removeExpiredPairs()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func VerifyCodeWithKey(key string, code string, purpose string) bool {
|
||||||
|
verificationMutex.Lock()
|
||||||
|
defer verificationMutex.Unlock()
|
||||||
|
value, okay := verificationMap[purpose+key]
|
||||||
|
now := time.Now()
|
||||||
|
if !okay || int(now.Sub(value.time).Seconds()) >= VerificationValidMinutes*60 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return code == value.code
|
||||||
|
}
|
||||||
|
|
||||||
|
func DeleteKey(key string, purpose string) {
|
||||||
|
verificationMutex.Lock()
|
||||||
|
defer verificationMutex.Unlock()
|
||||||
|
delete(verificationMap, purpose+key)
|
||||||
|
}
|
||||||
|
|
||||||
|
// no lock inside, so the caller must lock the verificationMap before calling!
|
||||||
|
func removeExpiredPairs() {
|
||||||
|
now := time.Now()
|
||||||
|
for key := range verificationMap {
|
||||||
|
if int(now.Sub(verificationMap[key].time).Seconds()) >= VerificationValidMinutes*60 {
|
||||||
|
delete(verificationMap, key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
verificationMutex.Lock()
|
||||||
|
defer verificationMutex.Unlock()
|
||||||
|
verificationMap = make(map[string]verificationValue)
|
||||||
|
}
|
160
controller/file.go
Normal file
160
controller/file.go
Normal file
@ -0,0 +1,160 @@
|
|||||||
|
package controller
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"gin-template/common"
|
||||||
|
"gin-template/model"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"net/http"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func GetAllFiles(c *gin.Context) {
|
||||||
|
p, _ := strconv.Atoi(c.Query("p"))
|
||||||
|
if p < 0 {
|
||||||
|
p = 0
|
||||||
|
}
|
||||||
|
files, err := model.GetAllFiles(p*common.ItemsPerPage, common.ItemsPerPage)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": true,
|
||||||
|
"message": "",
|
||||||
|
"data": files,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func SearchFiles(c *gin.Context) {
|
||||||
|
keyword := c.Query("keyword")
|
||||||
|
files, err := model.SearchFiles(keyword)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": true,
|
||||||
|
"message": "",
|
||||||
|
"data": files,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func UploadFile(c *gin.Context) {
|
||||||
|
form, err := c.MultipartForm()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
uploadPath := common.UploadPath
|
||||||
|
description := c.PostForm("description")
|
||||||
|
if description == "" {
|
||||||
|
description = "无描述信息"
|
||||||
|
}
|
||||||
|
uploader := c.GetString("username")
|
||||||
|
if uploader == "" {
|
||||||
|
uploader = "访客用户"
|
||||||
|
}
|
||||||
|
uploaderId := c.GetInt("id")
|
||||||
|
currentTime := time.Now().Format("2006-01-02 15:04:05")
|
||||||
|
files := form.File["file"]
|
||||||
|
for _, file := range files {
|
||||||
|
filename := filepath.Base(file.Filename)
|
||||||
|
ext := filepath.Ext(filename)
|
||||||
|
link := common.GetUUID() + ext
|
||||||
|
savePath := filepath.Join(uploadPath, link) // both parts are checked, so this path should be safe to use
|
||||||
|
if err := c.SaveUploadedFile(file, savePath); err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// save to database
|
||||||
|
fileObj := &model.File{
|
||||||
|
Description: description,
|
||||||
|
Uploader: uploader,
|
||||||
|
UploadTime: currentTime,
|
||||||
|
UploaderId: uploaderId,
|
||||||
|
Link: link,
|
||||||
|
Filename: filename,
|
||||||
|
}
|
||||||
|
err = fileObj.Insert()
|
||||||
|
if err != nil {
|
||||||
|
_ = fmt.Errorf(err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": true,
|
||||||
|
"message": "",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func DeleteFile(c *gin.Context) {
|
||||||
|
fileIdStr := c.Param("id")
|
||||||
|
fileId, err := strconv.Atoi(fileIdStr)
|
||||||
|
if err != nil || fileId == 0 {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "无效的参数",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
fileObj := &model.File{
|
||||||
|
Id: fileId,
|
||||||
|
}
|
||||||
|
model.DB.Where("id = ?", fileId).First(&fileObj)
|
||||||
|
if fileObj.Link == "" {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "文件不存在!",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
err = fileObj.Delete()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": true,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
message := "文件删除成功"
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": true,
|
||||||
|
"message": message,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func DownloadFile(c *gin.Context) {
|
||||||
|
path := c.Param("file")
|
||||||
|
fullPath := filepath.Join(common.UploadPath, path)
|
||||||
|
if !strings.HasPrefix(fullPath, common.UploadPath) {
|
||||||
|
// We may being attacked!
|
||||||
|
c.Status(403)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.File(fullPath)
|
||||||
|
// Update download counter
|
||||||
|
go func() {
|
||||||
|
model.UpdateDownloadCounter(path)
|
||||||
|
}()
|
||||||
|
}
|
207
controller/github.go
Normal file
207
controller/github.go
Normal file
@ -0,0 +1,207 @@
|
|||||||
|
package controller
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"gin-template/common"
|
||||||
|
"gin-template/model"
|
||||||
|
"github.com/gin-contrib/sessions"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type GitHubOAuthResponse struct {
|
||||||
|
AccessToken string `json:"access_token"`
|
||||||
|
Scope string `json:"scope"`
|
||||||
|
TokenType string `json:"token_type"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type GitHubUser struct {
|
||||||
|
Login string `json:"login"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func getGitHubUserInfoByCode(code string) (*GitHubUser, error) {
|
||||||
|
if code == "" {
|
||||||
|
return nil, errors.New("无效的参数")
|
||||||
|
}
|
||||||
|
values := map[string]string{"client_id": common.GitHubClientId, "client_secret": common.GitHubClientSecret, "code": code}
|
||||||
|
jsonData, err := json.Marshal(values)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req, err := http.NewRequest("POST", "https://github.com/login/oauth/access_token", bytes.NewBuffer(jsonData))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
req.Header.Set("Accept", "application/json")
|
||||||
|
client := http.Client{
|
||||||
|
Timeout: 5 * time.Second,
|
||||||
|
}
|
||||||
|
res, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
common.SysLog(err.Error())
|
||||||
|
return nil, errors.New("无法连接至 GitHub 服务器,请稍后重试!")
|
||||||
|
}
|
||||||
|
defer res.Body.Close()
|
||||||
|
var oAuthResponse GitHubOAuthResponse
|
||||||
|
err = json.NewDecoder(res.Body).Decode(&oAuthResponse)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req, err = http.NewRequest("GET", "https://api.github.com/user", nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", oAuthResponse.AccessToken))
|
||||||
|
res2, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
common.SysLog(err.Error())
|
||||||
|
return nil, errors.New("无法连接至 GitHub 服务器,请稍后重试!")
|
||||||
|
}
|
||||||
|
defer res2.Body.Close()
|
||||||
|
var githubUser GitHubUser
|
||||||
|
err = json.NewDecoder(res2.Body).Decode(&githubUser)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if githubUser.Login == "" {
|
||||||
|
return nil, errors.New("返回值非法,用户字段为空,请稍后重试!")
|
||||||
|
}
|
||||||
|
return &githubUser, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func GitHubOAuth(c *gin.Context) {
|
||||||
|
session := sessions.Default(c)
|
||||||
|
username := session.Get("username")
|
||||||
|
if username != nil {
|
||||||
|
GitHubBind(c)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if !common.GitHubOAuthEnabled {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "管理员未开启通过 GitHub 登录以及注册",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
code := c.Query("code")
|
||||||
|
githubUser, err := getGitHubUserInfoByCode(code)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
user := model.User{
|
||||||
|
GitHubId: githubUser.Login,
|
||||||
|
}
|
||||||
|
if model.IsGitHubIdAlreadyTaken(user.GitHubId) {
|
||||||
|
err := user.FillUserByGitHubId()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if common.RegisterEnabled {
|
||||||
|
user.Username = "github_" + strconv.Itoa(model.GetMaxUserId()+1)
|
||||||
|
if githubUser.Name != "" {
|
||||||
|
user.DisplayName = githubUser.Name
|
||||||
|
} else {
|
||||||
|
user.DisplayName = "GitHub User"
|
||||||
|
}
|
||||||
|
user.Email = githubUser.Email
|
||||||
|
user.Role = common.RoleCommonUser
|
||||||
|
user.Status = common.UserStatusEnabled
|
||||||
|
|
||||||
|
if err := user.Insert(); err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "管理员关闭了新用户注册",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if user.Status != common.UserStatusEnabled {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"message": "用户已被封禁",
|
||||||
|
"success": false,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setupLogin(&user, c)
|
||||||
|
}
|
||||||
|
|
||||||
|
func GitHubBind(c *gin.Context) {
|
||||||
|
if !common.GitHubOAuthEnabled {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "管理员未开启通过 GitHub 登录以及注册",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
code := c.Query("code")
|
||||||
|
githubUser, err := getGitHubUserInfoByCode(code)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
user := model.User{
|
||||||
|
GitHubId: githubUser.Login,
|
||||||
|
}
|
||||||
|
if model.IsGitHubIdAlreadyTaken(user.GitHubId) {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "该 GitHub 账户已被绑定",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
session := sessions.Default(c)
|
||||||
|
id := session.Get("id")
|
||||||
|
// id := c.GetInt("id") // critical bug!
|
||||||
|
user.Id = id.(int)
|
||||||
|
err = user.FillUserById()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
user.GitHubId = githubUser.Login
|
||||||
|
err = user.Update(false)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": true,
|
||||||
|
"message": "bind",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
169
controller/misc.go
Normal file
169
controller/misc.go
Normal file
@ -0,0 +1,169 @@
|
|||||||
|
package controller
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"gin-template/common"
|
||||||
|
"gin-template/model"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
func GetStatus(c *gin.Context) {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": true,
|
||||||
|
"message": "",
|
||||||
|
"data": gin.H{
|
||||||
|
"version": common.Version,
|
||||||
|
"start_time": common.StartTime,
|
||||||
|
"email_verification": common.EmailVerificationEnabled,
|
||||||
|
"github_oauth": common.GitHubOAuthEnabled,
|
||||||
|
"github_client_id": common.GitHubClientId,
|
||||||
|
"system_name": common.SystemName,
|
||||||
|
"footer_html": common.Footer,
|
||||||
|
"wechat_qrcode": common.WeChatAccountQRCodeImageURL,
|
||||||
|
"wechat_login": common.WeChatAuthEnabled,
|
||||||
|
"server_address": common.ServerAddress,
|
||||||
|
"turnstile_check": common.TurnstileCheckEnabled,
|
||||||
|
"turnstile_site_key": common.TurnstileSiteKey,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetNotice(c *gin.Context) {
|
||||||
|
common.OptionMapRWMutex.RLock()
|
||||||
|
defer common.OptionMapRWMutex.RUnlock()
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": true,
|
||||||
|
"message": "",
|
||||||
|
"data": common.OptionMap["Notice"],
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetAbout(c *gin.Context) {
|
||||||
|
common.OptionMapRWMutex.RLock()
|
||||||
|
defer common.OptionMapRWMutex.RUnlock()
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": true,
|
||||||
|
"message": "",
|
||||||
|
"data": common.OptionMap["About"],
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func SendEmailVerification(c *gin.Context) {
|
||||||
|
email := c.Query("email")
|
||||||
|
if err := common.Validate.Var(email, "required,email"); err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "无效的参数",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if model.IsEmailAlreadyTaken(email) {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "邮箱地址已被占用",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
code := common.GenerateVerificationCode(6)
|
||||||
|
common.RegisterVerificationCodeWithKey(email, code, common.EmailVerificationPurpose)
|
||||||
|
subject := fmt.Sprintf("%s邮箱验证邮件", common.SystemName)
|
||||||
|
content := fmt.Sprintf("<p>您好,你正在进行%s邮箱验证。</p>"+
|
||||||
|
"<p>您的验证码为: <strong>%s</strong></p>"+
|
||||||
|
"<p>验证码 %d 分钟内有效,如果不是本人操作,请忽略。</p>", common.SystemName, code, common.VerificationValidMinutes)
|
||||||
|
err := common.SendEmail(subject, email, content)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": true,
|
||||||
|
"message": "",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func SendPasswordResetEmail(c *gin.Context) {
|
||||||
|
email := c.Query("email")
|
||||||
|
if err := common.Validate.Var(email, "required,email"); err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "无效的参数",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !model.IsEmailAlreadyTaken(email) {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "该邮箱地址未注册",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
code := common.GenerateVerificationCode(0)
|
||||||
|
common.RegisterVerificationCodeWithKey(email, code, common.PasswordResetPurpose)
|
||||||
|
link := fmt.Sprintf("%s/user/reset?email=%s&token=%s", common.ServerAddress, email, code)
|
||||||
|
subject := fmt.Sprintf("%s密码重置", common.SystemName)
|
||||||
|
content := fmt.Sprintf("<p>您好,你正在进行%s密码重置。</p>"+
|
||||||
|
"<p>点击<a href='%s'>此处</a>进行密码重置。</p>"+
|
||||||
|
"<p>重置链接 %d 分钟内有效,如果不是本人操作,请忽略。</p>", common.SystemName, link, common.VerificationValidMinutes)
|
||||||
|
err := common.SendEmail(subject, email, content)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": true,
|
||||||
|
"message": "",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
type PasswordResetRequest struct {
|
||||||
|
Email string `json:"email"`
|
||||||
|
Token string `json:"token"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func ResetPassword(c *gin.Context) {
|
||||||
|
var req PasswordResetRequest
|
||||||
|
err := json.NewDecoder(c.Request.Body).Decode(&req)
|
||||||
|
if req.Email == "" || req.Token == "" {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "无效的参数",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !common.VerifyCodeWithKey(req.Email, req.Token, common.PasswordResetPurpose) {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "重置链接非法或已过期",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
password := common.GenerateVerificationCode(12)
|
||||||
|
err = model.ResetUserPasswordByEmail(req.Email, password)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
common.DeleteKey(req.Email, common.PasswordResetPurpose)
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": true,
|
||||||
|
"message": "",
|
||||||
|
"data": password,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
82
controller/option.go
Normal file
82
controller/option.go
Normal file
@ -0,0 +1,82 @@
|
|||||||
|
package controller
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"gin-template/common"
|
||||||
|
"gin-template/model"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
func GetOptions(c *gin.Context) {
|
||||||
|
var options []*model.Option
|
||||||
|
common.OptionMapRWMutex.Lock()
|
||||||
|
for k, v := range common.OptionMap {
|
||||||
|
if strings.Contains(k, "Token") || strings.Contains(k, "Secret") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
options = append(options, &model.Option{
|
||||||
|
Key: k,
|
||||||
|
Value: common.Interface2String(v),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
common.OptionMapRWMutex.Unlock()
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": true,
|
||||||
|
"message": "",
|
||||||
|
"data": options,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func UpdateOption(c *gin.Context) {
|
||||||
|
var option model.Option
|
||||||
|
err := json.NewDecoder(c.Request.Body).Decode(&option)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "无效的参数",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
switch option.Key {
|
||||||
|
case "GitHubOAuthEnabled":
|
||||||
|
if option.Value == "true" && common.GitHubClientId == "" {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "无法启用 GitHub OAuth,请先填入 GitHub Client ID 以及 GitHub Client Secret!",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
case "WeChatAuthEnabled":
|
||||||
|
if option.Value == "true" && common.WeChatServerAddress == "" {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "无法启用微信登录,请先填入微信登录相关配置信息!",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
case "TurnstileCheckEnabled":
|
||||||
|
if option.Value == "true" && common.TurnstileSiteKey == "" {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "无法启用 Turnstile 校验,请先填入 Turnstile 校验相关配置信息!",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
err = model.UpdateOption(option.Key, option.Value)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": true,
|
||||||
|
"message": "",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
624
controller/user.go
Normal file
624
controller/user.go
Normal file
@ -0,0 +1,624 @@
|
|||||||
|
package controller
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"gin-template/common"
|
||||||
|
"gin-template/model"
|
||||||
|
"github.com/gin-contrib/sessions"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
type LoginRequest struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func Login(c *gin.Context) {
|
||||||
|
if !common.PasswordLoginEnabled {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"message": "管理员关闭了密码登录",
|
||||||
|
"success": false,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var loginRequest LoginRequest
|
||||||
|
err := json.NewDecoder(c.Request.Body).Decode(&loginRequest)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"message": "无效的参数",
|
||||||
|
"success": false,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
username := loginRequest.Username
|
||||||
|
password := loginRequest.Password
|
||||||
|
if username == "" || password == "" {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"message": "无效的参数",
|
||||||
|
"success": false,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
user := model.User{
|
||||||
|
Username: username,
|
||||||
|
Password: password,
|
||||||
|
}
|
||||||
|
err = user.ValidateAndFill()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"message": err.Error(),
|
||||||
|
"success": false,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setupLogin(&user, c)
|
||||||
|
}
|
||||||
|
|
||||||
|
// setup session & cookies and then return user info
|
||||||
|
func setupLogin(user *model.User, c *gin.Context) {
|
||||||
|
session := sessions.Default(c)
|
||||||
|
session.Set("id", user.Id)
|
||||||
|
session.Set("username", user.Username)
|
||||||
|
session.Set("role", user.Role)
|
||||||
|
session.Set("status", user.Status)
|
||||||
|
err := session.Save()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"message": "无法保存会话信息,请重试",
|
||||||
|
"success": false,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cleanUser := model.User{
|
||||||
|
Id: user.Id,
|
||||||
|
Username: user.Username,
|
||||||
|
DisplayName: user.DisplayName,
|
||||||
|
Role: user.Role,
|
||||||
|
Status: user.Status,
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"message": "",
|
||||||
|
"success": true,
|
||||||
|
"data": cleanUser,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func Logout(c *gin.Context) {
|
||||||
|
session := sessions.Default(c)
|
||||||
|
session.Clear()
|
||||||
|
err := session.Save()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"message": err.Error(),
|
||||||
|
"success": false,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"message": "",
|
||||||
|
"success": true,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func Register(c *gin.Context) {
|
||||||
|
if !common.RegisterEnabled {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"message": "管理员关闭了新用户注册",
|
||||||
|
"success": false,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !common.PasswordRegisterEnabled {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"message": "管理员关闭了通过密码进行注册,请使用第三方账户验证的形式进行注册",
|
||||||
|
"success": false,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var user model.User
|
||||||
|
err := json.NewDecoder(c.Request.Body).Decode(&user)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "无效的参数",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := common.Validate.Struct(&user); err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "输入不合法 " + err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if common.EmailVerificationEnabled {
|
||||||
|
if user.Email == "" || user.VerificationCode == "" {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "管理员开启了邮箱验证,请输入邮箱地址和验证码",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !common.VerifyCodeWithKey(user.Email, user.VerificationCode, common.EmailVerificationPurpose) {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "验证码错误或已过期",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cleanUser := model.User{
|
||||||
|
Username: user.Username,
|
||||||
|
Password: user.Password,
|
||||||
|
DisplayName: user.Username,
|
||||||
|
}
|
||||||
|
if common.EmailVerificationEnabled {
|
||||||
|
cleanUser.Email = user.Email
|
||||||
|
}
|
||||||
|
if err := cleanUser.Insert(); err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": true,
|
||||||
|
"message": "",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetAllUsers(c *gin.Context) {
|
||||||
|
p, _ := strconv.Atoi(c.Query("p"))
|
||||||
|
if p < 0 {
|
||||||
|
p = 0
|
||||||
|
}
|
||||||
|
users, err := model.GetAllUsers(p*common.ItemsPerPage, common.ItemsPerPage)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": true,
|
||||||
|
"message": "",
|
||||||
|
"data": users,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func SearchUsers(c *gin.Context) {
|
||||||
|
keyword := c.Query("keyword")
|
||||||
|
users, err := model.SearchUsers(keyword)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": true,
|
||||||
|
"message": "",
|
||||||
|
"data": users,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetUser(c *gin.Context) {
|
||||||
|
id, err := strconv.Atoi(c.Param("id"))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
user, err := model.GetUserById(id, false)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
myRole := c.GetInt("role")
|
||||||
|
if myRole <= user.Role {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "无权获取同级或更高等级用户的信息",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": true,
|
||||||
|
"message": "",
|
||||||
|
"data": user,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func GenerateToken(c *gin.Context) {
|
||||||
|
id := c.GetInt("id")
|
||||||
|
user, err := model.GetUserById(id, true)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
user.Token = uuid.New().String()
|
||||||
|
user.Token = strings.Replace(user.Token, "-", "", -1)
|
||||||
|
|
||||||
|
if model.DB.Where("token = ?", user.Token).First(user).RowsAffected != 0 {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "请重试,系统生成的 UUID 竟然重复了!",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := user.Update(false); err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": true,
|
||||||
|
"message": "",
|
||||||
|
"data": user.Token,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetSelf(c *gin.Context) {
|
||||||
|
id := c.GetInt("id")
|
||||||
|
user, err := model.GetUserById(id, false)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": true,
|
||||||
|
"message": "",
|
||||||
|
"data": user,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func UpdateUser(c *gin.Context) {
|
||||||
|
var updatedUser model.User
|
||||||
|
err := json.NewDecoder(c.Request.Body).Decode(&updatedUser)
|
||||||
|
if err != nil || updatedUser.Id == 0 {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "无效的参数",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if updatedUser.Password == "" {
|
||||||
|
updatedUser.Password = "$I_LOVE_U" // make Validator happy :)
|
||||||
|
}
|
||||||
|
if err := common.Validate.Struct(&updatedUser); err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "输入不合法 " + err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
originUser, err := model.GetUserById(updatedUser.Id, false)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
myRole := c.GetInt("role")
|
||||||
|
if myRole <= originUser.Role {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "无权更新同权限等级或更高权限等级的用户信息",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if myRole <= updatedUser.Role {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "无权将其他用户权限等级提升到大于等于自己的权限等级",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if updatedUser.Password == "$I_LOVE_U" {
|
||||||
|
updatedUser.Password = "" // rollback to what it should be
|
||||||
|
}
|
||||||
|
updatePassword := updatedUser.Password != ""
|
||||||
|
if err := updatedUser.Update(updatePassword); err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": true,
|
||||||
|
"message": "",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func UpdateSelf(c *gin.Context) {
|
||||||
|
var user model.User
|
||||||
|
err := json.NewDecoder(c.Request.Body).Decode(&user)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "无效的参数",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if user.Password == "" {
|
||||||
|
user.Password = "$I_LOVE_U" // make Validator happy :)
|
||||||
|
}
|
||||||
|
if err := common.Validate.Struct(&user); err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "输入不合法 " + err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
cleanUser := model.User{
|
||||||
|
Id: c.GetInt("id"),
|
||||||
|
Username: user.Username,
|
||||||
|
Password: user.Password,
|
||||||
|
DisplayName: user.DisplayName,
|
||||||
|
}
|
||||||
|
if user.Password == "$I_LOVE_U" {
|
||||||
|
user.Password = "" // rollback to what it should be
|
||||||
|
cleanUser.Password = ""
|
||||||
|
}
|
||||||
|
updatePassword := user.Password != ""
|
||||||
|
if err := cleanUser.Update(updatePassword); err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": true,
|
||||||
|
"message": "",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func DeleteUser(c *gin.Context) {
|
||||||
|
id, err := strconv.Atoi(c.Param("id"))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
originUser, err := model.GetUserById(id, false)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
myRole := c.GetInt("role")
|
||||||
|
if myRole <= originUser.Role {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "无权删除同权限等级或更高权限等级的用户",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
err = model.DeleteUserById(id)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": true,
|
||||||
|
"message": "",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func DeleteSelf(c *gin.Context) {
|
||||||
|
id := c.GetInt("id")
|
||||||
|
err := model.DeleteUserById(id)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": true,
|
||||||
|
"message": "",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func CreateUser(c *gin.Context) {
|
||||||
|
var user model.User
|
||||||
|
err := json.NewDecoder(c.Request.Body).Decode(&user)
|
||||||
|
if err != nil || user.Username == "" || user.Password == "" {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "无效的参数",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if user.DisplayName == "" {
|
||||||
|
user.DisplayName = user.Username
|
||||||
|
}
|
||||||
|
myRole := c.GetInt("role")
|
||||||
|
if user.Role >= myRole {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "无法创建权限大于等于自己的用户",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Even for admin users, we cannot fully trust them!
|
||||||
|
cleanUser := model.User{
|
||||||
|
Username: user.Username,
|
||||||
|
Password: user.Password,
|
||||||
|
DisplayName: user.DisplayName,
|
||||||
|
}
|
||||||
|
if err := cleanUser.Insert(); err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": true,
|
||||||
|
"message": "",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
type ManageRequest struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
Action string `json:"action"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ManageUser Only admin user can do this
|
||||||
|
func ManageUser(c *gin.Context) {
|
||||||
|
var req ManageRequest
|
||||||
|
err := json.NewDecoder(c.Request.Body).Decode(&req)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "无效的参数",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
user := model.User{
|
||||||
|
Username: req.Username,
|
||||||
|
}
|
||||||
|
// Fill attributes
|
||||||
|
model.DB.Where(&user).First(&user)
|
||||||
|
if user.Id == 0 {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "用户不存在",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
myRole := c.GetInt("role")
|
||||||
|
if myRole <= user.Role && myRole != common.RoleRootUser {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "无权更新同权限等级或更高权限等级的用户信息",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
switch req.Action {
|
||||||
|
case "disable":
|
||||||
|
user.Status = common.UserStatusDisabled
|
||||||
|
case "enable":
|
||||||
|
user.Status = common.UserStatusEnabled
|
||||||
|
case "delete":
|
||||||
|
if err := user.Delete(); err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
case "promote":
|
||||||
|
if myRole != common.RoleRootUser {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "普通管理员用户无法提升其他用户为管理员",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
user.Role = common.RoleAdminUser
|
||||||
|
case "demote":
|
||||||
|
user.Role = common.RoleCommonUser
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := user.Update(false); err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
clearUser := model.User{
|
||||||
|
Role: user.Role,
|
||||||
|
Status: user.Status,
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": true,
|
||||||
|
"message": "",
|
||||||
|
"data": clearUser,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func EmailBind(c *gin.Context) {
|
||||||
|
email := c.Query("email")
|
||||||
|
code := c.Query("code")
|
||||||
|
if !common.VerifyCodeWithKey(email, code, common.EmailVerificationPurpose) {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "验证码错误或已过期",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
id := c.GetInt("id")
|
||||||
|
user := model.User{
|
||||||
|
Id: id,
|
||||||
|
}
|
||||||
|
err := user.FillUserById()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
user.Email = email
|
||||||
|
// no need to check if this email already taken, because we have used verification code to check it
|
||||||
|
err = user.Update(false)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": true,
|
||||||
|
"message": "",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
164
controller/wechat.go
Normal file
164
controller/wechat.go
Normal file
@ -0,0 +1,164 @@
|
|||||||
|
package controller
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"gin-template/common"
|
||||||
|
"gin-template/model"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type wechatLoginResponse struct {
|
||||||
|
Success bool `json:"success"`
|
||||||
|
Message string `json:"message"`
|
||||||
|
Data string `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func getWeChatIdByCode(code string) (string, error) {
|
||||||
|
if code == "" {
|
||||||
|
return "", errors.New("无效的参数")
|
||||||
|
}
|
||||||
|
req, err := http.NewRequest("GET", fmt.Sprintf("%s/api/wechat/user?code=%s", common.WeChatServerAddress, code), nil)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
req.Header.Set("Authorization", common.WeChatServerToken)
|
||||||
|
client := http.Client{
|
||||||
|
Timeout: 5 * time.Second,
|
||||||
|
}
|
||||||
|
httpResponse, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer httpResponse.Body.Close()
|
||||||
|
var res wechatLoginResponse
|
||||||
|
err = json.NewDecoder(httpResponse.Body).Decode(&res)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if !res.Success {
|
||||||
|
return "", errors.New(res.Message)
|
||||||
|
}
|
||||||
|
if res.Data == "" {
|
||||||
|
return "", errors.New("验证码错误或已过期")
|
||||||
|
}
|
||||||
|
return res.Data, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func WeChatAuth(c *gin.Context) {
|
||||||
|
if !common.WeChatAuthEnabled {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"message": "管理员未开启通过微信登录以及注册",
|
||||||
|
"success": false,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
code := c.Query("code")
|
||||||
|
wechatId, err := getWeChatIdByCode(code)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"message": err.Error(),
|
||||||
|
"success": false,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
user := model.User{
|
||||||
|
WeChatId: wechatId,
|
||||||
|
}
|
||||||
|
if model.IsWeChatIdAlreadyTaken(wechatId) {
|
||||||
|
err := user.FillUserByWeChatId()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if common.RegisterEnabled {
|
||||||
|
user.Username = "wechat_" + strconv.Itoa(model.GetMaxUserId()+1)
|
||||||
|
user.DisplayName = "WeChat User"
|
||||||
|
user.Role = common.RoleCommonUser
|
||||||
|
user.Status = common.UserStatusEnabled
|
||||||
|
|
||||||
|
if err := user.Insert(); err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "管理员关闭了新用户注册",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if user.Status != common.UserStatusEnabled {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"message": "用户已被封禁",
|
||||||
|
"success": false,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setupLogin(&user, c)
|
||||||
|
}
|
||||||
|
|
||||||
|
func WeChatBind(c *gin.Context) {
|
||||||
|
if !common.WeChatAuthEnabled {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"message": "管理员未开启通过微信登录以及注册",
|
||||||
|
"success": false,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
code := c.Query("code")
|
||||||
|
wechatId, err := getWeChatIdByCode(code)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"message": err.Error(),
|
||||||
|
"success": false,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if model.IsWeChatIdAlreadyTaken(wechatId) {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "该微信账号已被绑定",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
id := c.GetInt("id")
|
||||||
|
user := model.User{
|
||||||
|
Id: id,
|
||||||
|
}
|
||||||
|
err = user.FillUserById()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
user.WeChatId = wechatId
|
||||||
|
err = user.Update(false)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": true,
|
||||||
|
"message": "",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
51
go.mod
Normal file
51
go.mod
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
module gin-template
|
||||||
|
|
||||||
|
// +heroku goVersion go1.18
|
||||||
|
go 1.18
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/gin-contrib/cors v1.4.0
|
||||||
|
github.com/gin-contrib/gzip v0.0.6
|
||||||
|
github.com/gin-contrib/sessions v0.0.5
|
||||||
|
github.com/gin-contrib/static v0.0.1
|
||||||
|
github.com/gin-gonic/gin v1.8.1
|
||||||
|
github.com/go-playground/validator/v10 v10.11.1
|
||||||
|
github.com/go-redis/redis/v8 v8.11.5
|
||||||
|
github.com/google/uuid v1.3.0
|
||||||
|
golang.org/x/crypto v0.1.0
|
||||||
|
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df
|
||||||
|
gorm.io/driver/mysql v1.4.3
|
||||||
|
gorm.io/driver/sqlite v1.4.3
|
||||||
|
gorm.io/gorm v1.24.0
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff // indirect
|
||||||
|
github.com/cespare/xxhash/v2 v2.1.2 // indirect
|
||||||
|
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||||
|
github.com/gin-contrib/sse v0.1.0 // indirect
|
||||||
|
github.com/go-playground/locales v0.14.0 // indirect
|
||||||
|
github.com/go-playground/universal-translator v0.18.0 // indirect
|
||||||
|
github.com/go-sql-driver/mysql v1.6.0 // indirect
|
||||||
|
github.com/goccy/go-json v0.9.7 // indirect
|
||||||
|
github.com/gomodule/redigo v2.0.0+incompatible // indirect
|
||||||
|
github.com/gorilla/context v1.1.1 // indirect
|
||||||
|
github.com/gorilla/securecookie v1.1.1 // indirect
|
||||||
|
github.com/gorilla/sessions v1.2.1 // indirect
|
||||||
|
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||||
|
github.com/jinzhu/now v1.1.5 // indirect
|
||||||
|
github.com/json-iterator/go v1.1.12 // indirect
|
||||||
|
github.com/leodido/go-urn v1.2.1 // indirect
|
||||||
|
github.com/mattn/go-isatty v0.0.14 // indirect
|
||||||
|
github.com/mattn/go-sqlite3 v2.0.3+incompatible // indirect
|
||||||
|
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
|
||||||
|
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||||
|
github.com/pelletier/go-toml/v2 v2.0.1 // indirect
|
||||||
|
github.com/ugorji/go/codec v1.2.7 // indirect
|
||||||
|
golang.org/x/net v0.7.0 // indirect
|
||||||
|
golang.org/x/sys v0.5.0 // indirect
|
||||||
|
golang.org/x/text v0.7.0 // indirect
|
||||||
|
google.golang.org/protobuf v1.28.0 // indirect
|
||||||
|
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
|
||||||
|
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||||
|
)
|
167
go.sum
Normal file
167
go.sum
Normal file
@ -0,0 +1,167 @@
|
|||||||
|
github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff h1:RmdPFa+slIr4SCBg4st/l/vZWVe9QJKMXGO60Bxbe04=
|
||||||
|
github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff/go.mod h1:+RTT1BOk5P97fT2CiHkbFQwkK3mjsFAP6zCYV2aXtjw=
|
||||||
|
github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE=
|
||||||
|
github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||||
|
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||||
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||||
|
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||||
|
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
|
||||||
|
github.com/gin-contrib/cors v1.4.0 h1:oJ6gwtUl3lqV0WEIwM/LxPF1QZ5qe2lGWdY2+bz7y0g=
|
||||||
|
github.com/gin-contrib/cors v1.4.0/go.mod h1:bs9pNM0x/UsmHPBWT2xZz9ROh8xYjYkiURUfmBoMlcs=
|
||||||
|
github.com/gin-contrib/gzip v0.0.6 h1:NjcunTcGAj5CO1gn4N8jHOSIeRFHIbn51z6K+xaN4d4=
|
||||||
|
github.com/gin-contrib/gzip v0.0.6/go.mod h1:QOJlmV2xmayAjkNS2Y8NQsMneuRShOU/kjovCXNuzzk=
|
||||||
|
github.com/gin-contrib/sessions v0.0.5 h1:CATtfHmLMQrMNpJRgzjWXD7worTh7g7ritsQfmF+0jE=
|
||||||
|
github.com/gin-contrib/sessions v0.0.5/go.mod h1:vYAuaUPqie3WUSsft6HUlCjlwwoJQs97miaG2+7neKY=
|
||||||
|
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
|
||||||
|
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
||||||
|
github.com/gin-contrib/static v0.0.1 h1:JVxuvHPuUfkoul12N7dtQw7KRn/pSMq7Ue1Va9Swm1U=
|
||||||
|
github.com/gin-contrib/static v0.0.1/go.mod h1:CSxeF+wep05e0kCOsqWdAWbSszmc31zTIbD8TvWl7Hs=
|
||||||
|
github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M=
|
||||||
|
github.com/gin-gonic/gin v1.8.1 h1:4+fr/el88TOO3ewCmQr8cx/CtZ/umlIRIs5M4NTNjf8=
|
||||||
|
github.com/gin-gonic/gin v1.8.1/go.mod h1:ji8BvRH1azfM+SYow9zQ6SZMvR8qOMZHmsCuWR9tTTk=
|
||||||
|
github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A=
|
||||||
|
github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||||
|
github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8=
|
||||||
|
github.com/go-playground/locales v0.14.0 h1:u50s323jtVGugKlcYeyzC0etD1HifMjqmJqb8WugfUU=
|
||||||
|
github.com/go-playground/locales v0.14.0/go.mod h1:sawfccIbzZTqEDETgFXqTho0QybSa7l++s0DH+LDiLs=
|
||||||
|
github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA=
|
||||||
|
github.com/go-playground/universal-translator v0.18.0 h1:82dyy6p4OuJq4/CByFNOn/jYrnRPArHwAcmLoJZxyho=
|
||||||
|
github.com/go-playground/universal-translator v0.18.0/go.mod h1:UvRDBj+xPUEGrFYl+lu/H90nyDXpg0fqeB/AQUGNTVA=
|
||||||
|
github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI=
|
||||||
|
github.com/go-playground/validator/v10 v10.10.0/go.mod h1:74x4gJWsvQexRdW8Pn3dXSGrTK4nAUsbPlLADvpJkos=
|
||||||
|
github.com/go-playground/validator/v10 v10.11.1 h1:prmOlTVv+YjZjmRmNSF3VmspqJIxJWXmqUsHwfTRRkQ=
|
||||||
|
github.com/go-playground/validator/v10 v10.11.1/go.mod h1:i+3WkQ1FvaUjjxh1kSvIA4dMGDBiPU55YFDl0WbKdWU=
|
||||||
|
github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI=
|
||||||
|
github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo=
|
||||||
|
github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE=
|
||||||
|
github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
|
||||||
|
github.com/goccy/go-json v0.9.7 h1:IcB+Aqpx/iMHu5Yooh7jEzJk1JZ7Pjtmys2ukPr7EeM=
|
||||||
|
github.com/goccy/go-json v0.9.7/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
||||||
|
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
|
||||||
|
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||||
|
github.com/gomodule/redigo v2.0.0+incompatible h1:K/R+8tc58AaqLkqG2Ol3Qk+DR/TlNuhuh457pBFPtt0=
|
||||||
|
github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4=
|
||||||
|
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
||||||
|
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
|
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||||
|
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
|
||||||
|
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
|
github.com/gorilla/context v1.1.1 h1:AWwleXJkX/nhcU9bZSnZoi3h/qGYqQAGhq6zZe/aQW8=
|
||||||
|
github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg=
|
||||||
|
github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ=
|
||||||
|
github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4=
|
||||||
|
github.com/gorilla/sessions v1.1.1/go.mod h1:8KCfur6+4Mqcc6S0FEfKuN15Vl5MgXW92AE8ovaJD0w=
|
||||||
|
github.com/gorilla/sessions v1.2.1 h1:DHd3rPN5lE3Ts3D8rKkQ8x/0kqfeNmBAaiSi+o7FsgI=
|
||||||
|
github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM=
|
||||||
|
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||||
|
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||||
|
github.com/jinzhu/now v1.1.4/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||||
|
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||||
|
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||||
|
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
|
||||||
|
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||||
|
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||||
|
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||||
|
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
|
||||||
|
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
||||||
|
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
|
||||||
|
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||||
|
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||||
|
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||||
|
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||||
|
github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII=
|
||||||
|
github.com/leodido/go-urn v1.2.1 h1:BqpAaACuzVSgi/VLzGZIobT2z4v53pjosyNd9Yv6n/w=
|
||||||
|
github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ictyFfxY=
|
||||||
|
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
||||||
|
github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y=
|
||||||
|
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
|
||||||
|
github.com/mattn/go-sqlite3 v1.14.15/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
|
||||||
|
github.com/mattn/go-sqlite3 v2.0.3+incompatible h1:gXHsfypPkaMZrKbD5209QV9jbUTJKjyR5WD3HYQSd+U=
|
||||||
|
github.com/mattn/go-sqlite3 v2.0.3+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
|
||||||
|
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
|
||||||
|
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||||
|
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
|
||||||
|
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||||
|
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||||
|
github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=
|
||||||
|
github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE=
|
||||||
|
github.com/onsi/gomega v1.18.1 h1:M1GfJqGRrBrrGGsbxzV5dqM2U2ApXefZCQpkukxYRLE=
|
||||||
|
github.com/pelletier/go-toml/v2 v2.0.1 h1:8e3L2cCQzLFi2CR4g7vGFuFxX7Jl1kKX8gW+iV0GUKU=
|
||||||
|
github.com/pelletier/go-toml/v2 v2.0.1/go.mod h1:r9LEWfGN8R5k0VXJ+0BkIe7MYkRdwZOjgMj2KwnJFUo=
|
||||||
|
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
|
||||||
|
github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8=
|
||||||
|
github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE=
|
||||||
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
|
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||||
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
|
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||||
|
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
|
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
|
github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk=
|
||||||
|
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||||
|
github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
|
||||||
|
github.com/ugorji/go v1.2.7/go.mod h1:nF9osbDWLy6bDVv/Rtoh6QgnvNDpmCalQV5urGCCS6M=
|
||||||
|
github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY=
|
||||||
|
github.com/ugorji/go/codec v1.2.7 h1:YPXUKf7fYbp/y8xloBqZOw2qaVggbfwMlI8WM3wZUJ0=
|
||||||
|
github.com/ugorji/go/codec v1.2.7/go.mod h1:WGN1fab3R1fzQlVQTkfxVtIBhWDRqOviHU95kRgeqEY=
|
||||||
|
golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||||
|
golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||||
|
golang.org/x/crypto v0.1.0 h1:MDRAIl0xIo9Io2xV565hzXHw3zVseKrJKodhohM5CjU=
|
||||||
|
golang.org/x/crypto v0.1.0/go.mod h1:RecgLatLF4+eUMCP1PoPZQb+cVrJcOPbHkTkbkB9sbw=
|
||||||
|
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||||
|
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||||
|
golang.org/x/net v0.7.0 h1:rJrUqqhjsgNp7KqAIc25s9pZnjU7TUcSY7HcVZjdn1g=
|
||||||
|
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||||
|
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU=
|
||||||
|
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
|
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||||
|
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
|
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
|
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||||
|
golang.org/x/text v0.7.0 h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo=
|
||||||
|
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||||
|
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
|
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
|
||||||
|
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
|
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||||
|
google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw=
|
||||||
|
google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
|
||||||
|
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc h1:2gGKlE2+asNV9m7xrywl36YYNnBG5ZQ0r/BOOxqPpmk=
|
||||||
|
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc/go.mod h1:m7x9LTH6d71AHyAX77c9yqWCCa3UKHcVEj9y7hAtKDk=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||||
|
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
|
||||||
|
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df h1:n7WqCuqOuCbNr617RXOY0AWRXxgwEyPp2z+p0+hgMuE=
|
||||||
|
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df/go.mod h1:LRQQ+SO6ZHR7tOkpBDuZnXENFzX8qRjMDMyPD6BRkCw=
|
||||||
|
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
|
||||||
|
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
|
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
|
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||||
|
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||||
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gorm.io/driver/mysql v1.4.3 h1:/JhWJhO2v17d8hjApTltKNADm7K7YI2ogkR7avJUL3k=
|
||||||
|
gorm.io/driver/mysql v1.4.3/go.mod h1:sSIebwZAVPiT+27jK9HIwvsqOGKx3YMPmrA3mBJR10c=
|
||||||
|
gorm.io/driver/sqlite v1.4.3 h1:HBBcZSDnWi5BW3B3rwvVTc510KGkBkexlOg0QrmLUuU=
|
||||||
|
gorm.io/driver/sqlite v1.4.3/go.mod h1:0Aq3iPO+v9ZKbcdiz8gLWRw5VOPcBOPUQJFLq5e2ecI=
|
||||||
|
gorm.io/gorm v1.23.8/go.mod h1:l2lP/RyAtc1ynaTjFksBde/O8v9oOGIApu2/xRitmZk=
|
||||||
|
gorm.io/gorm v1.24.0 h1:j/CoiSm6xpRpmzbFJsQHYj+I8bGYWLXVHeYEyyKlF74=
|
||||||
|
gorm.io/gorm v1.24.0/go.mod h1:DVrVomtaYTbqs7gB/x2uVvqnXzv0nqjB396B8cG4dBA=
|
76
main.go
Normal file
76
main.go
Normal file
@ -0,0 +1,76 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"embed"
|
||||||
|
"gin-template/common"
|
||||||
|
"gin-template/middleware"
|
||||||
|
"gin-template/model"
|
||||||
|
"gin-template/router"
|
||||||
|
"github.com/gin-contrib/gzip"
|
||||||
|
"github.com/gin-contrib/sessions"
|
||||||
|
"github.com/gin-contrib/sessions/cookie"
|
||||||
|
"github.com/gin-contrib/sessions/redis"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:embed web/build
|
||||||
|
var buildFS embed.FS
|
||||||
|
|
||||||
|
//go:embed web/build/index.html
|
||||||
|
var indexPage []byte
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
common.SetupGinLog()
|
||||||
|
common.SysLog("system started")
|
||||||
|
if os.Getenv("GIN_MODE") != "debug" {
|
||||||
|
gin.SetMode(gin.ReleaseMode)
|
||||||
|
}
|
||||||
|
// Initialize SQL Database
|
||||||
|
err := model.InitDB()
|
||||||
|
if err != nil {
|
||||||
|
common.FatalLog(err)
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
err := model.CloseDB()
|
||||||
|
if err != nil {
|
||||||
|
common.FatalLog(err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
// Initialize Redis
|
||||||
|
err = common.InitRedisClient()
|
||||||
|
if err != nil {
|
||||||
|
common.FatalLog(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initialize options
|
||||||
|
model.InitOptionMap()
|
||||||
|
|
||||||
|
// Initialize HTTP server
|
||||||
|
server := gin.Default()
|
||||||
|
server.Use(gzip.Gzip(gzip.DefaultCompression))
|
||||||
|
server.Use(middleware.CORS())
|
||||||
|
|
||||||
|
// Initialize session store
|
||||||
|
if common.RedisEnabled {
|
||||||
|
opt := common.ParseRedisOption()
|
||||||
|
store, _ := redis.NewStore(opt.MinIdleConns, opt.Network, opt.Addr, opt.Password, []byte(common.SessionSecret))
|
||||||
|
server.Use(sessions.Sessions("session", store))
|
||||||
|
} else {
|
||||||
|
store := cookie.NewStore([]byte(common.SessionSecret))
|
||||||
|
server.Use(sessions.Sessions("session", store))
|
||||||
|
}
|
||||||
|
|
||||||
|
router.SetRouter(server, buildFS, indexPage)
|
||||||
|
var port = os.Getenv("PORT")
|
||||||
|
if port == "" {
|
||||||
|
port = strconv.Itoa(*common.Port)
|
||||||
|
}
|
||||||
|
err = server.Run(":" + port)
|
||||||
|
if err != nil {
|
||||||
|
log.Println(err)
|
||||||
|
}
|
||||||
|
}
|
117
middleware/auth.go
Normal file
117
middleware/auth.go
Normal file
@ -0,0 +1,117 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"gin-template/common"
|
||||||
|
"gin-template/model"
|
||||||
|
"github.com/gin-contrib/sessions"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
func authHelper(c *gin.Context, minRole int) {
|
||||||
|
session := sessions.Default(c)
|
||||||
|
username := session.Get("username")
|
||||||
|
role := session.Get("role")
|
||||||
|
id := session.Get("id")
|
||||||
|
status := session.Get("status")
|
||||||
|
authByToken := false
|
||||||
|
if username == nil {
|
||||||
|
// Check token
|
||||||
|
token := c.Request.Header.Get("Authorization")
|
||||||
|
if token == "" {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "无权进行此操作,未登录或 token 无效",
|
||||||
|
})
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
user := model.ValidateUserToken(token)
|
||||||
|
if user != nil && user.Username != "" {
|
||||||
|
// Token is valid
|
||||||
|
username = user.Username
|
||||||
|
role = user.Role
|
||||||
|
id = user.Id
|
||||||
|
status = user.Status
|
||||||
|
} else {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "无权进行此操作,token 无效",
|
||||||
|
})
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
authByToken = true
|
||||||
|
}
|
||||||
|
if status.(int) == common.UserStatusDisabled {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "用户已被封禁",
|
||||||
|
})
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if role.(int) < minRole {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "无权进行此操作,权限不足",
|
||||||
|
})
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Set("username", username)
|
||||||
|
c.Set("role", role)
|
||||||
|
c.Set("id", id)
|
||||||
|
c.Set("authByToken", authByToken)
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
|
|
||||||
|
func UserAuth() func(c *gin.Context) {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
authHelper(c, common.RoleCommonUser)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func AdminAuth() func(c *gin.Context) {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
authHelper(c, common.RoleAdminUser)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func RootAuth() func(c *gin.Context) {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
authHelper(c, common.RoleRootUser)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NoTokenAuth You should always use this after normal auth middlewares.
|
||||||
|
func NoTokenAuth() func(c *gin.Context) {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
authByToken := c.GetBool("authByToken")
|
||||||
|
if authByToken {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "本接口不支持使用 token 进行验证",
|
||||||
|
})
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TokenOnlyAuth You should always use this after normal auth middlewares.
|
||||||
|
func TokenOnlyAuth() func(c *gin.Context) {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
authByToken := c.GetBool("authByToken")
|
||||||
|
if !authByToken {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "本接口仅支持使用 token 进行验证",
|
||||||
|
})
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
|
}
|
12
middleware/cache.go
Normal file
12
middleware/cache.go
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Cache() func(c *gin.Context) {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
c.Header("Cache-Control", "max-age=604800") // one week
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
|
}
|
12
middleware/cors.go
Normal file
12
middleware/cors.go
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gin-contrib/cors"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func CORS() gin.HandlerFunc {
|
||||||
|
config := cors.DefaultConfig()
|
||||||
|
config.AllowOrigins = []string{"https://gin-template.vercel.app", "http://localhost:3000/"}
|
||||||
|
return cors.New(config)
|
||||||
|
}
|
103
middleware/rate-limit.go
Normal file
103
middleware/rate-limit.go
Normal file
@ -0,0 +1,103 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"gin-template/common"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
var timeFormat = "2006-01-02T15:04:05.000Z"
|
||||||
|
|
||||||
|
var inMemoryRateLimiter common.InMemoryRateLimiter
|
||||||
|
|
||||||
|
func redisRateLimiter(c *gin.Context, maxRequestNum int, duration int64, mark string) {
|
||||||
|
ctx := context.Background()
|
||||||
|
rdb := common.RDB
|
||||||
|
key := "rateLimit:" + mark + c.ClientIP()
|
||||||
|
listLength, err := rdb.LLen(ctx, key).Result()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err.Error())
|
||||||
|
c.Status(http.StatusInternalServerError)
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if listLength < int64(maxRequestNum) {
|
||||||
|
rdb.LPush(ctx, key, time.Now().Format(timeFormat))
|
||||||
|
rdb.Expire(ctx, key, common.RateLimitKeyExpirationDuration)
|
||||||
|
} else {
|
||||||
|
oldTimeStr, _ := rdb.LIndex(ctx, key, -1).Result()
|
||||||
|
oldTime, err := time.Parse(timeFormat, oldTimeStr)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
c.Status(http.StatusInternalServerError)
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
nowTimeStr := time.Now().Format(timeFormat)
|
||||||
|
nowTime, err := time.Parse(timeFormat, nowTimeStr)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
c.Status(http.StatusInternalServerError)
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// time.Since will return negative number!
|
||||||
|
// See: https://stackoverflow.com/questions/50970900/why-is-time-since-returning-negative-durations-on-windows
|
||||||
|
if int64(nowTime.Sub(oldTime).Seconds()) < duration {
|
||||||
|
rdb.Expire(ctx, key, common.RateLimitKeyExpirationDuration)
|
||||||
|
c.Status(http.StatusTooManyRequests)
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
rdb.LPush(ctx, key, time.Now().Format(timeFormat))
|
||||||
|
rdb.LTrim(ctx, key, 0, int64(maxRequestNum-1))
|
||||||
|
rdb.Expire(ctx, key, common.RateLimitKeyExpirationDuration)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func memoryRateLimiter(c *gin.Context, maxRequestNum int, duration int64, mark string) {
|
||||||
|
key := mark + c.ClientIP()
|
||||||
|
if !inMemoryRateLimiter.Request(key, maxRequestNum, duration) {
|
||||||
|
c.Status(http.StatusTooManyRequests)
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func rateLimitFactory(maxRequestNum int, duration int64, mark string) func(c *gin.Context) {
|
||||||
|
if common.RedisEnabled {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
redisRateLimiter(c, maxRequestNum, duration, mark)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// It's safe to call multi times.
|
||||||
|
inMemoryRateLimiter.Init(common.RateLimitKeyExpirationDuration)
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
memoryRateLimiter(c, maxRequestNum, duration, mark)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func GlobalWebRateLimit() func(c *gin.Context) {
|
||||||
|
return rateLimitFactory(common.GlobalWebRateLimitNum, common.GlobalWebRateLimitDuration, "GW")
|
||||||
|
}
|
||||||
|
|
||||||
|
func GlobalAPIRateLimit() func(c *gin.Context) {
|
||||||
|
return rateLimitFactory(common.GlobalApiRateLimitNum, common.GlobalApiRateLimitDuration, "GA")
|
||||||
|
}
|
||||||
|
|
||||||
|
func CriticalRateLimit() func(c *gin.Context) {
|
||||||
|
return rateLimitFactory(common.CriticalRateLimitNum, common.CriticalRateLimitDuration, "CT")
|
||||||
|
}
|
||||||
|
|
||||||
|
func DownloadRateLimit() func(c *gin.Context) {
|
||||||
|
return rateLimitFactory(common.DownloadRateLimitNum, common.DownloadRateLimitDuration, "DW")
|
||||||
|
}
|
||||||
|
|
||||||
|
func UploadRateLimit() func(c *gin.Context) {
|
||||||
|
return rateLimitFactory(common.UploadRateLimitNum, common.UploadRateLimitDuration, "UP")
|
||||||
|
}
|
80
middleware/turnstile-check.go
Normal file
80
middleware/turnstile-check.go
Normal file
@ -0,0 +1,80 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"gin-template/common"
|
||||||
|
"github.com/gin-contrib/sessions"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
)
|
||||||
|
|
||||||
|
type turnstileCheckResponse struct {
|
||||||
|
Success bool `json:"success"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func TurnstileCheck() gin.HandlerFunc {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
if common.TurnstileCheckEnabled {
|
||||||
|
session := sessions.Default(c)
|
||||||
|
turnstileChecked := session.Get("turnstile")
|
||||||
|
if turnstileChecked != nil {
|
||||||
|
c.Next()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
response := c.Query("turnstile")
|
||||||
|
if response == "" {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "Turnstile token 为空",
|
||||||
|
})
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rawRes, err := http.PostForm("https://challenges.cloudflare.com/turnstile/v0/siteverify", url.Values{
|
||||||
|
"secret": {common.TurnstileSecretKey},
|
||||||
|
"response": {response},
|
||||||
|
"remoteip": {c.ClientIP()},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
common.SysError(err.Error())
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer rawRes.Body.Close()
|
||||||
|
var res turnstileCheckResponse
|
||||||
|
err = json.NewDecoder(rawRes.Body).Decode(&res)
|
||||||
|
if err != nil {
|
||||||
|
common.SysError(err.Error())
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": err.Error(),
|
||||||
|
})
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !res.Success {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"message": "Turnstile 校验失败,请刷新重试!",
|
||||||
|
})
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
session.Set("turnstile", true)
|
||||||
|
err = session.Save()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"message": "无法保存会话信息,请重试",
|
||||||
|
"success": false,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
|
}
|
51
model/file.go
Normal file
51
model/file.go
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
package model
|
||||||
|
|
||||||
|
import (
|
||||||
|
"gin-template/common"
|
||||||
|
_ "gorm.io/driver/sqlite"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
|
)
|
||||||
|
|
||||||
|
type File struct {
|
||||||
|
Id int `json:"id"`
|
||||||
|
Filename string `json:"filename" gorm:"index"`
|
||||||
|
Description string `json:"description"`
|
||||||
|
Uploader string `json:"uploader" gorm:"index"`
|
||||||
|
UploaderId int `json:"uploader_id" gorm:"index"`
|
||||||
|
Link string `json:"link" gorm:"unique;index"`
|
||||||
|
UploadTime string `json:"upload_time"`
|
||||||
|
DownloadCounter int `json:"download_counter"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetAllFiles(startIdx int, num int) ([]*File, error) {
|
||||||
|
var files []*File
|
||||||
|
var err error
|
||||||
|
err = DB.Order("id desc").Limit(num).Offset(startIdx).Find(&files).Error
|
||||||
|
return files, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func SearchFiles(keyword string) (files []*File, err error) {
|
||||||
|
err = DB.Select([]string{"id", "filename", "description", "uploader", "uploader_id", "link", "upload_time", "download_counter"}).Where(
|
||||||
|
"filename LIKE ? or uploader LIKE ? or uploader_id = ?", keyword+"%", keyword+"%", keyword).Find(&files).Error
|
||||||
|
return files, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (file *File) Insert() error {
|
||||||
|
var err error
|
||||||
|
err = DB.Create(file).Error
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete Make sure link is valid! Because we will use os.Remove to delete it!
|
||||||
|
func (file *File) Delete() error {
|
||||||
|
var err error
|
||||||
|
err = DB.Delete(file).Error
|
||||||
|
err = os.Remove(path.Join(common.UploadPath, file.Link))
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func UpdateDownloadCounter(link string) {
|
||||||
|
DB.Model(&File{}).Where("link = ?", link).UpdateColumn("download_counter", gorm.Expr("download_counter + 1"))
|
||||||
|
}
|
82
model/main.go
Normal file
82
model/main.go
Normal file
@ -0,0 +1,82 @@
|
|||||||
|
package model
|
||||||
|
|
||||||
|
import (
|
||||||
|
"gin-template/common"
|
||||||
|
"gorm.io/driver/mysql"
|
||||||
|
"gorm.io/driver/sqlite"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
"os"
|
||||||
|
)
|
||||||
|
|
||||||
|
var DB *gorm.DB
|
||||||
|
|
||||||
|
func createRootAccountIfNeed() error {
|
||||||
|
var user User
|
||||||
|
//if user.Status != common.UserStatusEnabled {
|
||||||
|
if err := DB.First(&user).Error; err != nil {
|
||||||
|
common.SysLog("no user exists, create a root user for you: username is root, password is 123456")
|
||||||
|
hashedPassword, err := common.Password2Hash("123456")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
rootUser := User{
|
||||||
|
Username: "root",
|
||||||
|
Password: hashedPassword,
|
||||||
|
Role: common.RoleRootUser,
|
||||||
|
Status: common.UserStatusEnabled,
|
||||||
|
DisplayName: "Root User",
|
||||||
|
}
|
||||||
|
DB.Create(&rootUser)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func CountTable(tableName string) (num int64) {
|
||||||
|
DB.Table(tableName).Count(&num)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func InitDB() (err error) {
|
||||||
|
var db *gorm.DB
|
||||||
|
if os.Getenv("SQL_DSN") != "" {
|
||||||
|
// Use MySQL
|
||||||
|
db, err = gorm.Open(mysql.Open(os.Getenv("SQL_DSN")), &gorm.Config{
|
||||||
|
PrepareStmt: true, // precompile SQL
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
// Use SQLite
|
||||||
|
db, err = gorm.Open(sqlite.Open(common.SQLitePath), &gorm.Config{
|
||||||
|
PrepareStmt: true, // precompile SQL
|
||||||
|
})
|
||||||
|
common.SysLog("SQL_DSN not set, using SQLite as database")
|
||||||
|
}
|
||||||
|
if err == nil {
|
||||||
|
DB = db
|
||||||
|
err := db.AutoMigrate(&File{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
err = db.AutoMigrate(&User{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
err = db.AutoMigrate(&Option{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
err = createRootAccountIfNeed()
|
||||||
|
return err
|
||||||
|
} else {
|
||||||
|
common.FatalLog(err)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func CloseDB() error {
|
||||||
|
sqlDB, err := DB.DB()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
err = sqlDB.Close()
|
||||||
|
return err
|
||||||
|
}
|
135
model/option.go
Normal file
135
model/option.go
Normal file
@ -0,0 +1,135 @@
|
|||||||
|
package model
|
||||||
|
|
||||||
|
import (
|
||||||
|
"gin-template/common"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Option struct {
|
||||||
|
Key string `json:"key" gorm:"primaryKey"`
|
||||||
|
Value string `json:"value"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func AllOption() ([]*Option, error) {
|
||||||
|
var options []*Option
|
||||||
|
var err error
|
||||||
|
err = DB.Find(&options).Error
|
||||||
|
return options, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func InitOptionMap() {
|
||||||
|
common.OptionMapRWMutex.Lock()
|
||||||
|
common.OptionMap = make(map[string]string)
|
||||||
|
common.OptionMap["FileUploadPermission"] = strconv.Itoa(common.FileUploadPermission)
|
||||||
|
common.OptionMap["FileDownloadPermission"] = strconv.Itoa(common.FileDownloadPermission)
|
||||||
|
common.OptionMap["ImageUploadPermission"] = strconv.Itoa(common.ImageUploadPermission)
|
||||||
|
common.OptionMap["ImageDownloadPermission"] = strconv.Itoa(common.ImageDownloadPermission)
|
||||||
|
common.OptionMap["PasswordLoginEnabled"] = strconv.FormatBool(common.PasswordLoginEnabled)
|
||||||
|
common.OptionMap["PasswordRegisterEnabled"] = strconv.FormatBool(common.PasswordRegisterEnabled)
|
||||||
|
common.OptionMap["EmailVerificationEnabled"] = strconv.FormatBool(common.EmailVerificationEnabled)
|
||||||
|
common.OptionMap["GitHubOAuthEnabled"] = strconv.FormatBool(common.GitHubOAuthEnabled)
|
||||||
|
common.OptionMap["WeChatAuthEnabled"] = strconv.FormatBool(common.WeChatAuthEnabled)
|
||||||
|
common.OptionMap["TurnstileCheckEnabled"] = strconv.FormatBool(common.TurnstileCheckEnabled)
|
||||||
|
common.OptionMap["RegisterEnabled"] = strconv.FormatBool(common.RegisterEnabled)
|
||||||
|
common.OptionMap["SMTPServer"] = ""
|
||||||
|
common.OptionMap["SMTPAccount"] = ""
|
||||||
|
common.OptionMap["SMTPToken"] = ""
|
||||||
|
common.OptionMap["Notice"] = ""
|
||||||
|
common.OptionMap["About"] = ""
|
||||||
|
common.OptionMap["Footer"] = common.Footer
|
||||||
|
common.OptionMap["ServerAddress"] = ""
|
||||||
|
common.OptionMap["GitHubClientId"] = ""
|
||||||
|
common.OptionMap["GitHubClientSecret"] = ""
|
||||||
|
common.OptionMap["WeChatServerAddress"] = ""
|
||||||
|
common.OptionMap["WeChatServerToken"] = ""
|
||||||
|
common.OptionMap["WeChatAccountQRCodeImageURL"] = ""
|
||||||
|
common.OptionMap["TurnstileSiteKey"] = ""
|
||||||
|
common.OptionMap["TurnstileSecretKey"] = ""
|
||||||
|
common.OptionMapRWMutex.Unlock()
|
||||||
|
options, _ := AllOption()
|
||||||
|
for _, option := range options {
|
||||||
|
updateOptionMap(option.Key, option.Value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func UpdateOption(key string, value string) error {
|
||||||
|
// Save to database first
|
||||||
|
option := Option{
|
||||||
|
Key: key,
|
||||||
|
}
|
||||||
|
// https://gorm.io/docs/update.html#Save-All-Fields
|
||||||
|
DB.FirstOrCreate(&option, Option{Key: key})
|
||||||
|
option.Value = value
|
||||||
|
// Save is a combination function.
|
||||||
|
// If save value does not contain primary key, it will execute Create,
|
||||||
|
// otherwise it will execute Update (with all fields).
|
||||||
|
DB.Save(&option)
|
||||||
|
// Update OptionMap
|
||||||
|
updateOptionMap(key, value)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func updateOptionMap(key string, value string) {
|
||||||
|
common.OptionMapRWMutex.Lock()
|
||||||
|
defer common.OptionMapRWMutex.Unlock()
|
||||||
|
common.OptionMap[key] = value
|
||||||
|
if strings.HasSuffix(key, "Permission") {
|
||||||
|
intValue, _ := strconv.Atoi(value)
|
||||||
|
switch key {
|
||||||
|
case "FileUploadPermission":
|
||||||
|
common.FileUploadPermission = intValue
|
||||||
|
case "FileDownloadPermission":
|
||||||
|
common.FileDownloadPermission = intValue
|
||||||
|
case "ImageUploadPermission":
|
||||||
|
common.ImageUploadPermission = intValue
|
||||||
|
case "ImageDownloadPermission":
|
||||||
|
common.ImageDownloadPermission = intValue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.HasSuffix(key, "Enabled") {
|
||||||
|
boolValue := value == "true"
|
||||||
|
switch key {
|
||||||
|
case "PasswordRegisterEnabled":
|
||||||
|
common.PasswordRegisterEnabled = boolValue
|
||||||
|
case "PasswordLoginEnabled":
|
||||||
|
common.PasswordLoginEnabled = boolValue
|
||||||
|
case "EmailVerificationEnabled":
|
||||||
|
common.EmailVerificationEnabled = boolValue
|
||||||
|
case "GitHubOAuthEnabled":
|
||||||
|
common.GitHubOAuthEnabled = boolValue
|
||||||
|
case "WeChatAuthEnabled":
|
||||||
|
common.WeChatAuthEnabled = boolValue
|
||||||
|
case "TurnstileCheckEnabled":
|
||||||
|
common.TurnstileCheckEnabled = boolValue
|
||||||
|
case "RegisterEnabled":
|
||||||
|
common.RegisterEnabled = boolValue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
switch key {
|
||||||
|
case "SMTPServer":
|
||||||
|
common.SMTPServer = value
|
||||||
|
case "SMTPAccount":
|
||||||
|
common.SMTPAccount = value
|
||||||
|
case "SMTPToken":
|
||||||
|
common.SMTPToken = value
|
||||||
|
case "ServerAddress":
|
||||||
|
common.ServerAddress = value
|
||||||
|
case "GitHubClientId":
|
||||||
|
common.GitHubClientId = value
|
||||||
|
case "GitHubClientSecret":
|
||||||
|
common.GitHubClientSecret = value
|
||||||
|
case "Footer":
|
||||||
|
common.Footer = value
|
||||||
|
case "WeChatServerAddress":
|
||||||
|
common.WeChatServerAddress = value
|
||||||
|
case "WeChatServerToken":
|
||||||
|
common.WeChatServerToken = value
|
||||||
|
case "WeChatAccountQRCodeImageURL":
|
||||||
|
common.WeChatAccountQRCodeImageURL = value
|
||||||
|
case "TurnstileSiteKey":
|
||||||
|
common.TurnstileSiteKey = value
|
||||||
|
case "TurnstileSecretKey":
|
||||||
|
common.TurnstileSecretKey = value
|
||||||
|
}
|
||||||
|
}
|
190
model/user.go
Normal file
190
model/user.go
Normal file
@ -0,0 +1,190 @@
|
|||||||
|
package model
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"gin-template/common"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// User if you add sensitive fields, don't forget to clean them in setupLogin function.
|
||||||
|
// Otherwise, the sensitive information will be saved on local storage in plain text!
|
||||||
|
type User struct {
|
||||||
|
Id int `json:"id"`
|
||||||
|
Username string `json:"username" gorm:"unique;index" validate:"max=12"`
|
||||||
|
Password string `json:"password" gorm:"not null;" validate:"min=8,max=20"`
|
||||||
|
DisplayName string `json:"display_name" gorm:"index" validate:"max=20"`
|
||||||
|
Role int `json:"role" gorm:"type:int;default:1"` // admin, common
|
||||||
|
Status int `json:"status" gorm:"type:int;default:1"` // enabled, disabled
|
||||||
|
Token string `json:"token" gorm:"index"`
|
||||||
|
Email string `json:"email" gorm:"index" validate:"max=50"`
|
||||||
|
GitHubId string `json:"github_id" gorm:"column:github_id;index"`
|
||||||
|
WeChatId string `json:"wechat_id" gorm:"column:wechat_id;index"`
|
||||||
|
VerificationCode string `json:"verification_code" gorm:"-:all"` // this field is only for Email verification, don't save it to database!
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetMaxUserId() int {
|
||||||
|
var user User
|
||||||
|
DB.Last(&user)
|
||||||
|
return user.Id
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetAllUsers(startIdx int, num int) (users []*User, err error) {
|
||||||
|
err = DB.Order("id desc").Limit(num).Offset(startIdx).Select([]string{"id", "username", "display_name", "role", "status", "email"}).Find(&users).Error
|
||||||
|
return users, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func SearchUsers(keyword string) (users []*User, err error) {
|
||||||
|
err = DB.Select([]string{"id", "username", "display_name", "role", "status", "email"}).Where("id = ? or username LIKE ? or email LIKE ? or display_name LIKE ?", keyword, keyword+"%", keyword+"%", keyword+"%").Find(&users).Error
|
||||||
|
return users, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetUserById(id int, selectAll bool) (*User, error) {
|
||||||
|
if id == 0 {
|
||||||
|
return nil, errors.New("id 为空!")
|
||||||
|
}
|
||||||
|
user := User{Id: id}
|
||||||
|
var err error = nil
|
||||||
|
if selectAll {
|
||||||
|
err = DB.First(&user, "id = ?", id).Error
|
||||||
|
} else {
|
||||||
|
err = DB.Select([]string{"id", "username", "display_name", "role", "status", "email", "wechat_id", "github_id"}).First(&user, "id = ?", id).Error
|
||||||
|
}
|
||||||
|
return &user, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func DeleteUserById(id int) (err error) {
|
||||||
|
if id == 0 {
|
||||||
|
return errors.New("id 为空!")
|
||||||
|
}
|
||||||
|
user := User{Id: id}
|
||||||
|
return user.Delete()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (user *User) Insert() error {
|
||||||
|
var err error
|
||||||
|
if user.Password != "" {
|
||||||
|
user.Password, err = common.Password2Hash(user.Password)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
err = DB.Create(user).Error
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (user *User) Update(updatePassword bool) error {
|
||||||
|
var err error
|
||||||
|
if updatePassword {
|
||||||
|
user.Password, err = common.Password2Hash(user.Password)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
err = DB.Model(user).Updates(user).Error
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (user *User) Delete() error {
|
||||||
|
if user.Id == 0 {
|
||||||
|
return errors.New("id 为空!")
|
||||||
|
}
|
||||||
|
err := DB.Delete(user).Error
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidateAndFill check password & user status
|
||||||
|
func (user *User) ValidateAndFill() (err error) {
|
||||||
|
// When querying with struct, GORM will only query with non-zero fields,
|
||||||
|
// that means if your field’s value is 0, '', false or other zero values,
|
||||||
|
// it won’t be used to build query conditions
|
||||||
|
password := user.Password
|
||||||
|
if user.Username == "" || password == "" {
|
||||||
|
return errors.New("用户名或密码为空")
|
||||||
|
}
|
||||||
|
DB.Where(User{Username: user.Username}).First(user)
|
||||||
|
okay := common.ValidatePasswordAndHash(password, user.Password)
|
||||||
|
if !okay || user.Status != common.UserStatusEnabled {
|
||||||
|
return errors.New("用户名或密码错误,或用户已被封禁")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (user *User) FillUserById() error {
|
||||||
|
if user.Id == 0 {
|
||||||
|
return errors.New("id 为空!")
|
||||||
|
}
|
||||||
|
DB.Where(User{Id: user.Id}).First(user)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (user *User) FillUserByEmail() error {
|
||||||
|
if user.Email == "" {
|
||||||
|
return errors.New("email 为空!")
|
||||||
|
}
|
||||||
|
DB.Where(User{Email: user.Email}).First(user)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (user *User) FillUserByGitHubId() error {
|
||||||
|
if user.GitHubId == "" {
|
||||||
|
return errors.New("GitHub id 为空!")
|
||||||
|
}
|
||||||
|
DB.Where(User{GitHubId: user.GitHubId}).First(user)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (user *User) FillUserByWeChatId() error {
|
||||||
|
if user.WeChatId == "" {
|
||||||
|
return errors.New("WeChat id 为空!")
|
||||||
|
}
|
||||||
|
DB.Where(User{WeChatId: user.WeChatId}).First(user)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (user *User) FillUserByUsername() error {
|
||||||
|
if user.Username == "" {
|
||||||
|
return errors.New("username 为空!")
|
||||||
|
}
|
||||||
|
DB.Where(User{Username: user.Username}).First(user)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ValidateUserToken(token string) (user *User) {
|
||||||
|
if token == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
token = strings.Replace(token, "Bearer ", "", 1)
|
||||||
|
user = &User{}
|
||||||
|
if DB.Where("token = ?", token).First(user).RowsAffected == 1 {
|
||||||
|
return user
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsEmailAlreadyTaken(email string) bool {
|
||||||
|
return DB.Where("email = ?", email).Find(&User{}).RowsAffected == 1
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsWeChatIdAlreadyTaken(wechatId string) bool {
|
||||||
|
return DB.Where("wechat_id = ?", wechatId).Find(&User{}).RowsAffected == 1
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsGitHubIdAlreadyTaken(githubId string) bool {
|
||||||
|
return DB.Where("github_id = ?", githubId).Find(&User{}).RowsAffected == 1
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsUsernameAlreadyTaken(username string) bool {
|
||||||
|
return DB.Where("username = ?", username).Find(&User{}).RowsAffected == 1
|
||||||
|
}
|
||||||
|
|
||||||
|
func ResetUserPasswordByEmail(email string, password string) error {
|
||||||
|
if email == "" || password == "" {
|
||||||
|
return errors.New("邮箱地址或密码为空!")
|
||||||
|
}
|
||||||
|
hashedPassword, err := common.Password2Hash(password)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
err = DB.Model(&User{}).Where("email = ?", email).Update("password", hashedPassword).Error
|
||||||
|
return err
|
||||||
|
}
|
66
router/api-router.go
Normal file
66
router/api-router.go
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
package router
|
||||||
|
|
||||||
|
import (
|
||||||
|
"gin-template/controller"
|
||||||
|
"gin-template/middleware"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func SetApiRouter(router *gin.Engine) {
|
||||||
|
apiRouter := router.Group("/api")
|
||||||
|
apiRouter.Use(middleware.GlobalAPIRateLimit())
|
||||||
|
{
|
||||||
|
apiRouter.GET("/status", controller.GetStatus)
|
||||||
|
apiRouter.GET("/notice", controller.GetNotice)
|
||||||
|
apiRouter.GET("/about", controller.GetAbout)
|
||||||
|
apiRouter.GET("/verification", middleware.CriticalRateLimit(), middleware.TurnstileCheck(), controller.SendEmailVerification)
|
||||||
|
apiRouter.GET("/reset_password", middleware.CriticalRateLimit(), middleware.TurnstileCheck(), controller.SendPasswordResetEmail)
|
||||||
|
apiRouter.POST("/user/reset", middleware.CriticalRateLimit(), controller.ResetPassword)
|
||||||
|
apiRouter.GET("/oauth/github", middleware.CriticalRateLimit(), controller.GitHubOAuth)
|
||||||
|
apiRouter.GET("/oauth/wechat", middleware.CriticalRateLimit(), controller.WeChatAuth)
|
||||||
|
apiRouter.GET("/oauth/wechat/bind", middleware.CriticalRateLimit(), middleware.UserAuth(), controller.WeChatBind)
|
||||||
|
apiRouter.GET("/oauth/email/bind", middleware.CriticalRateLimit(), middleware.UserAuth(), controller.EmailBind)
|
||||||
|
|
||||||
|
userRoute := apiRouter.Group("/user")
|
||||||
|
{
|
||||||
|
userRoute.POST("/register", middleware.CriticalRateLimit(), middleware.TurnstileCheck(), controller.Register)
|
||||||
|
userRoute.POST("/login", middleware.CriticalRateLimit(), controller.Login)
|
||||||
|
userRoute.GET("/logout", controller.Logout)
|
||||||
|
|
||||||
|
selfRoute := userRoute.Group("/")
|
||||||
|
selfRoute.Use(middleware.UserAuth(), middleware.NoTokenAuth())
|
||||||
|
{
|
||||||
|
selfRoute.GET("/self", controller.GetSelf)
|
||||||
|
selfRoute.PUT("/self", controller.UpdateSelf)
|
||||||
|
selfRoute.DELETE("/self", controller.DeleteSelf)
|
||||||
|
selfRoute.GET("/token", controller.GenerateToken)
|
||||||
|
}
|
||||||
|
|
||||||
|
adminRoute := userRoute.Group("/")
|
||||||
|
adminRoute.Use(middleware.AdminAuth(), middleware.NoTokenAuth())
|
||||||
|
{
|
||||||
|
adminRoute.GET("/", controller.GetAllUsers)
|
||||||
|
adminRoute.GET("/search", controller.SearchUsers)
|
||||||
|
adminRoute.GET("/:id", controller.GetUser)
|
||||||
|
adminRoute.POST("/", controller.CreateUser)
|
||||||
|
adminRoute.POST("/manage", controller.ManageUser)
|
||||||
|
adminRoute.PUT("/", controller.UpdateUser)
|
||||||
|
adminRoute.DELETE("/:id", controller.DeleteUser)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
optionRoute := apiRouter.Group("/option")
|
||||||
|
optionRoute.Use(middleware.RootAuth(), middleware.NoTokenAuth())
|
||||||
|
{
|
||||||
|
optionRoute.GET("/", controller.GetOptions)
|
||||||
|
optionRoute.PUT("/", controller.UpdateOption)
|
||||||
|
}
|
||||||
|
fileRoute := apiRouter.Group("/file")
|
||||||
|
fileRoute.Use(middleware.AdminAuth())
|
||||||
|
{
|
||||||
|
fileRoute.GET("/", controller.GetAllFiles)
|
||||||
|
fileRoute.GET("/search", controller.SearchFiles)
|
||||||
|
fileRoute.POST("/", middleware.UploadRateLimit(), controller.UploadFile)
|
||||||
|
fileRoute.DELETE("/:id", controller.DeleteFile)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
11
router/main.go
Normal file
11
router/main.go
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
package router
|
||||||
|
|
||||||
|
import (
|
||||||
|
"embed"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func SetRouter(router *gin.Engine, buildFS embed.FS, indexPage []byte) {
|
||||||
|
SetApiRouter(router)
|
||||||
|
setWebRouter(router, buildFS, indexPage)
|
||||||
|
}
|
22
router/web-router.go
Normal file
22
router/web-router.go
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
package router
|
||||||
|
|
||||||
|
import (
|
||||||
|
"embed"
|
||||||
|
"gin-template/common"
|
||||||
|
"gin-template/controller"
|
||||||
|
"gin-template/middleware"
|
||||||
|
"github.com/gin-contrib/static"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
func setWebRouter(router *gin.Engine, buildFS embed.FS, indexPage []byte) {
|
||||||
|
router.Use(middleware.GlobalWebRateLimit())
|
||||||
|
fileDownloadRoute := router.Group("/")
|
||||||
|
fileDownloadRoute.GET("/upload/:file", middleware.DownloadRateLimit(), controller.DownloadFile)
|
||||||
|
router.Use(middleware.Cache())
|
||||||
|
router.Use(static.Serve("/", common.EmbedFolder(buildFS, "web/build")))
|
||||||
|
router.NoRoute(func(c *gin.Context) {
|
||||||
|
c.Data(http.StatusOK, "text/html; charset=utf-8", indexPage)
|
||||||
|
})
|
||||||
|
}
|
26
web/.gitignore
vendored
Normal file
26
web/.gitignore
vendored
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||||
|
|
||||||
|
# dependencies
|
||||||
|
/node_modules
|
||||||
|
/.pnp
|
||||||
|
.pnp.js
|
||||||
|
|
||||||
|
# testing
|
||||||
|
/coverage
|
||||||
|
|
||||||
|
# production
|
||||||
|
/build
|
||||||
|
|
||||||
|
# misc
|
||||||
|
.DS_Store
|
||||||
|
.env.local
|
||||||
|
.env.development.local
|
||||||
|
.env.test.local
|
||||||
|
.env.production.local
|
||||||
|
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
.idea
|
||||||
|
package-lock.json
|
||||||
|
yarn.lock
|
21
web/README.md
Normal file
21
web/README.md
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
# React Template
|
||||||
|
|
||||||
|
## Basic Usages
|
||||||
|
|
||||||
|
```shell
|
||||||
|
# Runs the app in the development mode
|
||||||
|
npm start
|
||||||
|
|
||||||
|
# Builds the app for production to the `build` folder
|
||||||
|
npm run build
|
||||||
|
```
|
||||||
|
|
||||||
|
If you want to change the default server, please set `REACT_APP_SERVER` environment variables before build,
|
||||||
|
for example: `REACT_APP_SERVER=http://your.domain.com`.
|
||||||
|
|
||||||
|
Before you start editing, make sure your `Actions on Save` options have `Optimize imports` & `Run Prettier` enabled.
|
||||||
|
|
||||||
|
## Reference
|
||||||
|
|
||||||
|
1. https://github.com/OIerDb-ng/OIerDb
|
||||||
|
2. https://github.com/cornflourblue/react-hooks-redux-registration-login-example
|
51
web/package.json
Normal file
51
web/package.json
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
{
|
||||||
|
"name": "react-template",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"dependencies": {
|
||||||
|
"axios": "^0.27.2",
|
||||||
|
"history": "^5.3.0",
|
||||||
|
"marked": "^4.1.1",
|
||||||
|
"react": "^18.2.0",
|
||||||
|
"react-dom": "^18.2.0",
|
||||||
|
"react-dropzone": "^14.2.3",
|
||||||
|
"react-router-dom": "^6.3.0",
|
||||||
|
"react-scripts": "5.0.1",
|
||||||
|
"react-toastify": "^9.0.8",
|
||||||
|
"react-turnstile": "^1.0.5",
|
||||||
|
"semantic-ui-css": "^2.5.0",
|
||||||
|
"semantic-ui-react": "^2.1.3"
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"start": "react-scripts start",
|
||||||
|
"build": "react-scripts build",
|
||||||
|
"test": "react-scripts test",
|
||||||
|
"eject": "react-scripts eject"
|
||||||
|
},
|
||||||
|
"eslintConfig": {
|
||||||
|
"extends": [
|
||||||
|
"react-app",
|
||||||
|
"react-app/jest"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"browserslist": {
|
||||||
|
"production": [
|
||||||
|
">0.2%",
|
||||||
|
"not dead",
|
||||||
|
"not op_mini all"
|
||||||
|
],
|
||||||
|
"development": [
|
||||||
|
"last 1 chrome version",
|
||||||
|
"last 1 firefox version",
|
||||||
|
"last 1 safari version"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"prettier": "^2.7.1"
|
||||||
|
},
|
||||||
|
"prettier": {
|
||||||
|
"singleQuote": true,
|
||||||
|
"jsxSingleQuote": true
|
||||||
|
},
|
||||||
|
"proxy": "http://localhost:3000"
|
||||||
|
}
|
BIN
web/public/favicon.ico
Normal file
BIN
web/public/favicon.ico
Normal file
Binary file not shown.
After Width: | Height: | Size: 3.8 KiB |
18
web/public/index.html
Normal file
18
web/public/index.html
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<link rel="icon" href="logo.png" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<meta name="theme-color" content="#ffffff" />
|
||||||
|
<meta
|
||||||
|
name="description"
|
||||||
|
content="Web site created using create-react-app"
|
||||||
|
/>
|
||||||
|
<title>项目模板</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||||
|
<div id="root"></div>
|
||||||
|
</body>
|
||||||
|
</html>
|
BIN
web/public/logo.png
Normal file
BIN
web/public/logo.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 5.2 KiB |
3
web/public/robots.txt
Normal file
3
web/public/robots.txt
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
# https://www.robotstxt.org/robotstxt.html
|
||||||
|
User-agent: *
|
||||||
|
Disallow:
|
170
web/src/App.js
Normal file
170
web/src/App.js
Normal file
@ -0,0 +1,170 @@
|
|||||||
|
import React, { lazy, Suspense, useContext, useEffect } from 'react';
|
||||||
|
import { Route, Routes } from 'react-router-dom';
|
||||||
|
import Loading from './components/Loading';
|
||||||
|
import User from './pages/User';
|
||||||
|
import { PrivateRoute } from './components/PrivateRoute';
|
||||||
|
import RegisterForm from './components/RegisterForm';
|
||||||
|
import LoginForm from './components/LoginForm';
|
||||||
|
import NotFound from './pages/NotFound';
|
||||||
|
import Setting from './pages/Setting';
|
||||||
|
import EditUser from './pages/User/EditUser';
|
||||||
|
import AddUser from './pages/User/AddUser';
|
||||||
|
import { API, showError, showNotice } from './helpers';
|
||||||
|
import PasswordResetForm from './components/PasswordResetForm';
|
||||||
|
import GitHubOAuth from './components/GitHubOAuth';
|
||||||
|
import PasswordResetConfirm from './components/PasswordResetConfirm';
|
||||||
|
import { UserContext } from './context/User';
|
||||||
|
import File from './pages/File';
|
||||||
|
|
||||||
|
const Home = lazy(() => import('./pages/Home'));
|
||||||
|
const About = lazy(() => import('./pages/About'));
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
const [userState, userDispatch] = useContext(UserContext);
|
||||||
|
|
||||||
|
const loadUser = () => {
|
||||||
|
let user = localStorage.getItem('user');
|
||||||
|
if (user) {
|
||||||
|
let data = JSON.parse(user);
|
||||||
|
userDispatch({ type: 'login', payload: data });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const loadStatus = async () => {
|
||||||
|
const res = await API.get('/api/status');
|
||||||
|
const { success, data } = res.data;
|
||||||
|
if (success) {
|
||||||
|
localStorage.setItem('status', JSON.stringify(data));
|
||||||
|
localStorage.setItem('footer_html', data.footer_html);
|
||||||
|
if (
|
||||||
|
data.version !== process.env.REACT_APP_VERSION &&
|
||||||
|
data.version !== 'v0.0.0' &&
|
||||||
|
process.env.REACT_APP_VERSION !== ''
|
||||||
|
) {
|
||||||
|
showNotice(
|
||||||
|
`新版本可用:${data.version},请使用快捷键 Shift + F5 刷新页面`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
showError('无法正常连接至服务器!');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
loadUser();
|
||||||
|
loadStatus().then();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Routes>
|
||||||
|
<Route
|
||||||
|
path='/'
|
||||||
|
element={
|
||||||
|
<Suspense fallback={<Loading></Loading>}>
|
||||||
|
<Home />
|
||||||
|
</Suspense>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path='/file'
|
||||||
|
element={
|
||||||
|
<PrivateRoute>
|
||||||
|
<File />
|
||||||
|
</PrivateRoute>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path='/user'
|
||||||
|
element={
|
||||||
|
<PrivateRoute>
|
||||||
|
<User />
|
||||||
|
</PrivateRoute>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path='/user/edit/:id'
|
||||||
|
element={
|
||||||
|
<Suspense fallback={<Loading></Loading>}>
|
||||||
|
<EditUser />
|
||||||
|
</Suspense>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path='/user/edit'
|
||||||
|
element={
|
||||||
|
<Suspense fallback={<Loading></Loading>}>
|
||||||
|
<EditUser />
|
||||||
|
</Suspense>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path='/user/add'
|
||||||
|
element={
|
||||||
|
<Suspense fallback={<Loading></Loading>}>
|
||||||
|
<AddUser />
|
||||||
|
</Suspense>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path='/user/reset'
|
||||||
|
element={
|
||||||
|
<Suspense fallback={<Loading></Loading>}>
|
||||||
|
<PasswordResetConfirm />
|
||||||
|
</Suspense>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path='/login'
|
||||||
|
element={
|
||||||
|
<Suspense fallback={<Loading></Loading>}>
|
||||||
|
<LoginForm />
|
||||||
|
</Suspense>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path='/register'
|
||||||
|
element={
|
||||||
|
<Suspense fallback={<Loading></Loading>}>
|
||||||
|
<RegisterForm />
|
||||||
|
</Suspense>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path='/reset'
|
||||||
|
element={
|
||||||
|
<Suspense fallback={<Loading></Loading>}>
|
||||||
|
<PasswordResetForm />
|
||||||
|
</Suspense>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path='/oauth/github'
|
||||||
|
element={
|
||||||
|
<Suspense fallback={<Loading></Loading>}>
|
||||||
|
<GitHubOAuth />
|
||||||
|
</Suspense>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path='/setting'
|
||||||
|
element={
|
||||||
|
<PrivateRoute>
|
||||||
|
<Suspense fallback={<Loading></Loading>}>
|
||||||
|
<Setting />
|
||||||
|
</Suspense>
|
||||||
|
</PrivateRoute>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path='/about'
|
||||||
|
element={
|
||||||
|
<Suspense fallback={<Loading></Loading>}>
|
||||||
|
<About />
|
||||||
|
</Suspense>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route path='*' element={NotFound} />
|
||||||
|
</Routes>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default App;
|
303
web/src/components/FilesTable.js
Normal file
303
web/src/components/FilesTable.js
Normal file
@ -0,0 +1,303 @@
|
|||||||
|
import React, { useEffect, useState } from 'react';
|
||||||
|
import {
|
||||||
|
Button,
|
||||||
|
Form,
|
||||||
|
Header,
|
||||||
|
Icon,
|
||||||
|
Pagination,
|
||||||
|
Popup,
|
||||||
|
Progress,
|
||||||
|
Segment,
|
||||||
|
Table,
|
||||||
|
} from 'semantic-ui-react';
|
||||||
|
import { API, copy, showError, showSuccess } from '../helpers';
|
||||||
|
import { useDropzone } from 'react-dropzone';
|
||||||
|
import { ITEMS_PER_PAGE } from '../constants';
|
||||||
|
|
||||||
|
const FilesTable = () => {
|
||||||
|
const [files, setFiles] = useState([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [activePage, setActivePage] = useState(1);
|
||||||
|
const [searchKeyword, setSearchKeyword] = useState('');
|
||||||
|
const [searching, setSearching] = useState(false);
|
||||||
|
const { acceptedFiles, getRootProps, getInputProps } = useDropzone();
|
||||||
|
const [uploading, setUploading] = useState(false);
|
||||||
|
const [uploadProgress, setUploadProgress] = useState('0');
|
||||||
|
|
||||||
|
const loadFiles = async (startIdx) => {
|
||||||
|
const res = await API.get(`/api/file/?p=${startIdx}`);
|
||||||
|
const { success, message, data } = res.data;
|
||||||
|
if (success) {
|
||||||
|
if (startIdx === 0) {
|
||||||
|
setFiles(data);
|
||||||
|
} else {
|
||||||
|
let newFiles = files;
|
||||||
|
newFiles.push(...data);
|
||||||
|
setFiles(newFiles);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
showError(message);
|
||||||
|
}
|
||||||
|
setLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const onPaginationChange = (e, { activePage }) => {
|
||||||
|
(async () => {
|
||||||
|
if (activePage === Math.ceil(files.length / ITEMS_PER_PAGE) + 1) {
|
||||||
|
// In this case we have to load more data and then append them.
|
||||||
|
await loadFiles(activePage - 1);
|
||||||
|
}
|
||||||
|
setActivePage(activePage);
|
||||||
|
})();
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
loadFiles(0)
|
||||||
|
.then()
|
||||||
|
.catch((reason) => {
|
||||||
|
showError(reason);
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const downloadFile = (link, filename) => {
|
||||||
|
let linkElement = document.createElement('a');
|
||||||
|
linkElement.download = filename;
|
||||||
|
linkElement.href = '/upload/' + link;
|
||||||
|
linkElement.click();
|
||||||
|
};
|
||||||
|
|
||||||
|
const copyLink = (link) => {
|
||||||
|
let url = window.location.origin + '/upload/' + link;
|
||||||
|
copy(url).then();
|
||||||
|
showSuccess('链接已复制到剪贴板');
|
||||||
|
};
|
||||||
|
|
||||||
|
const deleteFile = async (id, idx) => {
|
||||||
|
const res = await API.delete(`/api/file/${id}`);
|
||||||
|
const { success, message } = res.data;
|
||||||
|
if (success) {
|
||||||
|
let newFiles = [...files];
|
||||||
|
let realIdx = (activePage - 1) * ITEMS_PER_PAGE + idx;
|
||||||
|
newFiles[realIdx].deleted = true;
|
||||||
|
// newFiles.splice(idx, 1);
|
||||||
|
setFiles(newFiles);
|
||||||
|
showSuccess('文件已删除!');
|
||||||
|
} else {
|
||||||
|
showError(message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const searchFiles = async () => {
|
||||||
|
if (searchKeyword === '') {
|
||||||
|
// if keyword is blank, load files instead.
|
||||||
|
await loadFiles(0);
|
||||||
|
setActivePage(1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setSearching(true);
|
||||||
|
const res = await API.get(`/api/file/search?keyword=${searchKeyword}`);
|
||||||
|
const { success, message, data } = res.data;
|
||||||
|
if (success) {
|
||||||
|
setFiles(data);
|
||||||
|
setActivePage(1);
|
||||||
|
} else {
|
||||||
|
showError(message);
|
||||||
|
}
|
||||||
|
setSearching(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleKeywordChange = async (e, { value }) => {
|
||||||
|
setSearchKeyword(value.trim());
|
||||||
|
};
|
||||||
|
|
||||||
|
const sortFile = (key) => {
|
||||||
|
if (files.length === 0) return;
|
||||||
|
setLoading(true);
|
||||||
|
let sortedUsers = [...files];
|
||||||
|
sortedUsers.sort((a, b) => {
|
||||||
|
return ('' + a[key]).localeCompare(b[key]);
|
||||||
|
});
|
||||||
|
if (sortedUsers[0].id === files[0].id) {
|
||||||
|
sortedUsers.reverse();
|
||||||
|
}
|
||||||
|
setFiles(sortedUsers);
|
||||||
|
setLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const uploadFiles = async () => {
|
||||||
|
if (acceptedFiles.length === 0) return;
|
||||||
|
setUploading(true);
|
||||||
|
let formData = new FormData();
|
||||||
|
for (let i = 0; i < acceptedFiles.length; i++) {
|
||||||
|
formData.append('file', acceptedFiles[i]);
|
||||||
|
}
|
||||||
|
const res = await API.post(`/api/file`, formData, {
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'multipart/form-data',
|
||||||
|
},
|
||||||
|
onUploadProgress: (e) => {
|
||||||
|
let uploadProgress = ((e.loaded / e.total) * 100).toFixed(2);
|
||||||
|
setUploadProgress(uploadProgress);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const { success, message } = res.data;
|
||||||
|
if (success) {
|
||||||
|
showSuccess(`${acceptedFiles.length} 个文件上传成功!`);
|
||||||
|
} else {
|
||||||
|
showError(message);
|
||||||
|
}
|
||||||
|
setUploading(false);
|
||||||
|
setUploadProgress('0');
|
||||||
|
setSearchKeyword('');
|
||||||
|
loadFiles(0).then();
|
||||||
|
setActivePage(1);
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
uploadFiles().then();
|
||||||
|
}, [acceptedFiles]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Segment
|
||||||
|
placeholder
|
||||||
|
{...getRootProps({ className: 'dropzone' })}
|
||||||
|
loading={uploading || loading}
|
||||||
|
style={{ cursor: 'pointer' }}
|
||||||
|
>
|
||||||
|
<Header icon>
|
||||||
|
<Icon name='file outline' />
|
||||||
|
拖拽上传或点击上传
|
||||||
|
<input {...getInputProps()} />
|
||||||
|
</Header>
|
||||||
|
</Segment>
|
||||||
|
{uploading ? (
|
||||||
|
<Progress
|
||||||
|
percent={uploadProgress}
|
||||||
|
success
|
||||||
|
progress='percent'
|
||||||
|
></Progress>
|
||||||
|
) : (
|
||||||
|
<></>
|
||||||
|
)}
|
||||||
|
<Form onSubmit={searchFiles}>
|
||||||
|
<Form.Input
|
||||||
|
icon='search'
|
||||||
|
fluid
|
||||||
|
iconPosition='left'
|
||||||
|
placeholder='搜索文件的名称,上传者以及描述信息 ...'
|
||||||
|
value={searchKeyword}
|
||||||
|
loading={searching}
|
||||||
|
onChange={handleKeywordChange}
|
||||||
|
/>
|
||||||
|
</Form>
|
||||||
|
|
||||||
|
<Table basic>
|
||||||
|
<Table.Header>
|
||||||
|
<Table.Row>
|
||||||
|
<Table.HeaderCell
|
||||||
|
style={{ cursor: 'pointer' }}
|
||||||
|
onClick={() => {
|
||||||
|
sortFile('filename');
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
文件名
|
||||||
|
</Table.HeaderCell>
|
||||||
|
<Table.HeaderCell
|
||||||
|
style={{ cursor: 'pointer' }}
|
||||||
|
onClick={() => {
|
||||||
|
sortFile('uploader_id');
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
上传者
|
||||||
|
</Table.HeaderCell>
|
||||||
|
<Table.HeaderCell
|
||||||
|
style={{ cursor: 'pointer' }}
|
||||||
|
onClick={() => {
|
||||||
|
sortFile('email');
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
上传时间
|
||||||
|
</Table.HeaderCell>
|
||||||
|
<Table.HeaderCell>操作</Table.HeaderCell>
|
||||||
|
</Table.Row>
|
||||||
|
</Table.Header>
|
||||||
|
|
||||||
|
<Table.Body>
|
||||||
|
{files
|
||||||
|
.slice(
|
||||||
|
(activePage - 1) * ITEMS_PER_PAGE,
|
||||||
|
activePage * ITEMS_PER_PAGE
|
||||||
|
)
|
||||||
|
.map((file, idx) => {
|
||||||
|
if (file.deleted) return <></>;
|
||||||
|
return (
|
||||||
|
<Table.Row key={file.id}>
|
||||||
|
<Table.Cell>
|
||||||
|
<a href={'/upload/' + file.link} target='_blank'>
|
||||||
|
{file.filename}
|
||||||
|
</a>
|
||||||
|
</Table.Cell>
|
||||||
|
<Popup
|
||||||
|
content={'上传者 ID:' + file.uploader_id}
|
||||||
|
trigger={<Table.Cell>{file.uploader}</Table.Cell>}
|
||||||
|
/>
|
||||||
|
<Table.Cell>{file.upload_time}</Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
<div>
|
||||||
|
<Button
|
||||||
|
size={'small'}
|
||||||
|
positive
|
||||||
|
onClick={() => {
|
||||||
|
downloadFile(file.link, file.filename);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
下载
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size={'small'}
|
||||||
|
negative
|
||||||
|
onClick={() => {
|
||||||
|
deleteFile(file.id, idx).then();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
删除
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size={'small'}
|
||||||
|
onClick={() => {
|
||||||
|
copyLink(file.link);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
复制链接
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</Table.Cell>
|
||||||
|
</Table.Row>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</Table.Body>
|
||||||
|
|
||||||
|
<Table.Footer>
|
||||||
|
<Table.Row>
|
||||||
|
<Table.HeaderCell colSpan='6'>
|
||||||
|
<Pagination
|
||||||
|
floated='right'
|
||||||
|
activePage={activePage}
|
||||||
|
onPageChange={onPaginationChange}
|
||||||
|
size='small'
|
||||||
|
siblingRange={1}
|
||||||
|
totalPages={
|
||||||
|
Math.ceil(files.length / ITEMS_PER_PAGE) +
|
||||||
|
(files.length % ITEMS_PER_PAGE === 0 ? 1 : 0)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</Table.HeaderCell>
|
||||||
|
</Table.Row>
|
||||||
|
</Table.Footer>
|
||||||
|
</Table>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default FilesTable;
|
44
web/src/components/Footer.js
Normal file
44
web/src/components/Footer.js
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
import React, { useEffect, useState } from 'react';
|
||||||
|
|
||||||
|
import { Container, Segment } from 'semantic-ui-react';
|
||||||
|
|
||||||
|
const Footer = () => {
|
||||||
|
const [Footer, setFooter] = useState('');
|
||||||
|
useEffect(() => {
|
||||||
|
let savedFooter = localStorage.getItem('footer_html');
|
||||||
|
if (!savedFooter) savedFooter = '';
|
||||||
|
setFooter(savedFooter);
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Segment vertical>
|
||||||
|
<Container textAlign="center">
|
||||||
|
{Footer === '' ? (
|
||||||
|
<div className="custom-footer">
|
||||||
|
<a
|
||||||
|
href="https://github.com/songquanpeng/gin-template"
|
||||||
|
target="_blank"
|
||||||
|
>
|
||||||
|
项目模板 {process.env.REACT_APP_VERSION}{' '}
|
||||||
|
</a>
|
||||||
|
由{' '}
|
||||||
|
<a href="https://github.com/songquanpeng" target="_blank">
|
||||||
|
JustSong
|
||||||
|
</a>{' '}
|
||||||
|
构建,源代码遵循{' '}
|
||||||
|
<a href="https://opensource.org/licenses/mit-license.php">
|
||||||
|
MIT 协议
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div
|
||||||
|
className="custom-footer"
|
||||||
|
dangerouslySetInnerHTML={{ __html: Footer }}
|
||||||
|
></div>
|
||||||
|
)}
|
||||||
|
</Container>
|
||||||
|
</Segment>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Footer;
|
57
web/src/components/GitHubOAuth.js
Normal file
57
web/src/components/GitHubOAuth.js
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
import React, { useContext, useEffect, useState } from 'react';
|
||||||
|
import { Dimmer, Loader, Segment } from 'semantic-ui-react';
|
||||||
|
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||||
|
import { API, showError, showSuccess } from '../helpers';
|
||||||
|
import { UserContext } from '../context/User';
|
||||||
|
|
||||||
|
const GitHubOAuth = () => {
|
||||||
|
const [searchParams, setSearchParams] = useSearchParams();
|
||||||
|
|
||||||
|
const [userState, userDispatch] = useContext(UserContext);
|
||||||
|
const [prompt, setPrompt] = useState('处理中...');
|
||||||
|
const [processing, setProcessing] = useState(true);
|
||||||
|
|
||||||
|
let navigate = useNavigate();
|
||||||
|
|
||||||
|
const sendCode = async (code, count) => {
|
||||||
|
const res = await API.get(`/api/oauth/github?code=${code}`);
|
||||||
|
const { success, message, data } = res.data;
|
||||||
|
if (success) {
|
||||||
|
if (message === 'bind') {
|
||||||
|
showSuccess('绑定成功!');
|
||||||
|
navigate('/setting');
|
||||||
|
} else {
|
||||||
|
userDispatch({ type: 'login', payload: data });
|
||||||
|
localStorage.setItem('user', JSON.stringify(data));
|
||||||
|
showSuccess('登录成功!');
|
||||||
|
navigate('/');
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
showError(message);
|
||||||
|
if (count === 0) {
|
||||||
|
setPrompt(`操作失败,重定向至登录界面中...`);
|
||||||
|
navigate('/setting'); // in case this is failed to bind GitHub
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
count++;
|
||||||
|
setPrompt(`出现错误,第 ${count} 次重试中...`);
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, count * 2000));
|
||||||
|
await sendCode(code, count);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let code = searchParams.get('code');
|
||||||
|
sendCode(code, 0).then();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Segment style={{ minHeight: '300px' }}>
|
||||||
|
<Dimmer active inverted>
|
||||||
|
<Loader size='large'>{prompt}</Loader>
|
||||||
|
</Dimmer>
|
||||||
|
</Segment>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default GitHubOAuth;
|
192
web/src/components/Header.js
Normal file
192
web/src/components/Header.js
Normal file
@ -0,0 +1,192 @@
|
|||||||
|
import React, { useContext, useState } from 'react';
|
||||||
|
import { Link, useNavigate } from 'react-router-dom';
|
||||||
|
import { UserContext } from '../context/User';
|
||||||
|
|
||||||
|
import { Button, Container, Dropdown, Icon, Menu, Segment } from 'semantic-ui-react';
|
||||||
|
import { API, isAdmin, isMobile, showSuccess } from '../helpers';
|
||||||
|
import '../index.css';
|
||||||
|
|
||||||
|
// Header Buttons
|
||||||
|
const headerButtons = [
|
||||||
|
{
|
||||||
|
name: '首页',
|
||||||
|
to: '/',
|
||||||
|
icon: 'home',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '文件',
|
||||||
|
to: '/file',
|
||||||
|
icon: 'file',
|
||||||
|
admin: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '用户',
|
||||||
|
to: '/user',
|
||||||
|
icon: 'user',
|
||||||
|
admin: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '设置',
|
||||||
|
to: '/setting',
|
||||||
|
icon: 'setting',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '关于',
|
||||||
|
to: '/about',
|
||||||
|
icon: 'info circle',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const Header = () => {
|
||||||
|
const [userState, userDispatch] = useContext(UserContext);
|
||||||
|
let navigate = useNavigate();
|
||||||
|
|
||||||
|
const [showSidebar, setShowSidebar] = useState(false);
|
||||||
|
|
||||||
|
async function logout() {
|
||||||
|
setShowSidebar(false);
|
||||||
|
await API.get('/api/user/logout');
|
||||||
|
showSuccess('注销成功!');
|
||||||
|
userDispatch({ type: 'logout' });
|
||||||
|
localStorage.removeItem('user');
|
||||||
|
navigate('/login');
|
||||||
|
}
|
||||||
|
|
||||||
|
const toggleSidebar = () => {
|
||||||
|
setShowSidebar(!showSidebar);
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderButtons = (isMobile) => {
|
||||||
|
return headerButtons.map((button) => {
|
||||||
|
if (button.admin && !isAdmin()) return <></>;
|
||||||
|
if (isMobile) {
|
||||||
|
return (
|
||||||
|
<Menu.Item
|
||||||
|
onClick={() => {
|
||||||
|
navigate(button.to);
|
||||||
|
setShowSidebar(false);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{button.name}
|
||||||
|
</Menu.Item>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<Menu.Item key={button.name} as={Link} to={button.to}>
|
||||||
|
<Icon name={button.icon} />
|
||||||
|
{button.name}
|
||||||
|
</Menu.Item>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
if (isMobile()) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Menu
|
||||||
|
borderless
|
||||||
|
size='large'
|
||||||
|
style={
|
||||||
|
showSidebar
|
||||||
|
? {
|
||||||
|
borderBottom: 'none',
|
||||||
|
marginBottom: '0',
|
||||||
|
borderTop: 'none',
|
||||||
|
height: '51px',
|
||||||
|
}
|
||||||
|
: { borderTop: 'none', height: '52px' }
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Container>
|
||||||
|
<Menu.Item as={Link} to='/'>
|
||||||
|
<img
|
||||||
|
src='/logo.png'
|
||||||
|
alt='logo'
|
||||||
|
style={{ marginRight: '0.75em' }}
|
||||||
|
/>
|
||||||
|
<div style={{ fontSize: '20px' }}>
|
||||||
|
<b>项目模板</b>
|
||||||
|
</div>
|
||||||
|
</Menu.Item>
|
||||||
|
<Menu.Menu position='right'>
|
||||||
|
<Menu.Item onClick={toggleSidebar}>
|
||||||
|
<Icon name={showSidebar ? 'close' : 'sidebar'} />
|
||||||
|
</Menu.Item>
|
||||||
|
</Menu.Menu>
|
||||||
|
</Container>
|
||||||
|
</Menu>
|
||||||
|
{showSidebar ? (
|
||||||
|
<Segment style={{ marginTop: 0, borderTop: '0' }}>
|
||||||
|
<Menu secondary vertical style={{ width: '100%', margin: 0 }}>
|
||||||
|
{renderButtons(true)}
|
||||||
|
<Menu.Item>
|
||||||
|
{userState.user ? (
|
||||||
|
<Button onClick={logout}>注销</Button>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
setShowSidebar(false);
|
||||||
|
navigate('/login');
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
登录
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
setShowSidebar(false);
|
||||||
|
navigate('/register');
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
注册
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Menu.Item>
|
||||||
|
</Menu>
|
||||||
|
</Segment>
|
||||||
|
) : (
|
||||||
|
<></>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Menu borderless style={{ borderTop: 'none' }}>
|
||||||
|
<Container>
|
||||||
|
<Menu.Item as={Link} to='/' className={'hide-on-mobile'}>
|
||||||
|
<img src='/logo.png' alt='logo' style={{ marginRight: '0.75em' }} />
|
||||||
|
<div style={{ fontSize: '20px' }}>
|
||||||
|
<b>项目模板</b>
|
||||||
|
</div>
|
||||||
|
</Menu.Item>
|
||||||
|
{renderButtons(false)}
|
||||||
|
<Menu.Menu position='right'>
|
||||||
|
{userState.user ? (
|
||||||
|
<Dropdown
|
||||||
|
text={userState.user.username}
|
||||||
|
pointing
|
||||||
|
className='link item'
|
||||||
|
>
|
||||||
|
<Dropdown.Menu>
|
||||||
|
<Dropdown.Item onClick={logout}>注销</Dropdown.Item>
|
||||||
|
</Dropdown.Menu>
|
||||||
|
</Dropdown>
|
||||||
|
) : (
|
||||||
|
<Menu.Item
|
||||||
|
name='登录'
|
||||||
|
as={Link}
|
||||||
|
to='/login'
|
||||||
|
className='btn btn-link'
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</Menu.Menu>
|
||||||
|
</Container>
|
||||||
|
</Menu>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Header;
|
14
web/src/components/Loading.js
Normal file
14
web/src/components/Loading.js
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { Segment, Dimmer, Loader } from 'semantic-ui-react';
|
||||||
|
|
||||||
|
const Loading = ({ prompt: name = 'page' }) => {
|
||||||
|
return (
|
||||||
|
<Segment style={{ height: 100 }}>
|
||||||
|
<Dimmer active inverted>
|
||||||
|
<Loader indeterminate>加载{name}中...</Loader>
|
||||||
|
</Dimmer>
|
||||||
|
</Segment>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Loading;
|
198
web/src/components/LoginForm.js
Normal file
198
web/src/components/LoginForm.js
Normal file
@ -0,0 +1,198 @@
|
|||||||
|
import React, { useContext, useEffect, useState } from 'react';
|
||||||
|
import {
|
||||||
|
Button,
|
||||||
|
Divider,
|
||||||
|
Form,
|
||||||
|
Grid,
|
||||||
|
Header,
|
||||||
|
Image,
|
||||||
|
Message,
|
||||||
|
Modal,
|
||||||
|
Segment,
|
||||||
|
} from 'semantic-ui-react';
|
||||||
|
import { Link, useNavigate } from 'react-router-dom';
|
||||||
|
import { UserContext } from '../context/User';
|
||||||
|
import { API, showError, showSuccess } from '../helpers';
|
||||||
|
|
||||||
|
const LoginForm = () => {
|
||||||
|
const [inputs, setInputs] = useState({
|
||||||
|
username: '',
|
||||||
|
password: '',
|
||||||
|
wechat_verification_code: '',
|
||||||
|
});
|
||||||
|
const [submitted, setSubmitted] = useState(false);
|
||||||
|
const { username, password } = inputs;
|
||||||
|
const [userState, userDispatch] = useContext(UserContext);
|
||||||
|
let navigate = useNavigate();
|
||||||
|
|
||||||
|
const [status, setStatus] = useState({});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let status = localStorage.getItem('status');
|
||||||
|
if (status) {
|
||||||
|
status = JSON.parse(status);
|
||||||
|
setStatus(status);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const [showWeChatLoginModal, setShowWeChatLoginModal] = useState(false);
|
||||||
|
|
||||||
|
const onGitHubOAuthClicked = () => {
|
||||||
|
window.open(
|
||||||
|
`https://github.com/login/oauth/authorize?client_id=${status.github_client_id}&scope=user:email`
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const onWeChatLoginClicked = () => {
|
||||||
|
setShowWeChatLoginModal(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const onSubmitWeChatVerificationCode = async () => {
|
||||||
|
const res = await API.get(
|
||||||
|
`/api/oauth/wechat?code=${inputs.wechat_verification_code}`
|
||||||
|
);
|
||||||
|
const { success, message, data } = res.data;
|
||||||
|
if (success) {
|
||||||
|
userDispatch({ type: 'login', payload: data });
|
||||||
|
localStorage.setItem('user', JSON.stringify(data));
|
||||||
|
navigate('/');
|
||||||
|
showSuccess('登录成功!');
|
||||||
|
setShowWeChatLoginModal(false);
|
||||||
|
} else {
|
||||||
|
showError(message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
function handleChange(e) {
|
||||||
|
const { name, value } = e.target;
|
||||||
|
setInputs((inputs) => ({ ...inputs, [name]: value }));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSubmit(e) {
|
||||||
|
setSubmitted(true);
|
||||||
|
if (username && password) {
|
||||||
|
const res = await API.post('/api/user/login', {
|
||||||
|
username,
|
||||||
|
password,
|
||||||
|
});
|
||||||
|
const { success, message, data } = res.data;
|
||||||
|
if (success) {
|
||||||
|
userDispatch({ type: 'login', payload: data });
|
||||||
|
localStorage.setItem('user', JSON.stringify(data));
|
||||||
|
navigate('/');
|
||||||
|
showSuccess('登录成功!');
|
||||||
|
} else {
|
||||||
|
showError(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Grid textAlign="center" style={{ marginTop: '48px' }}>
|
||||||
|
<Grid.Column style={{ maxWidth: 450 }}>
|
||||||
|
<Header as="h2" color="teal" textAlign="center">
|
||||||
|
<Image src="/logo.png" /> 用户登录
|
||||||
|
</Header>
|
||||||
|
<Form size="large">
|
||||||
|
<Segment>
|
||||||
|
<Form.Input
|
||||||
|
fluid
|
||||||
|
icon="user"
|
||||||
|
iconPosition="left"
|
||||||
|
placeholder="用户名"
|
||||||
|
name="username"
|
||||||
|
value={username}
|
||||||
|
onChange={handleChange}
|
||||||
|
/>
|
||||||
|
<Form.Input
|
||||||
|
fluid
|
||||||
|
icon="lock"
|
||||||
|
iconPosition="left"
|
||||||
|
placeholder="密码"
|
||||||
|
name="password"
|
||||||
|
type="password"
|
||||||
|
value={password}
|
||||||
|
onChange={handleChange}
|
||||||
|
/>
|
||||||
|
<Button color="teal" fluid size="large" onClick={handleSubmit}>
|
||||||
|
登录
|
||||||
|
</Button>
|
||||||
|
</Segment>
|
||||||
|
</Form>
|
||||||
|
<Message>
|
||||||
|
忘记密码?
|
||||||
|
<Link to="/reset" className="btn btn-link">
|
||||||
|
点击重置
|
||||||
|
</Link>
|
||||||
|
; 没有账户?
|
||||||
|
<Link to="/register" className="btn btn-link">
|
||||||
|
点击注册
|
||||||
|
</Link>
|
||||||
|
</Message>
|
||||||
|
{status.github_oauth || status.wechat_login ? (
|
||||||
|
<>
|
||||||
|
<Divider horizontal>Or</Divider>
|
||||||
|
{status.github_oauth ? (
|
||||||
|
<Button
|
||||||
|
circular
|
||||||
|
color="black"
|
||||||
|
icon="github"
|
||||||
|
onClick={onGitHubOAuthClicked}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<></>
|
||||||
|
)}
|
||||||
|
{status.wechat_login ? (
|
||||||
|
<Button
|
||||||
|
circular
|
||||||
|
color="green"
|
||||||
|
icon="wechat"
|
||||||
|
onClick={onWeChatLoginClicked}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<></>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<></>
|
||||||
|
)}
|
||||||
|
<Modal
|
||||||
|
onClose={() => setShowWeChatLoginModal(false)}
|
||||||
|
onOpen={() => setShowWeChatLoginModal(true)}
|
||||||
|
open={showWeChatLoginModal}
|
||||||
|
size={'mini'}
|
||||||
|
>
|
||||||
|
<Modal.Content>
|
||||||
|
<Modal.Description>
|
||||||
|
<Image src={status.wechat_qrcode} fluid />
|
||||||
|
<div style={{ textAlign: 'center' }}>
|
||||||
|
<p>
|
||||||
|
微信扫码关注公众号,输入「验证码」获取验证码(三分钟内有效)
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Form size="large">
|
||||||
|
<Form.Input
|
||||||
|
fluid
|
||||||
|
placeholder="验证码"
|
||||||
|
name="wechat_verification_code"
|
||||||
|
value={inputs.wechat_verification_code}
|
||||||
|
onChange={handleChange}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
color="teal"
|
||||||
|
fluid
|
||||||
|
size="large"
|
||||||
|
onClick={onSubmitWeChatVerificationCode}
|
||||||
|
>
|
||||||
|
登录
|
||||||
|
</Button>
|
||||||
|
</Form>
|
||||||
|
</Modal.Description>
|
||||||
|
</Modal.Content>
|
||||||
|
</Modal>
|
||||||
|
</Grid.Column>
|
||||||
|
</Grid>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default LoginForm;
|
161
web/src/components/OtherSetting.js
Normal file
161
web/src/components/OtherSetting.js
Normal file
@ -0,0 +1,161 @@
|
|||||||
|
import React, { useEffect, useState } from 'react';
|
||||||
|
import { Button, Divider, Form, Grid, Header, Modal } from 'semantic-ui-react';
|
||||||
|
import { API, showError, showSuccess } from '../helpers';
|
||||||
|
import { marked } from 'marked';
|
||||||
|
|
||||||
|
const OtherSetting = () => {
|
||||||
|
let [inputs, setInputs] = useState({
|
||||||
|
Footer: '',
|
||||||
|
Notice: '',
|
||||||
|
About: '',
|
||||||
|
});
|
||||||
|
let originInputs = {};
|
||||||
|
let [loading, setLoading] = useState(false);
|
||||||
|
const [showUpdateModal, setShowUpdateModal] = useState(false);
|
||||||
|
const [updateData, setUpdateData] = useState({
|
||||||
|
tag_name: '',
|
||||||
|
content: '',
|
||||||
|
});
|
||||||
|
|
||||||
|
const getOptions = async () => {
|
||||||
|
const res = await API.get('/api/option');
|
||||||
|
const { success, message, data } = res.data;
|
||||||
|
if (success) {
|
||||||
|
let newInputs = {};
|
||||||
|
data.forEach((item) => {
|
||||||
|
if (item.key in inputs) {
|
||||||
|
newInputs[item.key] = item.value;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
setInputs(newInputs);
|
||||||
|
originInputs = newInputs;
|
||||||
|
} else {
|
||||||
|
showError(message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
getOptions().then();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const updateOption = async (key, value) => {
|
||||||
|
setLoading(true);
|
||||||
|
const res = await API.put('/api/option', {
|
||||||
|
key,
|
||||||
|
value,
|
||||||
|
});
|
||||||
|
const { success, message } = res.data;
|
||||||
|
if (success) {
|
||||||
|
setInputs((inputs) => ({ ...inputs, [key]: value }));
|
||||||
|
} else {
|
||||||
|
showError(message);
|
||||||
|
}
|
||||||
|
setLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleInputChange = async (e, { name, value }) => {
|
||||||
|
setInputs((inputs) => ({ ...inputs, [name]: value }));
|
||||||
|
};
|
||||||
|
|
||||||
|
const submitNotice = async () => {
|
||||||
|
await updateOption('Notice', inputs.Notice);
|
||||||
|
};
|
||||||
|
|
||||||
|
const submitFooter = async () => {
|
||||||
|
await updateOption('Footer', inputs.Footer);
|
||||||
|
};
|
||||||
|
|
||||||
|
const submitAbout = async () => {
|
||||||
|
await updateOption('About', inputs.About);
|
||||||
|
};
|
||||||
|
|
||||||
|
const openGitHubRelease = () => {
|
||||||
|
window.location =
|
||||||
|
'https://github.com/songquanpeng/gin-template/releases/latest';
|
||||||
|
};
|
||||||
|
|
||||||
|
const checkUpdate = async () => {
|
||||||
|
const res = await API.get(
|
||||||
|
'https://api.github.com/repos/songquanpeng/gin-template/releases/latest'
|
||||||
|
);
|
||||||
|
const { tag_name, body } = res.data;
|
||||||
|
if (tag_name === process.env.REACT_APP_VERSION) {
|
||||||
|
showSuccess(`已是最新版本:${tag_name}`);
|
||||||
|
} else {
|
||||||
|
setUpdateData({
|
||||||
|
tag_name: tag_name,
|
||||||
|
content: marked.parse(body),
|
||||||
|
});
|
||||||
|
setShowUpdateModal(true);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Grid columns={1}>
|
||||||
|
<Grid.Column>
|
||||||
|
<Form loading={loading}>
|
||||||
|
<Header as='h3'>通用设置</Header>
|
||||||
|
<Form.Button onClick={checkUpdate}>检查更新</Form.Button>
|
||||||
|
<Form.Group widths='equal'>
|
||||||
|
<Form.TextArea
|
||||||
|
label='公告'
|
||||||
|
placeholder='在此输入新的公告内容'
|
||||||
|
value={inputs.Notice}
|
||||||
|
name='Notice'
|
||||||
|
onChange={handleInputChange}
|
||||||
|
style={{ minHeight: 150, fontFamily: 'JetBrains Mono, Consolas' }}
|
||||||
|
/>
|
||||||
|
</Form.Group>
|
||||||
|
<Form.Button onClick={submitNotice}>保存公告</Form.Button>
|
||||||
|
<Divider />
|
||||||
|
<Header as='h3'>个性化设置</Header>
|
||||||
|
<Form.Group widths='equal'>
|
||||||
|
<Form.TextArea
|
||||||
|
label='关于'
|
||||||
|
placeholder='在此输入新的关于内容,支持 Markdown & HTML 代码'
|
||||||
|
value={inputs.About}
|
||||||
|
name='About'
|
||||||
|
onChange={handleInputChange}
|
||||||
|
style={{ minHeight: 150, fontFamily: 'JetBrains Mono, Consolas' }}
|
||||||
|
/>
|
||||||
|
</Form.Group>
|
||||||
|
<Form.Button onClick={submitAbout}>保存关于</Form.Button>
|
||||||
|
<Form.Group widths='equal'>
|
||||||
|
<Form.Input
|
||||||
|
label='页脚'
|
||||||
|
placeholder='在此输入新的页脚,留空则使用默认页脚,支持 HTML 代码'
|
||||||
|
value={inputs.Footer}
|
||||||
|
name='Footer'
|
||||||
|
onChange={handleInputChange}
|
||||||
|
/>
|
||||||
|
</Form.Group>
|
||||||
|
<Form.Button onClick={submitFooter}>设置页脚</Form.Button>
|
||||||
|
</Form>
|
||||||
|
</Grid.Column>
|
||||||
|
<Modal
|
||||||
|
onClose={() => setShowUpdateModal(false)}
|
||||||
|
onOpen={() => setShowUpdateModal(true)}
|
||||||
|
open={showUpdateModal}
|
||||||
|
>
|
||||||
|
<Modal.Header>新版本:{updateData.tag_name}</Modal.Header>
|
||||||
|
<Modal.Content>
|
||||||
|
<Modal.Description>
|
||||||
|
<div dangerouslySetInnerHTML={{ __html: updateData.content }}></div>
|
||||||
|
</Modal.Description>
|
||||||
|
</Modal.Content>
|
||||||
|
<Modal.Actions>
|
||||||
|
<Button onClick={() => setShowUpdateModal(false)}>关闭</Button>
|
||||||
|
<Button
|
||||||
|
content='详情'
|
||||||
|
onClick={() => {
|
||||||
|
setShowUpdateModal(false);
|
||||||
|
openGitHubRelease();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</Modal.Actions>
|
||||||
|
</Modal>
|
||||||
|
</Grid>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default OtherSetting;
|
76
web/src/components/PasswordResetConfirm.js
Normal file
76
web/src/components/PasswordResetConfirm.js
Normal file
@ -0,0 +1,76 @@
|
|||||||
|
import React, { useEffect, useState } from 'react';
|
||||||
|
import { Button, Form, Grid, Header, Image, Segment } from 'semantic-ui-react';
|
||||||
|
import { API, copy, showError, showSuccess } from '../helpers';
|
||||||
|
import { useSearchParams } from 'react-router-dom';
|
||||||
|
|
||||||
|
const PasswordResetConfirm = () => {
|
||||||
|
const [inputs, setInputs] = useState({
|
||||||
|
email: '',
|
||||||
|
token: '',
|
||||||
|
});
|
||||||
|
const { email, token } = inputs;
|
||||||
|
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
|
const [searchParams, setSearchParams] = useSearchParams();
|
||||||
|
useEffect(() => {
|
||||||
|
let token = searchParams.get('token');
|
||||||
|
let email = searchParams.get('email');
|
||||||
|
setInputs({
|
||||||
|
token,
|
||||||
|
email,
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
async function handleSubmit(e) {
|
||||||
|
if (!email) return;
|
||||||
|
setLoading(true);
|
||||||
|
const res = await API.post(`/api/user/reset`, {
|
||||||
|
email,
|
||||||
|
token,
|
||||||
|
});
|
||||||
|
const { success, message } = res.data;
|
||||||
|
if (success) {
|
||||||
|
let password = res.data.data;
|
||||||
|
await copy(password);
|
||||||
|
showSuccess(`密码已重置并已复制到剪贴板:${password}`);
|
||||||
|
} else {
|
||||||
|
showError(message);
|
||||||
|
}
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Grid textAlign='center' style={{ marginTop: '48px' }}>
|
||||||
|
<Grid.Column style={{ maxWidth: 450 }}>
|
||||||
|
<Header as='h2' color='teal' textAlign='center'>
|
||||||
|
<Image src='/logo.png' /> 密码重置确认
|
||||||
|
</Header>
|
||||||
|
<Form size='large'>
|
||||||
|
<Segment>
|
||||||
|
<Form.Input
|
||||||
|
fluid
|
||||||
|
icon='mail'
|
||||||
|
iconPosition='left'
|
||||||
|
placeholder='邮箱地址'
|
||||||
|
name='email'
|
||||||
|
value={email}
|
||||||
|
readOnly
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
color='teal'
|
||||||
|
fluid
|
||||||
|
size='large'
|
||||||
|
onClick={handleSubmit}
|
||||||
|
loading={loading}
|
||||||
|
>
|
||||||
|
提交
|
||||||
|
</Button>
|
||||||
|
</Segment>
|
||||||
|
</Form>
|
||||||
|
</Grid.Column>
|
||||||
|
</Grid>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default PasswordResetConfirm;
|
96
web/src/components/PasswordResetForm.js
Normal file
96
web/src/components/PasswordResetForm.js
Normal file
@ -0,0 +1,96 @@
|
|||||||
|
import React, { useEffect, useState } from 'react';
|
||||||
|
import { Button, Form, Grid, Header, Image, Segment } from 'semantic-ui-react';
|
||||||
|
import { API, showError, showInfo, showSuccess } from '../helpers';
|
||||||
|
import Turnstile from 'react-turnstile';
|
||||||
|
|
||||||
|
const PasswordResetForm = () => {
|
||||||
|
const [inputs, setInputs] = useState({
|
||||||
|
email: '',
|
||||||
|
});
|
||||||
|
const { email } = inputs;
|
||||||
|
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [turnstileEnabled, setTurnstileEnabled] = useState(false);
|
||||||
|
const [turnstileSiteKey, setTurnstileSiteKey] = useState('');
|
||||||
|
const [turnstileToken, setTurnstileToken] = useState('');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let status = localStorage.getItem('status');
|
||||||
|
if (status) {
|
||||||
|
status = JSON.parse(status);
|
||||||
|
if (status.turnstile_check) {
|
||||||
|
setTurnstileEnabled(true);
|
||||||
|
setTurnstileSiteKey(status.turnstile_site_key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
function handleChange(e) {
|
||||||
|
const { name, value } = e.target;
|
||||||
|
setInputs((inputs) => ({ ...inputs, [name]: value }));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSubmit(e) {
|
||||||
|
if (!email) return;
|
||||||
|
if (turnstileEnabled && turnstileToken === '') {
|
||||||
|
showInfo('请稍后几秒重试,Turnstile 正在检查用户环境!');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setLoading(true);
|
||||||
|
const res = await API.get(
|
||||||
|
`/api/reset_password?email=${email}&turnstile=${turnstileToken}`
|
||||||
|
);
|
||||||
|
const { success, message } = res.data;
|
||||||
|
if (success) {
|
||||||
|
showSuccess('重置邮件发送成功,请检查邮箱!');
|
||||||
|
setInputs({ ...inputs, email: '' });
|
||||||
|
} else {
|
||||||
|
showError(message);
|
||||||
|
}
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Grid textAlign='center' style={{ marginTop: '48px' }}>
|
||||||
|
<Grid.Column style={{ maxWidth: 450 }}>
|
||||||
|
<Header as='h2' color='teal' textAlign='center'>
|
||||||
|
<Image src='/logo.png' /> 密码重置
|
||||||
|
</Header>
|
||||||
|
<Form size='large'>
|
||||||
|
<Segment>
|
||||||
|
<Form.Input
|
||||||
|
fluid
|
||||||
|
icon='mail'
|
||||||
|
iconPosition='left'
|
||||||
|
placeholder='邮箱地址'
|
||||||
|
name='email'
|
||||||
|
value={email}
|
||||||
|
onChange={handleChange}
|
||||||
|
/>
|
||||||
|
{turnstileEnabled ? (
|
||||||
|
<Turnstile
|
||||||
|
sitekey={turnstileSiteKey}
|
||||||
|
onVerify={(token) => {
|
||||||
|
setTurnstileToken(token);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<></>
|
||||||
|
)}
|
||||||
|
<Button
|
||||||
|
color='teal'
|
||||||
|
fluid
|
||||||
|
size='large'
|
||||||
|
onClick={handleSubmit}
|
||||||
|
loading={loading}
|
||||||
|
>
|
||||||
|
提交
|
||||||
|
</Button>
|
||||||
|
</Segment>
|
||||||
|
</Form>
|
||||||
|
</Grid.Column>
|
||||||
|
</Grid>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default PasswordResetForm;
|
213
web/src/components/PersonalSetting.js
Normal file
213
web/src/components/PersonalSetting.js
Normal file
@ -0,0 +1,213 @@
|
|||||||
|
import React, { useEffect, useState } from 'react';
|
||||||
|
import { Button, Divider, Form, Header, Image, Modal } from 'semantic-ui-react';
|
||||||
|
import { Link } from 'react-router-dom';
|
||||||
|
import { API, copy, showError, showInfo, showSuccess } from '../helpers';
|
||||||
|
import Turnstile from 'react-turnstile';
|
||||||
|
|
||||||
|
const PersonalSetting = () => {
|
||||||
|
const [inputs, setInputs] = useState({
|
||||||
|
wechat_verification_code: '',
|
||||||
|
email_verification_code: '',
|
||||||
|
email: '',
|
||||||
|
});
|
||||||
|
const [status, setStatus] = useState({});
|
||||||
|
const [showWeChatBindModal, setShowWeChatBindModal] = useState(false);
|
||||||
|
const [showEmailBindModal, setShowEmailBindModal] = useState(false);
|
||||||
|
const [turnstileEnabled, setTurnstileEnabled] = useState(false);
|
||||||
|
const [turnstileSiteKey, setTurnstileSiteKey] = useState('');
|
||||||
|
const [turnstileToken, setTurnstileToken] = useState('');
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let status = localStorage.getItem('status');
|
||||||
|
if (status) {
|
||||||
|
status = JSON.parse(status);
|
||||||
|
setStatus(status);
|
||||||
|
if (status.turnstile_check) {
|
||||||
|
setTurnstileEnabled(true);
|
||||||
|
setTurnstileSiteKey(status.turnstile_site_key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleInputChange = (e, { name, value }) => {
|
||||||
|
setInputs((inputs) => ({ ...inputs, [name]: value }));
|
||||||
|
};
|
||||||
|
|
||||||
|
const generateToken = async () => {
|
||||||
|
const res = await API.get('/api/user/token');
|
||||||
|
const { success, message, data } = res.data;
|
||||||
|
if (success) {
|
||||||
|
await copy(data);
|
||||||
|
showSuccess(`令牌已重置并已复制到剪贴板:${data}`);
|
||||||
|
} else {
|
||||||
|
showError(message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const bindWeChat = async () => {
|
||||||
|
if (inputs.wechat_verification_code === '') return;
|
||||||
|
const res = await API.get(
|
||||||
|
`/api/oauth/wechat/bind?code=${inputs.wechat_verification_code}`
|
||||||
|
);
|
||||||
|
const { success, message } = res.data;
|
||||||
|
if (success) {
|
||||||
|
showSuccess('微信账户绑定成功!');
|
||||||
|
setShowWeChatBindModal(false);
|
||||||
|
} else {
|
||||||
|
showError(message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const openGitHubOAuth = () => {
|
||||||
|
window.open(
|
||||||
|
`https://github.com/login/oauth/authorize?client_id=${status.github_client_id}&scope=user:email`
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const sendVerificationCode = async () => {
|
||||||
|
if (inputs.email === '') return;
|
||||||
|
if (turnstileEnabled && turnstileToken === '') {
|
||||||
|
showInfo('请稍后几秒重试,Turnstile 正在检查用户环境!');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setLoading(true);
|
||||||
|
const res = await API.get(
|
||||||
|
`/api/verification?email=${inputs.email}&turnstile=${turnstileToken}`
|
||||||
|
);
|
||||||
|
const { success, message } = res.data;
|
||||||
|
if (success) {
|
||||||
|
showSuccess('验证码发送成功,请检查邮箱!');
|
||||||
|
} else {
|
||||||
|
showError(message);
|
||||||
|
}
|
||||||
|
setLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const bindEmail = async () => {
|
||||||
|
if (inputs.email_verification_code === '') return;
|
||||||
|
setLoading(true);
|
||||||
|
const res = await API.get(
|
||||||
|
`/api/oauth/email/bind?email=${inputs.email}&code=${inputs.email_verification_code}`
|
||||||
|
);
|
||||||
|
const { success, message } = res.data;
|
||||||
|
if (success) {
|
||||||
|
showSuccess('邮箱账户绑定成功!');
|
||||||
|
setShowEmailBindModal(false);
|
||||||
|
} else {
|
||||||
|
showError(message);
|
||||||
|
}
|
||||||
|
setLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ lineHeight: '40px' }}>
|
||||||
|
<Header as='h3'>通用设置</Header>
|
||||||
|
<Button as={Link} to={`/user/edit/`}>
|
||||||
|
更新个人信息
|
||||||
|
</Button>
|
||||||
|
<Button onClick={generateToken}>生成访问令牌</Button>
|
||||||
|
<Divider />
|
||||||
|
<Header as='h3'>账号绑定</Header>
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
setShowWeChatBindModal(true);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
绑定微信账号
|
||||||
|
</Button>
|
||||||
|
<Modal
|
||||||
|
onClose={() => setShowWeChatBindModal(false)}
|
||||||
|
onOpen={() => setShowWeChatBindModal(true)}
|
||||||
|
open={showWeChatBindModal}
|
||||||
|
size={'mini'}
|
||||||
|
>
|
||||||
|
<Modal.Content>
|
||||||
|
<Modal.Description>
|
||||||
|
<Image src={status.wechat_qrcode} fluid />
|
||||||
|
<div style={{ textAlign: 'center' }}>
|
||||||
|
<p>
|
||||||
|
微信扫码关注公众号,输入「验证码」获取验证码(三分钟内有效)
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Form size='large'>
|
||||||
|
<Form.Input
|
||||||
|
fluid
|
||||||
|
placeholder='验证码'
|
||||||
|
name='wechat_verification_code'
|
||||||
|
value={inputs.wechat_verification_code}
|
||||||
|
onChange={handleInputChange}
|
||||||
|
/>
|
||||||
|
<Button color='teal' fluid size='large' onClick={bindWeChat}>
|
||||||
|
绑定
|
||||||
|
</Button>
|
||||||
|
</Form>
|
||||||
|
</Modal.Description>
|
||||||
|
</Modal.Content>
|
||||||
|
</Modal>
|
||||||
|
<Button onClick={openGitHubOAuth}>绑定 GitHub 账号</Button>
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
setShowEmailBindModal(true);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
绑定邮箱地址
|
||||||
|
</Button>
|
||||||
|
<Modal
|
||||||
|
onClose={() => setShowEmailBindModal(false)}
|
||||||
|
onOpen={() => setShowEmailBindModal(true)}
|
||||||
|
open={showEmailBindModal}
|
||||||
|
size={'tiny'}
|
||||||
|
style={{ maxWidth: '450px' }}
|
||||||
|
>
|
||||||
|
<Modal.Header>绑定邮箱地址</Modal.Header>
|
||||||
|
<Modal.Content>
|
||||||
|
<Modal.Description>
|
||||||
|
<Form size='large'>
|
||||||
|
<Form.Input
|
||||||
|
fluid
|
||||||
|
placeholder='输入邮箱地址'
|
||||||
|
onChange={handleInputChange}
|
||||||
|
name='email'
|
||||||
|
type='email'
|
||||||
|
action={
|
||||||
|
<Button onClick={sendVerificationCode} disabled={loading}>
|
||||||
|
获取验证码
|
||||||
|
</Button>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Form.Input
|
||||||
|
fluid
|
||||||
|
placeholder='验证码'
|
||||||
|
name='email_verification_code'
|
||||||
|
value={inputs.email_verification_code}
|
||||||
|
onChange={handleInputChange}
|
||||||
|
/>
|
||||||
|
{turnstileEnabled ? (
|
||||||
|
<Turnstile
|
||||||
|
sitekey={turnstileSiteKey}
|
||||||
|
onVerify={(token) => {
|
||||||
|
setTurnstileToken(token);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<></>
|
||||||
|
)}
|
||||||
|
<Button
|
||||||
|
color='teal'
|
||||||
|
fluid
|
||||||
|
size='large'
|
||||||
|
onClick={bindEmail}
|
||||||
|
loading={loading}
|
||||||
|
>
|
||||||
|
绑定
|
||||||
|
</Button>
|
||||||
|
</Form>
|
||||||
|
</Modal.Description>
|
||||||
|
</Modal.Content>
|
||||||
|
</Modal>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default PersonalSetting;
|
13
web/src/components/PrivateRoute.js
Normal file
13
web/src/components/PrivateRoute.js
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
import { Navigate } from 'react-router-dom';
|
||||||
|
|
||||||
|
import { history } from '../helpers';
|
||||||
|
|
||||||
|
|
||||||
|
function PrivateRoute({ children }) {
|
||||||
|
if (!localStorage.getItem('user')) {
|
||||||
|
return <Navigate to='/login' state={{ from: history.location }} />;
|
||||||
|
}
|
||||||
|
return children;
|
||||||
|
}
|
||||||
|
|
||||||
|
export { PrivateRoute };
|
193
web/src/components/RegisterForm.js
Normal file
193
web/src/components/RegisterForm.js
Normal file
@ -0,0 +1,193 @@
|
|||||||
|
import React, { useEffect, useState } from 'react';
|
||||||
|
import {
|
||||||
|
Button,
|
||||||
|
Form,
|
||||||
|
Grid,
|
||||||
|
Header,
|
||||||
|
Image,
|
||||||
|
Message,
|
||||||
|
Segment,
|
||||||
|
} from 'semantic-ui-react';
|
||||||
|
import { Link, useNavigate } from 'react-router-dom';
|
||||||
|
import { API, showError, showInfo, showSuccess } from '../helpers';
|
||||||
|
import Turnstile from 'react-turnstile';
|
||||||
|
|
||||||
|
const RegisterForm = () => {
|
||||||
|
const [inputs, setInputs] = useState({
|
||||||
|
username: '',
|
||||||
|
password: '',
|
||||||
|
password2: '',
|
||||||
|
email: '',
|
||||||
|
verification_code: '',
|
||||||
|
});
|
||||||
|
const { username, password, password2 } = inputs;
|
||||||
|
const [showEmailVerification, setShowEmailVerification] = useState(false);
|
||||||
|
const [turnstileEnabled, setTurnstileEnabled] = useState(false);
|
||||||
|
const [turnstileSiteKey, setTurnstileSiteKey] = useState('');
|
||||||
|
const [turnstileToken, setTurnstileToken] = useState('');
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let status = localStorage.getItem('status');
|
||||||
|
if (status) {
|
||||||
|
status = JSON.parse(status);
|
||||||
|
setShowEmailVerification(status.email_verification);
|
||||||
|
if (status.turnstile_check) {
|
||||||
|
setTurnstileEnabled(true);
|
||||||
|
setTurnstileSiteKey(status.turnstile_site_key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let navigate = useNavigate();
|
||||||
|
|
||||||
|
function handleChange(e) {
|
||||||
|
const { name, value } = e.target;
|
||||||
|
console.log(name, value);
|
||||||
|
setInputs((inputs) => ({ ...inputs, [name]: value }));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSubmit(e) {
|
||||||
|
if (password.length < 8) {
|
||||||
|
showInfo('密码长度不得小于 8 位!');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (password !== password2) {
|
||||||
|
showInfo('两次输入的密码不一致');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (username && password) {
|
||||||
|
if (turnstileEnabled && turnstileToken === '') {
|
||||||
|
showInfo('请稍后几秒重试,Turnstile 正在检查用户环境!');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setLoading(true);
|
||||||
|
const res = await API.post(
|
||||||
|
`/api/user/register?turnstile=${turnstileToken}`,
|
||||||
|
inputs
|
||||||
|
);
|
||||||
|
const { success, message } = res.data;
|
||||||
|
if (success) {
|
||||||
|
navigate('/login');
|
||||||
|
showSuccess('注册成功!');
|
||||||
|
} else {
|
||||||
|
showError(message);
|
||||||
|
}
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const sendVerificationCode = async () => {
|
||||||
|
if (inputs.email === '') return;
|
||||||
|
if (turnstileEnabled && turnstileToken === '') {
|
||||||
|
showInfo('请稍后几秒重试,Turnstile 正在检查用户环境!');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setLoading(true);
|
||||||
|
const res = await API.get(
|
||||||
|
`/api/verification?email=${inputs.email}&turnstile=${turnstileToken}`
|
||||||
|
);
|
||||||
|
const { success, message } = res.data;
|
||||||
|
if (success) {
|
||||||
|
showSuccess('验证码发送成功,请检查你的邮箱!');
|
||||||
|
} else {
|
||||||
|
showError(message);
|
||||||
|
}
|
||||||
|
setLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Grid textAlign='center' style={{ marginTop: '48px' }}>
|
||||||
|
<Grid.Column style={{ maxWidth: 450 }}>
|
||||||
|
<Header as='h2' color='teal' textAlign='center'>
|
||||||
|
<Image src='/logo.png' /> 新用户注册
|
||||||
|
</Header>
|
||||||
|
<Form size='large'>
|
||||||
|
<Segment>
|
||||||
|
<Form.Input
|
||||||
|
fluid
|
||||||
|
icon='user'
|
||||||
|
iconPosition='left'
|
||||||
|
placeholder='输入用户名,最长 12 位'
|
||||||
|
onChange={handleChange}
|
||||||
|
name='username'
|
||||||
|
/>
|
||||||
|
<Form.Input
|
||||||
|
fluid
|
||||||
|
icon='lock'
|
||||||
|
iconPosition='left'
|
||||||
|
placeholder='输入密码,最短 8 位,最长 20 位'
|
||||||
|
onChange={handleChange}
|
||||||
|
name='password'
|
||||||
|
type='password'
|
||||||
|
/>
|
||||||
|
<Form.Input
|
||||||
|
fluid
|
||||||
|
icon='lock'
|
||||||
|
iconPosition='left'
|
||||||
|
placeholder='输入密码,最短 8 位,最长 20 位'
|
||||||
|
onChange={handleChange}
|
||||||
|
name='password2'
|
||||||
|
type='password'
|
||||||
|
/>
|
||||||
|
{showEmailVerification ? (
|
||||||
|
<>
|
||||||
|
<Form.Input
|
||||||
|
fluid
|
||||||
|
icon='mail'
|
||||||
|
iconPosition='left'
|
||||||
|
placeholder='输入邮箱地址'
|
||||||
|
onChange={handleChange}
|
||||||
|
name='email'
|
||||||
|
type='email'
|
||||||
|
action={
|
||||||
|
<Button onClick={sendVerificationCode} disabled={loading}>
|
||||||
|
获取验证码
|
||||||
|
</Button>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Form.Input
|
||||||
|
fluid
|
||||||
|
icon='lock'
|
||||||
|
iconPosition='left'
|
||||||
|
placeholder='输入验证码'
|
||||||
|
onChange={handleChange}
|
||||||
|
name='verification_code'
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<></>
|
||||||
|
)}
|
||||||
|
{turnstileEnabled ? (
|
||||||
|
<Turnstile
|
||||||
|
sitekey={turnstileSiteKey}
|
||||||
|
onVerify={(token) => {
|
||||||
|
setTurnstileToken(token);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<></>
|
||||||
|
)}
|
||||||
|
<Button
|
||||||
|
color='teal'
|
||||||
|
fluid
|
||||||
|
size='large'
|
||||||
|
onClick={handleSubmit}
|
||||||
|
loading={loading}
|
||||||
|
>
|
||||||
|
注册
|
||||||
|
</Button>
|
||||||
|
</Segment>
|
||||||
|
</Form>
|
||||||
|
<Message>
|
||||||
|
已有账户?
|
||||||
|
<Link to='/login' className='btn btn-link'>
|
||||||
|
点击登录
|
||||||
|
</Link>
|
||||||
|
</Message>
|
||||||
|
</Grid.Column>
|
||||||
|
</Grid>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default RegisterForm;
|
384
web/src/components/SystemSetting.js
Normal file
384
web/src/components/SystemSetting.js
Normal file
@ -0,0 +1,384 @@
|
|||||||
|
import React, { useEffect, useState } from 'react';
|
||||||
|
import { Divider, Form, Grid, Header, Message } from 'semantic-ui-react';
|
||||||
|
import { API, removeTrailingSlash, showError } from '../helpers';
|
||||||
|
|
||||||
|
const SystemSetting = () => {
|
||||||
|
let [inputs, setInputs] = useState({
|
||||||
|
PasswordLoginEnabled: '',
|
||||||
|
PasswordRegisterEnabled: '',
|
||||||
|
EmailVerificationEnabled: '',
|
||||||
|
GitHubOAuthEnabled: '',
|
||||||
|
GitHubClientId: '',
|
||||||
|
GitHubClientSecret: '',
|
||||||
|
Notice: '',
|
||||||
|
SMTPServer: '',
|
||||||
|
SMTPAccount: '',
|
||||||
|
SMTPToken: '',
|
||||||
|
ServerAddress: '',
|
||||||
|
Footer: '',
|
||||||
|
WeChatAuthEnabled: '',
|
||||||
|
WeChatServerAddress: '',
|
||||||
|
WeChatServerToken: '',
|
||||||
|
WeChatAccountQRCodeImageURL: '',
|
||||||
|
TurnstileCheckEnabled: '',
|
||||||
|
TurnstileSiteKey: '',
|
||||||
|
TurnstileSecretKey: '',
|
||||||
|
RegisterEnabled: '',
|
||||||
|
});
|
||||||
|
let originInputs = {};
|
||||||
|
let [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
|
const getOptions = async () => {
|
||||||
|
const res = await API.get('/api/option');
|
||||||
|
const { success, message, data } = res.data;
|
||||||
|
if (success) {
|
||||||
|
let newInputs = {};
|
||||||
|
data.forEach((item) => {
|
||||||
|
newInputs[item.key] = item.value;
|
||||||
|
});
|
||||||
|
setInputs(newInputs);
|
||||||
|
originInputs = newInputs;
|
||||||
|
} else {
|
||||||
|
showError(message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
getOptions().then();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const updateOption = async (key, value) => {
|
||||||
|
setLoading(true);
|
||||||
|
switch (key) {
|
||||||
|
case 'PasswordLoginEnabled':
|
||||||
|
case 'PasswordRegisterEnabled':
|
||||||
|
case 'EmailVerificationEnabled':
|
||||||
|
case 'GitHubOAuthEnabled':
|
||||||
|
case 'WeChatAuthEnabled':
|
||||||
|
case 'TurnstileCheckEnabled':
|
||||||
|
case 'RegisterEnabled':
|
||||||
|
value = inputs[key] === 'true' ? 'false' : 'true';
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
const res = await API.put('/api/option', {
|
||||||
|
key,
|
||||||
|
value,
|
||||||
|
});
|
||||||
|
const { success, message } = res.data;
|
||||||
|
if (success) {
|
||||||
|
setInputs((inputs) => ({ ...inputs, [key]: value }));
|
||||||
|
} else {
|
||||||
|
showError(message);
|
||||||
|
}
|
||||||
|
setLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleInputChange = async (e, { name, value }) => {
|
||||||
|
if (
|
||||||
|
name === 'Notice' ||
|
||||||
|
name.startsWith('SMTP') ||
|
||||||
|
name === 'ServerAddress' ||
|
||||||
|
name === 'GitHubClientId' ||
|
||||||
|
name === 'GitHubClientSecret' ||
|
||||||
|
name === 'WeChatServerAddress' ||
|
||||||
|
name === 'WeChatServerToken' ||
|
||||||
|
name === 'WeChatAccountQRCodeImageURL' ||
|
||||||
|
name === 'TurnstileSiteKey' ||
|
||||||
|
name === 'TurnstileSecretKey'
|
||||||
|
) {
|
||||||
|
setInputs((inputs) => ({ ...inputs, [name]: value }));
|
||||||
|
} else {
|
||||||
|
await updateOption(name, value);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const submitServerAddress = async () => {
|
||||||
|
let ServerAddress = removeTrailingSlash(inputs.ServerAddress);
|
||||||
|
await updateOption('ServerAddress', ServerAddress);
|
||||||
|
};
|
||||||
|
|
||||||
|
const submitSMTP = async () => {
|
||||||
|
if (originInputs['SMTPServer'] !== inputs.SMTPServer) {
|
||||||
|
await updateOption('SMTPServer', inputs.SMTPServer);
|
||||||
|
}
|
||||||
|
if (originInputs['SMTPAccount'] !== inputs.SMTPAccount) {
|
||||||
|
await updateOption('SMTPAccount', inputs.SMTPAccount);
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
originInputs['SMTPToken'] !== inputs.SMTPToken &&
|
||||||
|
inputs.SMTPToken !== ''
|
||||||
|
) {
|
||||||
|
await updateOption('SMTPToken', inputs.SMTPToken);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const submitWeChat = async () => {
|
||||||
|
if (originInputs['WeChatServerAddress'] !== inputs.WeChatServerAddress) {
|
||||||
|
await updateOption(
|
||||||
|
'WeChatServerAddress',
|
||||||
|
removeTrailingSlash(inputs.WeChatServerAddress)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
originInputs['WeChatAccountQRCodeImageURL'] !==
|
||||||
|
inputs.WeChatAccountQRCodeImageURL
|
||||||
|
) {
|
||||||
|
await updateOption(
|
||||||
|
'WeChatAccountQRCodeImageURL',
|
||||||
|
inputs.WeChatAccountQRCodeImageURL
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
originInputs['WeChatServerToken'] !== inputs.WeChatServerToken &&
|
||||||
|
inputs.WeChatServerToken !== ''
|
||||||
|
) {
|
||||||
|
await updateOption('WeChatServerToken', inputs.WeChatServerToken);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const submitGitHubOAuth = async () => {
|
||||||
|
if (originInputs['GitHubClientId'] !== inputs.GitHubClientId) {
|
||||||
|
await updateOption('GitHubClientId', inputs.GitHubClientId);
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
originInputs['GitHubClientSecret'] !== inputs.GitHubClientSecret &&
|
||||||
|
inputs.GitHubClientSecret !== ''
|
||||||
|
) {
|
||||||
|
await updateOption('GitHubClientSecret', inputs.GitHubClientSecret);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const submitTurnstile = async () => {
|
||||||
|
if (originInputs['TurnstileSiteKey'] !== inputs.TurnstileSiteKey) {
|
||||||
|
await updateOption('TurnstileSiteKey', inputs.TurnstileSiteKey);
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
originInputs['TurnstileSecretKey'] !== inputs.TurnstileSecretKey &&
|
||||||
|
inputs.TurnstileSecretKey !== ''
|
||||||
|
) {
|
||||||
|
await updateOption('TurnstileSecretKey', inputs.TurnstileSecretKey);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Grid columns={1}>
|
||||||
|
<Grid.Column>
|
||||||
|
<Form loading={loading}>
|
||||||
|
<Header as='h3'>通用设置</Header>
|
||||||
|
<Form.Group widths='equal'>
|
||||||
|
<Form.Input
|
||||||
|
label='服务器地址'
|
||||||
|
placeholder='例如:https://yourdomain.com'
|
||||||
|
value={inputs.ServerAddress}
|
||||||
|
name='ServerAddress'
|
||||||
|
onChange={handleInputChange}
|
||||||
|
/>
|
||||||
|
</Form.Group>
|
||||||
|
<Form.Button onClick={submitServerAddress}>
|
||||||
|
更新服务器地址
|
||||||
|
</Form.Button>
|
||||||
|
<Divider />
|
||||||
|
<Header as='h3'>配置登录注册</Header>
|
||||||
|
<Form.Group inline>
|
||||||
|
<Form.Checkbox
|
||||||
|
checked={inputs.PasswordLoginEnabled === 'true'}
|
||||||
|
label='允许通过密码进行登录'
|
||||||
|
name='PasswordLoginEnabled'
|
||||||
|
onChange={handleInputChange}
|
||||||
|
/>
|
||||||
|
<Form.Checkbox
|
||||||
|
checked={inputs.PasswordRegisterEnabled === 'true'}
|
||||||
|
label='允许通过密码进行注册'
|
||||||
|
name='PasswordRegisterEnabled'
|
||||||
|
onChange={handleInputChange}
|
||||||
|
/>
|
||||||
|
<Form.Checkbox
|
||||||
|
checked={inputs.EmailVerificationEnabled === 'true'}
|
||||||
|
label='通过密码注册时需要进行邮箱验证'
|
||||||
|
name='EmailVerificationEnabled'
|
||||||
|
onChange={handleInputChange}
|
||||||
|
/>
|
||||||
|
<Form.Checkbox
|
||||||
|
checked={inputs.GitHubOAuthEnabled === 'true'}
|
||||||
|
label='允许通过 GitHub 账户登录 & 注册'
|
||||||
|
name='GitHubOAuthEnabled'
|
||||||
|
onChange={handleInputChange}
|
||||||
|
/>
|
||||||
|
<Form.Checkbox
|
||||||
|
checked={inputs.WeChatAuthEnabled === 'true'}
|
||||||
|
label='允许通过微信登录 & 注册'
|
||||||
|
name='WeChatAuthEnabled'
|
||||||
|
onChange={handleInputChange}
|
||||||
|
/>
|
||||||
|
</Form.Group>
|
||||||
|
<Form.Group inline>
|
||||||
|
<Form.Checkbox
|
||||||
|
checked={inputs.RegisterEnabled === 'true'}
|
||||||
|
label='允许新用户注册(此项为否时,新用户将无法以任何方式进行注册)'
|
||||||
|
name='RegisterEnabled'
|
||||||
|
onChange={handleInputChange}
|
||||||
|
/>
|
||||||
|
<Form.Checkbox
|
||||||
|
checked={inputs.TurnstileCheckEnabled === 'true'}
|
||||||
|
label='启用 Turnstile 用户校验'
|
||||||
|
name='TurnstileCheckEnabled'
|
||||||
|
onChange={handleInputChange}
|
||||||
|
/>
|
||||||
|
</Form.Group>
|
||||||
|
<Divider />
|
||||||
|
<Header as='h3'>
|
||||||
|
配置 SMTP
|
||||||
|
<Header.Subheader>用以支持系统的邮件发送</Header.Subheader>
|
||||||
|
</Header>
|
||||||
|
<Form.Group widths={3}>
|
||||||
|
<Form.Input
|
||||||
|
label='SMTP 服务器地址'
|
||||||
|
name='SMTPServer'
|
||||||
|
onChange={handleInputChange}
|
||||||
|
autoComplete='off'
|
||||||
|
value={inputs.SMTPServer}
|
||||||
|
placeholder='例如:smtp.qq.com'
|
||||||
|
/>
|
||||||
|
<Form.Input
|
||||||
|
label='SMTP 账户'
|
||||||
|
name='SMTPAccount'
|
||||||
|
onChange={handleInputChange}
|
||||||
|
autoComplete='off'
|
||||||
|
value={inputs.SMTPAccount}
|
||||||
|
placeholder='通常是邮箱地址'
|
||||||
|
/>
|
||||||
|
<Form.Input
|
||||||
|
label='SMTP 访问凭证'
|
||||||
|
name='SMTPToken'
|
||||||
|
onChange={handleInputChange}
|
||||||
|
type='password'
|
||||||
|
autoComplete='off'
|
||||||
|
value={inputs.SMTPToken}
|
||||||
|
placeholder='敏感信息不会发送到前端显示'
|
||||||
|
/>
|
||||||
|
</Form.Group>
|
||||||
|
<Form.Button onClick={submitSMTP}>保存 SMTP 设置</Form.Button>
|
||||||
|
<Divider />
|
||||||
|
<Header as='h3'>
|
||||||
|
配置 GitHub OAuth App
|
||||||
|
<Header.Subheader>
|
||||||
|
用以支持通过 GitHub 进行登录注册,
|
||||||
|
<a href='https://github.com/settings/developers' target='_blank'>
|
||||||
|
点击此处
|
||||||
|
</a>
|
||||||
|
管理你的 GitHub OAuth App
|
||||||
|
</Header.Subheader>
|
||||||
|
</Header>
|
||||||
|
<Message>
|
||||||
|
Homepage URL 填 <code>{inputs.ServerAddress}</code>
|
||||||
|
,Authorization callback URL 填{' '}
|
||||||
|
<code>{`${inputs.ServerAddress}/oauth/github`}</code>
|
||||||
|
</Message>
|
||||||
|
<Form.Group widths={3}>
|
||||||
|
<Form.Input
|
||||||
|
label='GitHub Client ID'
|
||||||
|
name='GitHubClientId'
|
||||||
|
onChange={handleInputChange}
|
||||||
|
autoComplete='off'
|
||||||
|
value={inputs.GitHubClientId}
|
||||||
|
placeholder='输入你注册的 GitHub OAuth APP 的 ID'
|
||||||
|
/>
|
||||||
|
<Form.Input
|
||||||
|
label='GitHub Client Secret'
|
||||||
|
name='GitHubClientSecret'
|
||||||
|
onChange={handleInputChange}
|
||||||
|
type='password'
|
||||||
|
autoComplete='off'
|
||||||
|
value={inputs.GitHubClientSecret}
|
||||||
|
placeholder='敏感信息不会发送到前端显示'
|
||||||
|
/>
|
||||||
|
</Form.Group>
|
||||||
|
<Form.Button onClick={submitGitHubOAuth}>
|
||||||
|
保存 GitHub OAuth 设置
|
||||||
|
</Form.Button>
|
||||||
|
<Divider />
|
||||||
|
<Header as='h3'>
|
||||||
|
配置 WeChat Server
|
||||||
|
<Header.Subheader>
|
||||||
|
用以支持通过微信进行登录注册,
|
||||||
|
<a
|
||||||
|
href='https://github.com/songquanpeng/wechat-server'
|
||||||
|
target='_blank'
|
||||||
|
>
|
||||||
|
点击此处
|
||||||
|
</a>
|
||||||
|
了解 WeChat Server
|
||||||
|
</Header.Subheader>
|
||||||
|
</Header>
|
||||||
|
<Form.Group widths={3}>
|
||||||
|
<Form.Input
|
||||||
|
label='WeChat Server 服务器地址'
|
||||||
|
name='WeChatServerAddress'
|
||||||
|
placeholder='例如:https://yourdomain.com'
|
||||||
|
onChange={handleInputChange}
|
||||||
|
autoComplete='off'
|
||||||
|
value={inputs.WeChatServerAddress}
|
||||||
|
/>
|
||||||
|
<Form.Input
|
||||||
|
label='WeChat Server 访问凭证'
|
||||||
|
name='WeChatServerToken'
|
||||||
|
type='password'
|
||||||
|
onChange={handleInputChange}
|
||||||
|
autoComplete='off'
|
||||||
|
value={inputs.WeChatServerToken}
|
||||||
|
placeholder='敏感信息不会发送到前端显示'
|
||||||
|
/>
|
||||||
|
<Form.Input
|
||||||
|
label='微信公众号二维码图片链接'
|
||||||
|
name='WeChatAccountQRCodeImageURL'
|
||||||
|
onChange={handleInputChange}
|
||||||
|
autoComplete='off'
|
||||||
|
value={inputs.WeChatAccountQRCodeImageURL}
|
||||||
|
placeholder='输入一个图片链接'
|
||||||
|
/>
|
||||||
|
</Form.Group>
|
||||||
|
<Form.Button onClick={submitWeChat}>
|
||||||
|
保存 WeChat Server 设置
|
||||||
|
</Form.Button>
|
||||||
|
<Divider />
|
||||||
|
<Header as='h3'>
|
||||||
|
配置 Turnstile
|
||||||
|
<Header.Subheader>
|
||||||
|
用以支持用户校验,
|
||||||
|
<a href='https://dash.cloudflare.com/' target='_blank'>
|
||||||
|
点击此处
|
||||||
|
</a>
|
||||||
|
管理你的 Turnstile Sites,推荐选择 Invisible Widget Type
|
||||||
|
</Header.Subheader>
|
||||||
|
</Header>
|
||||||
|
<Form.Group widths={3}>
|
||||||
|
<Form.Input
|
||||||
|
label='Turnstile Site Key'
|
||||||
|
name='TurnstileSiteKey'
|
||||||
|
onChange={handleInputChange}
|
||||||
|
autoComplete='off'
|
||||||
|
value={inputs.TurnstileSiteKey}
|
||||||
|
placeholder='输入你注册的 Turnstile Site Key'
|
||||||
|
/>
|
||||||
|
<Form.Input
|
||||||
|
label='Turnstile Secret Key'
|
||||||
|
name='TurnstileSecretKey'
|
||||||
|
onChange={handleInputChange}
|
||||||
|
type='password'
|
||||||
|
autoComplete='off'
|
||||||
|
value={inputs.TurnstileSecretKey}
|
||||||
|
placeholder='敏感信息不会发送到前端显示'
|
||||||
|
/>
|
||||||
|
</Form.Group>
|
||||||
|
<Form.Button onClick={submitTurnstile}>
|
||||||
|
保存 Turnstile 设置
|
||||||
|
</Form.Button>
|
||||||
|
</Form>
|
||||||
|
</Grid.Column>
|
||||||
|
</Grid>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default SystemSetting;
|
300
web/src/components/UsersTable.js
Normal file
300
web/src/components/UsersTable.js
Normal file
@ -0,0 +1,300 @@
|
|||||||
|
import React, { useEffect, useState } from 'react';
|
||||||
|
import { Button, Form, Label, Pagination, Table } from 'semantic-ui-react';
|
||||||
|
import { Link } from 'react-router-dom';
|
||||||
|
import { API, showError, showSuccess } from '../helpers';
|
||||||
|
|
||||||
|
import { ITEMS_PER_PAGE } from '../constants';
|
||||||
|
|
||||||
|
function renderRole(role) {
|
||||||
|
switch (role) {
|
||||||
|
case 1:
|
||||||
|
return <Label>普通用户</Label>;
|
||||||
|
case 10:
|
||||||
|
return <Label color='yellow'>管理员</Label>;
|
||||||
|
case 100:
|
||||||
|
return <Label color='orange'>超级管理员</Label>;
|
||||||
|
default:
|
||||||
|
return <Label color='red'>未知身份</Label>;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const UsersTable = () => {
|
||||||
|
const [users, setUsers] = useState([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [activePage, setActivePage] = useState(1);
|
||||||
|
const [searchKeyword, setSearchKeyword] = useState('');
|
||||||
|
const [searching, setSearching] = useState(false);
|
||||||
|
|
||||||
|
const loadUsers = async (startIdx) => {
|
||||||
|
const res = await API.get(`/api/user/?p=${startIdx}`);
|
||||||
|
const { success, message, data } = res.data;
|
||||||
|
if (success) {
|
||||||
|
if (startIdx === 0) {
|
||||||
|
setUsers(data);
|
||||||
|
} else {
|
||||||
|
let newUsers = users;
|
||||||
|
newUsers.push(...data);
|
||||||
|
setUsers(newUsers);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
showError(message);
|
||||||
|
}
|
||||||
|
setLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const onPaginationChange = (e, { activePage }) => {
|
||||||
|
(async () => {
|
||||||
|
if (activePage === Math.ceil(users.length / ITEMS_PER_PAGE) + 1) {
|
||||||
|
// In this case we have to load more data and then append them.
|
||||||
|
await loadUsers(activePage - 1);
|
||||||
|
}
|
||||||
|
setActivePage(activePage);
|
||||||
|
})();
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
loadUsers(0)
|
||||||
|
.then()
|
||||||
|
.catch((reason) => {
|
||||||
|
showError(reason);
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const manageUser = (username, action, idx) => {
|
||||||
|
(async () => {
|
||||||
|
const res = await API.post('/api/user/manage', {
|
||||||
|
username,
|
||||||
|
action,
|
||||||
|
});
|
||||||
|
const { success, message } = res.data;
|
||||||
|
if (success) {
|
||||||
|
showSuccess('操作成功完成!');
|
||||||
|
let user = res.data.data;
|
||||||
|
let newUsers = [...users];
|
||||||
|
let realIdx = (activePage - 1) * ITEMS_PER_PAGE + idx;
|
||||||
|
if (action === 'delete') {
|
||||||
|
newUsers[realIdx].deleted = true;
|
||||||
|
} else {
|
||||||
|
newUsers[realIdx].status = user.status;
|
||||||
|
newUsers[realIdx].role = user.role;
|
||||||
|
}
|
||||||
|
setUsers(newUsers);
|
||||||
|
} else {
|
||||||
|
showError(message);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderStatus = (status) => {
|
||||||
|
switch (status) {
|
||||||
|
case 1:
|
||||||
|
return <Label basic>已激活</Label>;
|
||||||
|
case 2:
|
||||||
|
return (
|
||||||
|
<Label basic color='red'>
|
||||||
|
已封禁
|
||||||
|
</Label>
|
||||||
|
);
|
||||||
|
default:
|
||||||
|
return (
|
||||||
|
<Label basic color='grey'>
|
||||||
|
未知状态
|
||||||
|
</Label>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const searchUsers = async () => {
|
||||||
|
if (searchKeyword === '') {
|
||||||
|
// if keyword is blank, load files instead.
|
||||||
|
await loadUsers(0);
|
||||||
|
setActivePage(1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setSearching(true);
|
||||||
|
const res = await API.get(`/api/user/search?keyword=${searchKeyword}`);
|
||||||
|
const { success, message, data } = res.data;
|
||||||
|
if (success) {
|
||||||
|
setUsers(data);
|
||||||
|
setActivePage(1);
|
||||||
|
} else {
|
||||||
|
showError(message);
|
||||||
|
}
|
||||||
|
setSearching(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleKeywordChange = async (e, { value }) => {
|
||||||
|
setSearchKeyword(value.trim());
|
||||||
|
};
|
||||||
|
|
||||||
|
const sortUser = (key) => {
|
||||||
|
if (users.length === 0) return;
|
||||||
|
setLoading(true);
|
||||||
|
let sortedUsers = [...users];
|
||||||
|
sortedUsers.sort((a, b) => {
|
||||||
|
return ('' + a[key]).localeCompare(b[key]);
|
||||||
|
});
|
||||||
|
if (sortedUsers[0].id === users[0].id) {
|
||||||
|
sortedUsers.reverse();
|
||||||
|
}
|
||||||
|
setUsers(sortedUsers);
|
||||||
|
setLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Form onSubmit={searchUsers}>
|
||||||
|
<Form.Input
|
||||||
|
icon='search'
|
||||||
|
fluid
|
||||||
|
iconPosition='left'
|
||||||
|
placeholder='搜索用户的 ID,用户名,显示名称,以及邮箱地址 ...'
|
||||||
|
value={searchKeyword}
|
||||||
|
loading={searching}
|
||||||
|
onChange={handleKeywordChange}
|
||||||
|
/>
|
||||||
|
</Form>
|
||||||
|
|
||||||
|
<Table basic>
|
||||||
|
<Table.Header>
|
||||||
|
<Table.Row>
|
||||||
|
<Table.HeaderCell
|
||||||
|
style={{ cursor: 'pointer' }}
|
||||||
|
onClick={() => {
|
||||||
|
sortUser('username');
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
用户名
|
||||||
|
</Table.HeaderCell>
|
||||||
|
<Table.HeaderCell
|
||||||
|
style={{ cursor: 'pointer' }}
|
||||||
|
onClick={() => {
|
||||||
|
sortUser('display_name');
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
显示名称
|
||||||
|
</Table.HeaderCell>
|
||||||
|
<Table.HeaderCell
|
||||||
|
style={{ cursor: 'pointer' }}
|
||||||
|
onClick={() => {
|
||||||
|
sortUser('email');
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
邮箱地址
|
||||||
|
</Table.HeaderCell>
|
||||||
|
<Table.HeaderCell
|
||||||
|
style={{ cursor: 'pointer' }}
|
||||||
|
onClick={() => {
|
||||||
|
sortUser('role');
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
用户角色
|
||||||
|
</Table.HeaderCell>
|
||||||
|
<Table.HeaderCell
|
||||||
|
style={{ cursor: 'pointer' }}
|
||||||
|
onClick={() => {
|
||||||
|
sortUser('status');
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
状态
|
||||||
|
</Table.HeaderCell>
|
||||||
|
<Table.HeaderCell>操作</Table.HeaderCell>
|
||||||
|
</Table.Row>
|
||||||
|
</Table.Header>
|
||||||
|
|
||||||
|
<Table.Body>
|
||||||
|
{users
|
||||||
|
.slice(
|
||||||
|
(activePage - 1) * ITEMS_PER_PAGE,
|
||||||
|
activePage * ITEMS_PER_PAGE
|
||||||
|
)
|
||||||
|
.map((user, idx) => {
|
||||||
|
if (user.deleted) return <></>;
|
||||||
|
return (
|
||||||
|
<Table.Row key={user.id}>
|
||||||
|
<Table.Cell>{user.username}</Table.Cell>
|
||||||
|
<Table.Cell>{user.display_name}</Table.Cell>
|
||||||
|
<Table.Cell>{user.email ? user.email : '无'}</Table.Cell>
|
||||||
|
<Table.Cell>{renderRole(user.role)}</Table.Cell>
|
||||||
|
<Table.Cell>{renderStatus(user.status)}</Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
<div>
|
||||||
|
<Button
|
||||||
|
size={'small'}
|
||||||
|
positive
|
||||||
|
onClick={() => {
|
||||||
|
manageUser(user.username, 'promote', idx);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
提升
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size={'small'}
|
||||||
|
color={'yellow'}
|
||||||
|
onClick={() => {
|
||||||
|
manageUser(user.username, 'demote', idx);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
降级
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size={'small'}
|
||||||
|
negative
|
||||||
|
onClick={() => {
|
||||||
|
manageUser(user.username, 'delete', idx);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
删除
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size={'small'}
|
||||||
|
onClick={() => {
|
||||||
|
manageUser(
|
||||||
|
user.username,
|
||||||
|
user.status === 1 ? 'disable' : 'enable',
|
||||||
|
idx
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{user.status === 1 ? '禁用' : '启用'}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size={'small'}
|
||||||
|
as={Link}
|
||||||
|
to={'/user/edit/' + user.id}
|
||||||
|
>
|
||||||
|
编辑
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</Table.Cell>
|
||||||
|
</Table.Row>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</Table.Body>
|
||||||
|
|
||||||
|
<Table.Footer>
|
||||||
|
<Table.Row>
|
||||||
|
<Table.HeaderCell colSpan='6'>
|
||||||
|
<Button size='small' as={Link} to='/user/add' loading={loading}>
|
||||||
|
添加新的用户
|
||||||
|
</Button>
|
||||||
|
<Pagination
|
||||||
|
floated='right'
|
||||||
|
activePage={activePage}
|
||||||
|
onPageChange={onPaginationChange}
|
||||||
|
size='small'
|
||||||
|
siblingRange={1}
|
||||||
|
totalPages={
|
||||||
|
Math.ceil(users.length / ITEMS_PER_PAGE) +
|
||||||
|
(users.length % ITEMS_PER_PAGE === 0 ? 1 : 0)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</Table.HeaderCell>
|
||||||
|
</Table.Row>
|
||||||
|
</Table.Footer>
|
||||||
|
</Table>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default UsersTable;
|
1
web/src/constants/common.constant.js
Normal file
1
web/src/constants/common.constant.js
Normal file
@ -0,0 +1 @@
|
|||||||
|
export const ITEMS_PER_PAGE = 10; // this value must keep same as the one defined in backend!
|
3
web/src/constants/index.js
Normal file
3
web/src/constants/index.js
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
export * from './toast.constants';
|
||||||
|
export * from './user.constants';
|
||||||
|
export * from './common.constant';
|
6
web/src/constants/toast.constants.js
Normal file
6
web/src/constants/toast.constants.js
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
export const toastConstants = {
|
||||||
|
SUCCESS_TIMEOUT: 500,
|
||||||
|
INFO_TIMEOUT: 3000,
|
||||||
|
ERROR_TIMEOUT: 5000,
|
||||||
|
NOTICE_TIMEOUT: 20000
|
||||||
|
};
|
19
web/src/constants/user.constants.js
Normal file
19
web/src/constants/user.constants.js
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
export const userConstants = {
|
||||||
|
REGISTER_REQUEST: 'USERS_REGISTER_REQUEST',
|
||||||
|
REGISTER_SUCCESS: 'USERS_REGISTER_SUCCESS',
|
||||||
|
REGISTER_FAILURE: 'USERS_REGISTER_FAILURE',
|
||||||
|
|
||||||
|
LOGIN_REQUEST: 'USERS_LOGIN_REQUEST',
|
||||||
|
LOGIN_SUCCESS: 'USERS_LOGIN_SUCCESS',
|
||||||
|
LOGIN_FAILURE: 'USERS_LOGIN_FAILURE',
|
||||||
|
|
||||||
|
LOGOUT: 'USERS_LOGOUT',
|
||||||
|
|
||||||
|
GETALL_REQUEST: 'USERS_GETALL_REQUEST',
|
||||||
|
GETALL_SUCCESS: 'USERS_GETALL_SUCCESS',
|
||||||
|
GETALL_FAILURE: 'USERS_GETALL_FAILURE',
|
||||||
|
|
||||||
|
DELETE_REQUEST: 'USERS_DELETE_REQUEST',
|
||||||
|
DELETE_SUCCESS: 'USERS_DELETE_SUCCESS',
|
||||||
|
DELETE_FAILURE: 'USERS_DELETE_FAILURE'
|
||||||
|
};
|
19
web/src/context/User/index.js
Normal file
19
web/src/context/User/index.js
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
// contexts/User/index.jsx
|
||||||
|
|
||||||
|
import React from "react"
|
||||||
|
import { reducer, initialState } from "./reducer"
|
||||||
|
|
||||||
|
export const UserContext = React.createContext({
|
||||||
|
state: initialState,
|
||||||
|
dispatch: () => null
|
||||||
|
})
|
||||||
|
|
||||||
|
export const UserProvider = ({ children }) => {
|
||||||
|
const [state, dispatch] = React.useReducer(reducer, initialState)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<UserContext.Provider value={[ state, dispatch ]}>
|
||||||
|
{ children }
|
||||||
|
</UserContext.Provider>
|
||||||
|
)
|
||||||
|
}
|
21
web/src/context/User/reducer.js
Normal file
21
web/src/context/User/reducer.js
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
export const reducer = (state, action) => {
|
||||||
|
switch (action.type) {
|
||||||
|
case 'login':
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
user: action.payload
|
||||||
|
};
|
||||||
|
case 'logout':
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
user: undefined
|
||||||
|
};
|
||||||
|
|
||||||
|
default:
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const initialState = {
|
||||||
|
user: undefined
|
||||||
|
};
|
13
web/src/helpers/api.js
Normal file
13
web/src/helpers/api.js
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
import { showError } from './utils';
|
||||||
|
import axios from 'axios';
|
||||||
|
|
||||||
|
export const API = axios.create({
|
||||||
|
baseURL: process.env.REACT_APP_SERVER ? process.env.REACT_APP_SERVER : '',
|
||||||
|
});
|
||||||
|
|
||||||
|
API.interceptors.response.use(
|
||||||
|
(response) => response,
|
||||||
|
(error) => {
|
||||||
|
showError(error);
|
||||||
|
}
|
||||||
|
);
|
10
web/src/helpers/auth-header.js
Normal file
10
web/src/helpers/auth-header.js
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
export function authHeader() {
|
||||||
|
// return authorization header with jwt token
|
||||||
|
let user = JSON.parse(localStorage.getItem('user'));
|
||||||
|
|
||||||
|
if (user && user.token) {
|
||||||
|
return { 'Authorization': 'Bearer ' + user.token };
|
||||||
|
} else {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
}
|
3
web/src/helpers/history.js
Normal file
3
web/src/helpers/history.js
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
import { createBrowserHistory } from 'history';
|
||||||
|
|
||||||
|
export const history = createBrowserHistory();
|
4
web/src/helpers/index.js
Normal file
4
web/src/helpers/index.js
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
export * from './history';
|
||||||
|
export * from './auth-header';
|
||||||
|
export * from './utils';
|
||||||
|
export * from './api';
|
99
web/src/helpers/utils.js
Normal file
99
web/src/helpers/utils.js
Normal file
@ -0,0 +1,99 @@
|
|||||||
|
import { toast } from 'react-toastify';
|
||||||
|
import { toastConstants } from '../constants';
|
||||||
|
|
||||||
|
export function isAdmin() {
|
||||||
|
let user = localStorage.getItem('user');
|
||||||
|
if (!user) return false;
|
||||||
|
user = JSON.parse(user);
|
||||||
|
return user.role >= 10;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isRoot() {
|
||||||
|
let user = localStorage.getItem('user');
|
||||||
|
if (!user) return false;
|
||||||
|
user = JSON.parse(user);
|
||||||
|
return user.role >= 100;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function copy(text) {
|
||||||
|
let okay = true;
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(text);
|
||||||
|
} catch (e) {
|
||||||
|
okay = false;
|
||||||
|
console.error(e);
|
||||||
|
}
|
||||||
|
return okay;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isMobile() {
|
||||||
|
return window.innerWidth <= 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
let showErrorOptions = { autoClose: toastConstants.ERROR_TIMEOUT };
|
||||||
|
let showSuccessOptions = { autoClose: toastConstants.SUCCESS_TIMEOUT };
|
||||||
|
let showInfoOptions = { autoClose: toastConstants.INFO_TIMEOUT };
|
||||||
|
let showNoticeOptions = { autoClose: false };
|
||||||
|
|
||||||
|
if (isMobile()) {
|
||||||
|
showErrorOptions.position = 'top-center';
|
||||||
|
// showErrorOptions.transition = 'flip';
|
||||||
|
|
||||||
|
showSuccessOptions.position = 'top-center';
|
||||||
|
// showSuccessOptions.transition = 'flip';
|
||||||
|
|
||||||
|
showInfoOptions.position = 'top-center';
|
||||||
|
// showInfoOptions.transition = 'flip';
|
||||||
|
|
||||||
|
showNoticeOptions.position = 'top-center';
|
||||||
|
// showNoticeOptions.transition = 'flip';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function showError(error) {
|
||||||
|
console.error(error);
|
||||||
|
if (error.message) {
|
||||||
|
if (error.name === 'AxiosError') {
|
||||||
|
switch (error.message) {
|
||||||
|
case 'Request failed with status code 429':
|
||||||
|
toast.error('错误:请求次数过多,请稍后再试!', showErrorOptions);
|
||||||
|
break;
|
||||||
|
case 'Request failed with status code 500':
|
||||||
|
toast.error('错误:服务器内部错误,请联系管理员!', showErrorOptions);
|
||||||
|
break;
|
||||||
|
case 'Request failed with status code 405':
|
||||||
|
toast.info('本站仅作演示之用,无服务端!');
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
toast.error('错误:' + error.message, showErrorOptions);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
toast.error('错误:' + error.message, showErrorOptions);
|
||||||
|
} else {
|
||||||
|
toast.error('错误:' + error, showErrorOptions);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function showSuccess(message) {
|
||||||
|
toast.success(message, showSuccessOptions);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function showInfo(message) {
|
||||||
|
toast.info(message, showInfoOptions);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function showNotice(message) {
|
||||||
|
toast.info(message, showNoticeOptions);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function openPage(url) {
|
||||||
|
window.open(url);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function removeTrailingSlash(url) {
|
||||||
|
if (url.endsWith('/')) {
|
||||||
|
return url.slice(0, -1);
|
||||||
|
} else {
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
}
|
30
web/src/index.css
Normal file
30
web/src/index.css
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
padding-top: 55px;
|
||||||
|
overflow-y: scroll;
|
||||||
|
font-family: Lato, 'Helvetica Neue', Arial, Helvetica, "Microsoft YaHei", sans-serif;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
-moz-osx-font-smoothing: grayscale;
|
||||||
|
}
|
||||||
|
|
||||||
|
code {
|
||||||
|
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace;
|
||||||
|
}
|
||||||
|
|
||||||
|
.main-content {
|
||||||
|
padding: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.small-icon .icon {
|
||||||
|
font-size: 1em !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.custom-footer {
|
||||||
|
font-size: 1.1em;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media only screen and (max-width: 600px) {
|
||||||
|
.hide-on-mobile {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
}
|
29
web/src/index.js
Normal file
29
web/src/index.js
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import ReactDOM from 'react-dom/client';
|
||||||
|
import { BrowserRouter } from 'react-router-dom';
|
||||||
|
import { Container } from 'semantic-ui-react';
|
||||||
|
import App from './App';
|
||||||
|
import Header from './components/Header';
|
||||||
|
import Footer from './components/Footer';
|
||||||
|
import 'semantic-ui-css/semantic.min.css';
|
||||||
|
import './index.css';
|
||||||
|
import { UserProvider } from './context/User';
|
||||||
|
import { ToastContainer } from 'react-toastify';
|
||||||
|
import 'react-toastify/dist/ReactToastify.css';
|
||||||
|
|
||||||
|
|
||||||
|
const root = ReactDOM.createRoot(document.getElementById('root'));
|
||||||
|
root.render(
|
||||||
|
<React.StrictMode>
|
||||||
|
<UserProvider>
|
||||||
|
<BrowserRouter>
|
||||||
|
<Header />
|
||||||
|
<Container className={'main-content'}>
|
||||||
|
<App />
|
||||||
|
</Container>
|
||||||
|
<ToastContainer/>
|
||||||
|
<Footer />
|
||||||
|
</BrowserRouter>
|
||||||
|
</UserProvider>
|
||||||
|
</React.StrictMode>
|
||||||
|
);
|
47
web/src/pages/About/index.js
Normal file
47
web/src/pages/About/index.js
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
import React, { useEffect, useState } from 'react';
|
||||||
|
import { Header, Segment } from 'semantic-ui-react';
|
||||||
|
import { API, showError } from '../../helpers';
|
||||||
|
import { marked } from 'marked';
|
||||||
|
|
||||||
|
const About = () => {
|
||||||
|
const [about, setAbout] = useState('');
|
||||||
|
|
||||||
|
const displayAbout = async () => {
|
||||||
|
const res = await API.get('/api/about');
|
||||||
|
const { success, message, data } = res.data;
|
||||||
|
if (success) {
|
||||||
|
let HTMLAbout = marked.parse(data);
|
||||||
|
localStorage.setItem('about', HTMLAbout);
|
||||||
|
setAbout(HTMLAbout);
|
||||||
|
} else {
|
||||||
|
showError(message);
|
||||||
|
setAbout('加载关于内容失败...');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
displayAbout().then();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Segment>
|
||||||
|
{
|
||||||
|
about === '' ? <>
|
||||||
|
<Header as='h3'>关于</Header>
|
||||||
|
<p>可在设置页面设置关于内容,支持 HTML & Markdown</p>
|
||||||
|
项目仓库地址:
|
||||||
|
<a href="https://github.com/songquanpeng/gin-template">
|
||||||
|
https://github.com/songquanpeng/gin-template
|
||||||
|
</a>
|
||||||
|
</> : <>
|
||||||
|
<div dangerouslySetInnerHTML={{ __html: about}}></div>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
</Segment>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
export default About;
|
14
web/src/pages/File/index.js
Normal file
14
web/src/pages/File/index.js
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { Header, Segment } from 'semantic-ui-react';
|
||||||
|
import FilesTable from '../../components/FilesTable';
|
||||||
|
|
||||||
|
const File = () => (
|
||||||
|
<>
|
||||||
|
<Segment>
|
||||||
|
<Header as='h3'>管理文件</Header>
|
||||||
|
<FilesTable />
|
||||||
|
</Segment>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
|
||||||
|
export default File;
|
78
web/src/pages/Home/index.js
Normal file
78
web/src/pages/Home/index.js
Normal file
@ -0,0 +1,78 @@
|
|||||||
|
import React, { useEffect } from 'react';
|
||||||
|
import { Grid, Header, Placeholder, Segment } from 'semantic-ui-react';
|
||||||
|
import { API, showError, showNotice } from '../../helpers';
|
||||||
|
|
||||||
|
const Home = () => {
|
||||||
|
const displayNotice = async () => {
|
||||||
|
const res = await API.get('/api/notice');
|
||||||
|
const { success, message, data } = res.data;
|
||||||
|
if (success) {
|
||||||
|
let oldNotice = localStorage.getItem('notice');
|
||||||
|
if (data !== oldNotice && data !== '') {
|
||||||
|
showNotice(data);
|
||||||
|
localStorage.setItem('notice', data);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
showError(message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
displayNotice().then();
|
||||||
|
}, []);
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Segment>
|
||||||
|
<Header as="h3">示例标题</Header>
|
||||||
|
<Grid columns={3} stackable>
|
||||||
|
<Grid.Column>
|
||||||
|
<Segment raised>
|
||||||
|
<Placeholder>
|
||||||
|
<Placeholder.Header image>
|
||||||
|
<Placeholder.Line />
|
||||||
|
<Placeholder.Line />
|
||||||
|
</Placeholder.Header>
|
||||||
|
<Placeholder.Paragraph>
|
||||||
|
<Placeholder.Line length="medium" />
|
||||||
|
<Placeholder.Line length="short" />
|
||||||
|
</Placeholder.Paragraph>
|
||||||
|
</Placeholder>
|
||||||
|
</Segment>
|
||||||
|
</Grid.Column>
|
||||||
|
|
||||||
|
<Grid.Column>
|
||||||
|
<Segment raised>
|
||||||
|
<Placeholder>
|
||||||
|
<Placeholder.Header image>
|
||||||
|
<Placeholder.Line />
|
||||||
|
<Placeholder.Line />
|
||||||
|
</Placeholder.Header>
|
||||||
|
<Placeholder.Paragraph>
|
||||||
|
<Placeholder.Line length="medium" />
|
||||||
|
<Placeholder.Line length="short" />
|
||||||
|
</Placeholder.Paragraph>
|
||||||
|
</Placeholder>
|
||||||
|
</Segment>
|
||||||
|
</Grid.Column>
|
||||||
|
|
||||||
|
<Grid.Column>
|
||||||
|
<Segment raised>
|
||||||
|
<Placeholder>
|
||||||
|
<Placeholder.Header image>
|
||||||
|
<Placeholder.Line />
|
||||||
|
<Placeholder.Line />
|
||||||
|
</Placeholder.Header>
|
||||||
|
<Placeholder.Paragraph>
|
||||||
|
<Placeholder.Line length="medium" />
|
||||||
|
<Placeholder.Line length="short" />
|
||||||
|
</Placeholder.Paragraph>
|
||||||
|
</Placeholder>
|
||||||
|
</Segment>
|
||||||
|
</Grid.Column>
|
||||||
|
</Grid>
|
||||||
|
</Segment>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Home;
|
20
web/src/pages/NotFound/index.js
Normal file
20
web/src/pages/NotFound/index.js
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { Segment, Header } from 'semantic-ui-react';
|
||||||
|
|
||||||
|
const NotFound = () => (
|
||||||
|
<>
|
||||||
|
<Header
|
||||||
|
block
|
||||||
|
as="h4"
|
||||||
|
content="404"
|
||||||
|
attached="top"
|
||||||
|
icon="info"
|
||||||
|
className="small-icon"
|
||||||
|
/>
|
||||||
|
<Segment attached="bottom">
|
||||||
|
未找到所请求的页面
|
||||||
|
</Segment>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
|
||||||
|
export default NotFound;
|
46
web/src/pages/Setting/index.js
Normal file
46
web/src/pages/Setting/index.js
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { Segment, Tab } from 'semantic-ui-react';
|
||||||
|
import SystemSetting from '../../components/SystemSetting';
|
||||||
|
import { isRoot } from '../../helpers';
|
||||||
|
import OtherSetting from '../../components/OtherSetting';
|
||||||
|
import PersonalSetting from '../../components/PersonalSetting';
|
||||||
|
|
||||||
|
const Setting = () => {
|
||||||
|
let panes = [
|
||||||
|
{
|
||||||
|
menuItem: '个人设置',
|
||||||
|
render: () => (
|
||||||
|
<Tab.Pane attached={false}>
|
||||||
|
<PersonalSetting />
|
||||||
|
</Tab.Pane>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
if (isRoot()) {
|
||||||
|
panes.push({
|
||||||
|
menuItem: '系统设置',
|
||||||
|
render: () => (
|
||||||
|
<Tab.Pane attached={false}>
|
||||||
|
<SystemSetting />
|
||||||
|
</Tab.Pane>
|
||||||
|
)
|
||||||
|
});
|
||||||
|
panes.push({
|
||||||
|
menuItem: '其他设置',
|
||||||
|
render: () => (
|
||||||
|
<Tab.Pane attached={false}>
|
||||||
|
<OtherSetting />
|
||||||
|
</Tab.Pane>
|
||||||
|
)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Segment>
|
||||||
|
<Tab menu={{ secondary: true, pointing: true }} panes={panes} />
|
||||||
|
</Segment>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Setting;
|
77
web/src/pages/User/AddUser.js
Normal file
77
web/src/pages/User/AddUser.js
Normal file
@ -0,0 +1,77 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import { Button, Form, Header, Segment } from 'semantic-ui-react';
|
||||||
|
import { API, showError, showSuccess } from '../../helpers';
|
||||||
|
|
||||||
|
const AddUser = () => {
|
||||||
|
const originInputs = {
|
||||||
|
username: '',
|
||||||
|
display_name: '',
|
||||||
|
password: '',
|
||||||
|
};
|
||||||
|
const [inputs, setInputs] = useState(originInputs);
|
||||||
|
const { username, display_name, password } = inputs;
|
||||||
|
|
||||||
|
const handleInputChange = (e, { name, value }) => {
|
||||||
|
setInputs((inputs) => ({ ...inputs, [name]: value }));
|
||||||
|
};
|
||||||
|
|
||||||
|
const submit = async () => {
|
||||||
|
if (inputs.username === '' || inputs.password === '') return;
|
||||||
|
const res = await API.post(`/api/user/`, inputs);
|
||||||
|
const { success, message } = res.data;
|
||||||
|
if (success) {
|
||||||
|
showSuccess('用户账户创建成功!');
|
||||||
|
setInputs(originInputs);
|
||||||
|
} else {
|
||||||
|
showError(message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Segment>
|
||||||
|
<Header as="h3">创建新用户账户</Header>
|
||||||
|
<Form autoComplete="off">
|
||||||
|
<Form.Field>
|
||||||
|
<Form.Input
|
||||||
|
label="用户名"
|
||||||
|
name="username"
|
||||||
|
placeholder={'请输入用户名'}
|
||||||
|
onChange={handleInputChange}
|
||||||
|
value={username}
|
||||||
|
autoComplete="off"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</Form.Field>
|
||||||
|
<Form.Field>
|
||||||
|
<Form.Input
|
||||||
|
label="显示名称"
|
||||||
|
name="display_name"
|
||||||
|
placeholder={'请输入显示名称'}
|
||||||
|
onChange={handleInputChange}
|
||||||
|
value={display_name}
|
||||||
|
autoComplete="off"
|
||||||
|
/>
|
||||||
|
</Form.Field>
|
||||||
|
<Form.Field>
|
||||||
|
<Form.Input
|
||||||
|
label="密码"
|
||||||
|
name="password"
|
||||||
|
type={'password'}
|
||||||
|
placeholder={'请输入密码'}
|
||||||
|
onChange={handleInputChange}
|
||||||
|
value={password}
|
||||||
|
autoComplete="off"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</Form.Field>
|
||||||
|
<Button type={'submit'} onClick={submit}>
|
||||||
|
提交
|
||||||
|
</Button>
|
||||||
|
</Form>
|
||||||
|
</Segment>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default AddUser;
|
132
web/src/pages/User/EditUser.js
Normal file
132
web/src/pages/User/EditUser.js
Normal file
@ -0,0 +1,132 @@
|
|||||||
|
import React, { useEffect, useState } from 'react';
|
||||||
|
import { Button, Form, Header, Segment } from 'semantic-ui-react';
|
||||||
|
import { useParams } from 'react-router-dom';
|
||||||
|
import { API, showError, showSuccess } from '../../helpers';
|
||||||
|
|
||||||
|
const EditUser = () => {
|
||||||
|
const params = useParams();
|
||||||
|
const userId = params.id;
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [inputs, setInputs] = useState({
|
||||||
|
username: '',
|
||||||
|
display_name: '',
|
||||||
|
password: '',
|
||||||
|
github_id: '',
|
||||||
|
wechat_id: '',
|
||||||
|
email: '',
|
||||||
|
});
|
||||||
|
const { username, display_name, password, github_id, wechat_id, email } =
|
||||||
|
inputs;
|
||||||
|
const handleInputChange = (e, { name, value }) => {
|
||||||
|
setInputs((inputs) => ({ ...inputs, [name]: value }));
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadUser = async () => {
|
||||||
|
let res = undefined;
|
||||||
|
if (userId) {
|
||||||
|
res = await API.get(`/api/user/${userId}`);
|
||||||
|
} else {
|
||||||
|
res = await API.get(`/api/user/self`);
|
||||||
|
}
|
||||||
|
const { success, message, data } = res.data;
|
||||||
|
if (success) {
|
||||||
|
data.password = '';
|
||||||
|
setInputs(data);
|
||||||
|
} else {
|
||||||
|
showError(message);
|
||||||
|
}
|
||||||
|
setLoading(false);
|
||||||
|
};
|
||||||
|
useEffect(() => {
|
||||||
|
loadUser().then();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const submit = async () => {
|
||||||
|
let res = undefined;
|
||||||
|
if (userId) {
|
||||||
|
res = await API.put(`/api/user/`, { ...inputs, id: parseInt(userId) });
|
||||||
|
} else {
|
||||||
|
res = await API.put(`/api/user/self`, inputs);
|
||||||
|
}
|
||||||
|
const { success, message } = res.data;
|
||||||
|
if (success) {
|
||||||
|
showSuccess('用户信息更新成功!');
|
||||||
|
} else {
|
||||||
|
showError(message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Segment loading={loading}>
|
||||||
|
<Header as='h3'>更新用户信息</Header>
|
||||||
|
<Form autoComplete='off'>
|
||||||
|
<Form.Field>
|
||||||
|
<Form.Input
|
||||||
|
label='用户名'
|
||||||
|
name='username'
|
||||||
|
placeholder={'请输入新的用户名'}
|
||||||
|
onChange={handleInputChange}
|
||||||
|
value={username}
|
||||||
|
autoComplete='off'
|
||||||
|
/>
|
||||||
|
</Form.Field>
|
||||||
|
<Form.Field>
|
||||||
|
<Form.Input
|
||||||
|
label='密码'
|
||||||
|
name='password'
|
||||||
|
type={'password'}
|
||||||
|
placeholder={'请输入新的密码'}
|
||||||
|
onChange={handleInputChange}
|
||||||
|
value={password}
|
||||||
|
autoComplete='off'
|
||||||
|
/>
|
||||||
|
</Form.Field>
|
||||||
|
<Form.Field>
|
||||||
|
<Form.Input
|
||||||
|
label='显示名称'
|
||||||
|
name='display_name'
|
||||||
|
placeholder={'请输入新的显示名称'}
|
||||||
|
onChange={handleInputChange}
|
||||||
|
value={display_name}
|
||||||
|
autoComplete='off'
|
||||||
|
/>
|
||||||
|
</Form.Field>
|
||||||
|
<Form.Field>
|
||||||
|
<Form.Input
|
||||||
|
label='已绑定的 GitHub 账户'
|
||||||
|
name='github_id'
|
||||||
|
value={github_id}
|
||||||
|
autoComplete='off'
|
||||||
|
placeholder='此项只读,需要用户通过个人设置页面的相关绑定按钮进行绑定,不可直接修改'
|
||||||
|
readOnly
|
||||||
|
/>
|
||||||
|
</Form.Field>
|
||||||
|
<Form.Field>
|
||||||
|
<Form.Input
|
||||||
|
label='已绑定的微信账户'
|
||||||
|
name='wechat_id'
|
||||||
|
value={wechat_id}
|
||||||
|
autoComplete='off'
|
||||||
|
placeholder='此项只读,需要用户通过个人设置页面的相关绑定按钮进行绑定,不可直接修改'
|
||||||
|
readOnly
|
||||||
|
/>
|
||||||
|
</Form.Field>
|
||||||
|
<Form.Field>
|
||||||
|
<Form.Input
|
||||||
|
label='已绑定的邮箱账户'
|
||||||
|
name='email'
|
||||||
|
value={email}
|
||||||
|
autoComplete='off'
|
||||||
|
placeholder='此项只读,需要用户通过个人设置页面的相关绑定按钮进行绑定,不可直接修改'
|
||||||
|
readOnly
|
||||||
|
/>
|
||||||
|
</Form.Field>
|
||||||
|
<Button onClick={submit}>提交</Button>
|
||||||
|
</Form>
|
||||||
|
</Segment>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default EditUser;
|
14
web/src/pages/User/index.js
Normal file
14
web/src/pages/User/index.js
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { Segment, Header } from 'semantic-ui-react';
|
||||||
|
import UsersTable from '../../components/UsersTable';
|
||||||
|
|
||||||
|
const User = () => (
|
||||||
|
<>
|
||||||
|
<Segment>
|
||||||
|
<Header as='h3'>管理用户</Header>
|
||||||
|
<UsersTable/>
|
||||||
|
</Segment>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
|
||||||
|
export default User;
|
5
web/vercel.json
Normal file
5
web/vercel.json
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"github": {
|
||||||
|
"silent": true
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user