├── .env.example ├── .gitignore ├── .npmrc ├── LICENSE ├── README.md ├── backend ├── .autod.conf.js ├── .env.example ├── .env.local ├── .eslintignore ├── .eslintrc ├── .sequelizerc ├── .travis.yml ├── README.md ├── app.js ├── app │ ├── controller │ │ ├── home.js │ │ ├── post.js │ │ ├── role.js │ │ └── user.js │ ├── extend │ │ └── helper.js │ ├── model │ │ ├── post.js │ │ ├── role.js │ │ └── user.js │ ├── router.js │ └── service │ │ ├── post.js │ │ ├── role.js │ │ └── user.js ├── appveyor.yml ├── config │ ├── config.default.js │ ├── config.local.js │ └── plugin.js ├── database │ ├── config.js │ ├── db.sql │ └── migrations │ │ ├── 20200204074424-init-user.js │ │ ├── 20200204074427-init-role.js │ │ ├── 20200204074431-init-post.js │ │ └── 20200204074502-add-associations.js ├── docker-compose.yml ├── jsconfig.json ├── layer │ └── serverless.yml ├── package.json ├── serverless.yml ├── sls.js ├── test │ ├── .setup.js │ ├── app │ │ └── controller │ │ │ ├── home.test.js │ │ │ ├── post.test.js │ │ │ ├── role.test.js │ │ │ └── user.test.js │ └── factories.js └── typings │ ├── app │ ├── controller │ │ └── index.d.ts │ ├── extend │ │ └── helper.d.ts │ ├── index.d.ts │ ├── model │ │ └── index.d.ts │ └── service │ │ └── index.d.ts │ └── config │ ├── index.d.ts │ └── plugin.d.ts ├── db └── serverless.yml ├── frontend ├── .editorconfig ├── .env.development ├── .env.production ├── .eslintignore ├── .eslintrc.js ├── .gitignore ├── .npmrc ├── .travis.yml ├── README-zh.md ├── README.md ├── babel.config.js ├── build │ └── index.js ├── jest.config.js ├── jsconfig.json ├── package.json ├── postcss.config.js ├── public │ ├── favicon.ico │ └── index.html ├── serverless.yml ├── src │ ├── App.vue │ ├── api │ │ ├── post.js │ │ └── user.js │ ├── assets │ │ ├── 404_images │ │ │ ├── 404.png │ │ │ └── 404_cloud.png │ │ └── authing.png │ ├── components │ │ ├── Breadcrumb │ │ │ └── index.vue │ │ ├── Hamburger │ │ │ └── index.vue │ │ └── SvgIcon │ │ │ └── index.vue │ ├── icons │ │ ├── index.js │ │ ├── svg │ │ │ ├── dashboard.svg │ │ │ ├── example.svg │ │ │ ├── eye-open.svg │ │ │ ├── eye.svg │ │ │ ├── form.svg │ │ │ ├── link.svg │ │ │ ├── nested.svg │ │ │ ├── password.svg │ │ │ ├── table.svg │ │ │ ├── tree.svg │ │ │ └── user.svg │ │ └── svgo.yml │ ├── layout │ │ ├── components │ │ │ ├── AppMain.vue │ │ │ ├── Navbar.vue │ │ │ ├── Sidebar │ │ │ │ ├── FixiOSBug.js │ │ │ │ ├── Item.vue │ │ │ │ ├── Link.vue │ │ │ │ ├── Logo.vue │ │ │ │ ├── SidebarItem.vue │ │ │ │ └── index.vue │ │ │ └── index.js │ │ ├── index.vue │ │ └── mixin │ │ │ └── ResizeHandler.js │ ├── main.js │ ├── permission.js │ ├── router │ │ └── index.js │ ├── settings.js │ ├── store │ │ ├── getters.js │ │ ├── index.js │ │ └── modules │ │ │ ├── app.js │ │ │ ├── settings.js │ │ │ └── user.js │ ├── styles │ │ ├── element-ui.scss │ │ ├── index.scss │ │ ├── mixin.scss │ │ ├── sidebar.scss │ │ ├── transition.scss │ │ └── variables.scss │ ├── utils │ │ ├── auth.js │ │ ├── get-page-title.js │ │ ├── index.js │ │ ├── request.js │ │ └── validate.js │ └── views │ │ ├── 404.vue │ │ ├── dashboard │ │ └── index.vue │ │ ├── login │ │ └── index.vue │ │ ├── nested │ │ ├── menu1 │ │ │ ├── index.vue │ │ │ ├── menu1-1 │ │ │ │ └── index.vue │ │ │ ├── menu1-2 │ │ │ │ ├── index.vue │ │ │ │ ├── menu1-2-1 │ │ │ │ │ └── index.vue │ │ │ │ └── menu1-2-2 │ │ │ │ │ └── index.vue │ │ │ └── menu1-3 │ │ │ │ └── index.vue │ │ └── menu2 │ │ │ └── index.vue │ │ ├── posts │ │ ├── create.vue │ │ └── index.vue │ │ └── tree │ │ └── index.vue ├── tests │ └── unit │ │ ├── .eslintrc.js │ │ ├── components │ │ ├── Breadcrumb.spec.js │ │ ├── Hamburger.spec.js │ │ └── SvgIcon.spec.js │ │ └── utils │ │ ├── formatTime.spec.js │ │ ├── parseTime.spec.js │ │ └── validate.spec.js └── vue.config.js ├── package.json ├── scripts └── bootstrap.js ├── serverless.template.yml └── vpc └── serverless.yml /.env.example: -------------------------------------------------------------------------------- 1 | TENCENT_SECRET_ID=xxx 2 | TENCENT_SECRET_KEY=xxx 3 | 4 | REGION=ap-guangzhou 5 | VPC_ID=xxx 6 | SUBNET_ID=xxx -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .env 2 | node_modules 3 | yarn.lock 4 | package-lock.json -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | registry=https://registry.npm.taobao.org/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Serverless Plus 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Serverless Admin System 2 | 3 | [在线体验](https://sls-admin.yugasun.com/) 4 | 5 | 使用 [Serverless Components](https://github.com/serverless/components) 开发的后台管理系统 6 | 7 | 1. [安装 CLI](#安装-CLI) 8 | 2. [初始化项目](#初始化项目) 9 | 3. [配置](#配置) 10 | 4. [部署](#部署) 11 | 5. [开发](#开发) 12 | 13 | ### 安装 CLI 14 | 15 | 在开始之前需要先安装 [Serverless CLI](https://github.com/serverless/serverless) 工具 16 | 17 | ```bash 18 | $ npm i serverless -g 19 | ``` 20 | 21 | ### 初始化项目 22 | 23 | Serverless 命令行工具非常方便,可以直接初始化项目模板: 24 | 25 | ```bash 26 | $ serverless init admin-system 27 | ``` 28 | 29 | 安装项目依赖: 30 | 31 | ```bash 32 | $ npm run bootstrap 33 | ``` 34 | 35 | ### 项目目录介绍 36 | 37 | ``` 38 | ├── backend 后端服务,Egg.js + PostgreSQL + Redis 39 | ├── db Serverless PG,使用 tencent-postgresql 组件部署创建 40 | ├── frontend 前端页面,Vue.js + vue-admin-template,项目模板:https://github.com/PanJiaChen/vue-admin-template 41 | ├── package.json 42 | ├── scripts 项目脚本,主要含有 bootstrap.js 用来自动安装前后端项目依赖 43 | └── vpc Serverless VPC,使用 tencent-vpc 组件部署,用来创建腾讯云私有网络 44 | ``` 45 | 46 | ### 配置 47 | 48 | 复制项目根目录的 `.env.example` 文件为 `.env`,内容如下: 49 | 50 | ```dotenv 51 | # .env 52 | TENCENT_SECRET_ID=xxx 53 | TENCENT_SECRET_KEY=xxx 54 | 55 | REGION=ap-guangzhou 56 | ZONE=ap-guangzhou-2 57 | ``` 58 | 59 | > 注意:`TENCENT_SECRET_ID` 和 `TENCENT_SECRET_KEY` 可以到 [腾讯云 CAM 控制台](https://bash.cloud.tencent.com/cam/capi) 获取。 60 | 61 | 由于后端服务使用 `redis` 来存储接口鉴权 Token,所以我们还需要给后端项目配置 redis 建连参数,复制 `backend` 目录的 `.env.example` 为 `.env`,然后配置自己的 redis 服务参数: 62 | 63 | ```dotenv 64 | REDIS_HOST=xxx 65 | REDIS_PORT=xxx 66 | REDIS_PASSWORD=xxx 67 | ``` 68 | 69 | 此项目也支持 [Authing](https://authing.cn/) 第三方登录,如果你不需要可以直接忽略,如果需要,可以到 [Authing 控制台](https://console.authing.cn/login) 获取配置,然后添加到 `backend/.env` 中: 70 | 71 | ```dotenv 72 | REDIS_HOST=xxx 73 | REDIS_PORT=xxx 74 | REDIS_PASSWORD=xxx 75 | 76 | # authing 应用配置 77 | AUTHING_APPID=xxx 78 | AUTHING_APPSECRET=xxx 79 | ``` 80 | 81 | ### 本地开发 82 | 83 | 后端服务使用的的数据库均使用本地 [Docker](https://www.docker.com/) 来启动,所以本地开发时,需要先启动 docker 服务: 84 | 85 | ```bash 86 | $ npm run docker:up 87 | ``` 88 | 89 | #### 启动后端服务 90 | 91 | ```bash 92 | $ npm run dev:be 93 | ``` 94 | 95 | #### 启动前端开发 96 | 97 | ```bash 98 | $ npm run dev:fe 99 | ``` 100 | 101 | ### 部署 102 | 103 | 在部署业务代码之前,我们需要先将后端的 `node_modules` 文件夹部署为层: 104 | 105 | ```bash 106 | $ npm run deploy:be:layer 107 | ``` 108 | 109 | > 注意:在层部署成功后,如果后端项目的 `node_modules` 没有修改,可以不用再次执行层部署。 110 | 111 | 部署项目代码: 112 | 113 | ```bash 114 | $ npm run deploy 115 | ``` 116 | 117 | ### 初始化数据库 118 | 119 | 部署成功后,我们就可以获得数据库相关参数,其中 postgresql 输出的 `public` 对象中的参数是用来公网访问的。 120 | 121 | 在访问服务前,我们还需要同步数据库表结构,修改 `database/config.js` 中的 `production` 对象的配置为 postgresql 输出的 `public` 对象中的参数值, 122 | 123 | 相关参数对应关系: 124 | 125 | | `postgresql.public` 输出 | `database/config.js` 中 `production` 参数 | 126 | | :----------------------: | :---------------------------------------: | 127 | | host | host | 128 | | port | post | 129 | | user | username | 130 | | password | password | 131 | | dbname | database | 132 | 133 | 然后我们执行: 134 | 135 | ```bash 136 | $ npm run db:migrate 137 | ``` 138 | 139 | 就可以自动帮助初始化数据库,包括表结构和测试数据。 140 | 141 | ### License 142 | 143 | MIT License 144 | 145 | Copyright (c) 2020 Serverless Plus 146 | -------------------------------------------------------------------------------- /backend/.autod.conf.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports = { 4 | write: true, 5 | prefix: '^', 6 | plugin: 'autod-egg', 7 | test: [ 8 | 'test', 9 | 'benchmark', 10 | ], 11 | dep: [ 12 | 'egg', 13 | 'egg-scripts', 14 | ], 15 | devdep: [ 16 | 'egg-ci', 17 | 'egg-bin', 18 | 'egg-mock', 19 | 'autod', 20 | 'autod-egg', 21 | 'eslint', 22 | 'eslint-config-egg', 23 | ], 24 | exclude: [ 25 | './test/fixtures', 26 | './dist', 27 | ], 28 | }; 29 | 30 | -------------------------------------------------------------------------------- /backend/.env.example: -------------------------------------------------------------------------------- 1 | REDIS_HOST=xxx 2 | REDIS_PORT=xxx 3 | REDIS_PASSWORD=xxx 4 | 5 | 6 | # authing app config, get from https://console.authing.cn/login 7 | AUTHING_APPID=xxx 8 | AUTHING_APPSECRET=xxx -------------------------------------------------------------------------------- /backend/.env.local: -------------------------------------------------------------------------------- 1 | # connect local docker postgre 2 | DB_HOST=127.0.0.1 3 | DB_PORT=5432 4 | DB_NAME=admin-system 5 | DB_USER=root 6 | DB_PASSWORD=root 7 | 8 | # connect local docker redis 9 | REDIS_HOST=127.0.0.1 10 | REDIS_PORT=6379 11 | REDIS_PASSWORD='' -------------------------------------------------------------------------------- /backend/.eslintignore: -------------------------------------------------------------------------------- 1 | coverage 2 | -------------------------------------------------------------------------------- /backend/.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "eslint-config-egg" 3 | } 4 | -------------------------------------------------------------------------------- /backend/.sequelizerc: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const path = require('path'); 4 | 5 | module.exports = { 6 | config: path.join(__dirname, 'database/config.json'), 7 | 'migrations-path': path.join(__dirname, 'database/migrations'), 8 | 'seeders-path': path.join(__dirname, 'database/seeders'), 9 | 'models-path': path.join(__dirname, 'app/model'), 10 | }; -------------------------------------------------------------------------------- /backend/.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: node_js 3 | node_js: 4 | - '10' 5 | before_install: 6 | - npm i npminstall -g 7 | install: 8 | - npminstall 9 | script: 10 | - npm run ci 11 | after_script: 12 | - npminstall codecov && codecov 13 | -------------------------------------------------------------------------------- /backend/README.md: -------------------------------------------------------------------------------- 1 | # Backend for serverless-admin-system 2 | 3 | ## QuickStart 4 | 5 | 6 | 7 | see [egg docs][egg] for more detail. 8 | 9 | ### Local Development 10 | 11 | **Firstly, start local docker images for postgresql and redis.** 12 | 13 | ```bash 14 | $ npm run docker:up 15 | ``` 16 | 17 | > Notice: docker must be installed. 18 | 19 | **Then, copy `.env.example` file to `.env.local`, and config for postgresql and redis.** 20 | 21 | ```bash 22 | $ npm i 23 | $ npm run dev 24 | $ open http://localhost:7001/ 25 | ``` 26 | 27 | ### Deploy 28 | 29 | ```bash 30 | $ npm start 31 | $ npm stop 32 | ``` 33 | 34 | ### npm scripts 35 | 36 | - Use `npm run lint` to check code style. 37 | - Use `npm test` to run unit test. 38 | - Use `npm run autod` to auto detect dependencies upgrade, see 39 | [autod](https://www.npmjs.com/package/autod) for more detail. 40 | 41 | [egg]: https://eggjs.org 42 | -------------------------------------------------------------------------------- /backend/app.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | class AppBootHook { 4 | constructor(app) { 5 | this.app = app; 6 | } 7 | 8 | configWillLoad() { 9 | // The config file has been read and merged, but it has not yet taken effect 10 | // This is the last time the application layer modifies the configuration 11 | // Note: This function only supports synchronous calls. 12 | // For example: the password in the parameter is encrypted, decrypt it here 13 | } 14 | 15 | async didLoad() { 16 | // All configurations have been loaded 17 | // Can be used to load the application custom file, start a custom service 18 | } 19 | 20 | async willReady() { 21 | // All plugins have been started, but the application is not yet ready 22 | // Can do some data initialization and other operations 23 | // Application will start after these operations executed succcessfully 24 | 25 | // For example: loading data from the database into the in-memory cache 26 | // TODO: init db migrate locally, it can not sync in scf, 27 | // TODO: better db miration method is using remote connection, and run `sequelize db:migrate` locally 28 | const isDev = process.env.NODE_ENV === 'development'; 29 | if (isDev && this.app.config.sequelize.sync) { 30 | try { 31 | console.log('Start syncing database models...'); 32 | // Notice!!!: For security you should not set force to true, because it will drop all tables. 33 | await this.app.model.sync({ logging: console.log, force: isDev }); 34 | console.log('Start init database data...'); 35 | // TODO: this init data is for demo 36 | await this.app.model.query("INSERT INTO roles (id, name, created_at, updated_at) VALUES (1, 'admin', '2020-02-04 09:54:25', '2020-02-04 09:54:25'),(2, 'editor', '2020-02-04 09:54:30', '2020-02-04 09:54:30');"); 37 | await this.app.model.query("INSERT INTO users (id, name, password, age, avatar, introduction, register_type, created_at, updated_at, role_id) VALUES (1, 'admin', 'e10adc3949ba59abbe56e057f20f883e', 20, 'https://yugasun.com/static/avatar.jpg', 'Fullstack Engineer', 'default', '2020-02-04 09:55:23', '2020-02-04 09:55:23', 1);"); 38 | await this.app.model.query("INSERT INTO posts (id, title, content, created_at, updated_at, user_id) VALUES (2, 'Awesome Egg.js', 'Egg.js is a awesome framework', '2020-02-04 09:57:24', '2020-02-04 09:57:24', 1),(3, 'Awesome Serverless', 'Build web, mobile and IoT applications using Tencent Cloud and API Gateway, Tencent Cloud Functions, and more.', '2020-02-04 10:00:23', '2020-02-04 10:00:23', 1);"); 39 | console.log('Successfully init database data.'); 40 | console.log('Successfully sync database models.'); 41 | } catch (e) { 42 | console.log(e); 43 | throw new Error('Database migration failed.'); 44 | } 45 | } 46 | } 47 | 48 | async didReady() { 49 | // Application already ready 50 | } 51 | 52 | async serverDidReady() { 53 | // http / https server has started and begins accepting external requests 54 | // At this point you can get an instance of server from app.server 55 | } 56 | } 57 | 58 | module.exports = AppBootHook; 59 | -------------------------------------------------------------------------------- /backend/app/controller/home.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Controller = require('egg').Controller; 4 | 5 | class HomeController extends Controller { 6 | async index() { 7 | const { ctx } = this; 8 | ctx.body = 'hi, egg'; 9 | } 10 | 11 | async getAppConfig() { 12 | const { ctx, app } = this; 13 | ctx.body = app.config; 14 | } 15 | 16 | async login() { 17 | const { ctx, app, config } = this; 18 | const { service, helper } = ctx; 19 | const { username, password } = ctx.request.body; 20 | const user = await service.user.findByName(username); 21 | if (!user) { 22 | ctx.status = 403; 23 | ctx.body = { 24 | code: 403, 25 | message: 'Username or password wrong', 26 | }; 27 | } else { 28 | if (user.password === helper.encryptPwd(password)) { 29 | ctx.status = 200; 30 | const token = app.jwt.sign({ 31 | id: user.id, 32 | name: user.name, 33 | role: user.role.name, 34 | avatar: user.avatar, 35 | }, config.jwt.secret, { 36 | expiresIn: '1h', 37 | }); 38 | try { 39 | 40 | await app.redis.set(`token_${user.id}`, token); 41 | ctx.body = { 42 | code: 0, 43 | message: 'Get token success', 44 | token, 45 | }; 46 | } catch (e) { 47 | console.error(e); 48 | ctx.body = { 49 | code: 500, 50 | message: 'Server busy, please try again', 51 | }; 52 | } 53 | } else { 54 | ctx.status = 403; 55 | ctx.body = { 56 | code: 403, 57 | message: 'Username or password wrong', 58 | }; 59 | } 60 | } 61 | } 62 | 63 | async userInfo() { 64 | const { ctx } = this; 65 | const { user } = ctx.state; 66 | ctx.status = 200; 67 | ctx.body = { 68 | code: 0, 69 | data: user, 70 | }; 71 | } 72 | 73 | async logout() { 74 | const { ctx } = this; 75 | ctx.status = 200; 76 | ctx.body = { 77 | code: 0, 78 | message: 'Logout success', 79 | }; 80 | } 81 | 82 | async authingAuth() { 83 | const { ctx, app, config } = this; 84 | const { helper } = ctx; 85 | const authingConfig = config.authing; 86 | const { code } = ctx.query; 87 | try { 88 | const authRes = await ctx.curl('https://oauth.authing.cn/oauth/oidc/token', { 89 | // 必须指定 method 90 | method: 'POST', 91 | headers: { 92 | 'Content-Type': 'application/x-www-form-urlencoded', 93 | }, 94 | data: helper.stringify({ 95 | code, 96 | client_id: authingConfig.appId, 97 | client_secret: authingConfig.appSecret, 98 | grant_type: 'authorization_code', 99 | redirect_uri: `${config.deployUrl}authing/auth`, 100 | }), 101 | // 明确告诉 HttpClient 以 JSON 格式处理返回的响应 body 102 | dataType: 'json', 103 | }); 104 | 105 | const { access_token } = authRes.data; 106 | // token 换用户信息 107 | const userInfoRes = await ctx.curl(`https://users.authing.cn/oauth/oidc/user/userinfo?access_token=${access_token}`, { 108 | dataType: 'json', 109 | }); 110 | 111 | const userInfo = userInfoRes.data; 112 | 113 | const username = userInfo.name || userInfo.email || userInfo.phone_number; 114 | const newUser = { 115 | name: username, 116 | avatar: userInfo.picture, 117 | email: userInfo.email, 118 | register_type: 'authing', 119 | phone_number: userInfo.phone_number, 120 | role_id: 2, 121 | }; 122 | const regRes = await this.authingRegister(newUser); 123 | // console.log('regRes', regRes); 124 | const token = app.jwt.sign({ 125 | id: regRes.id, 126 | name: regRes.name, 127 | role: 'editor', 128 | avatar: regRes.avatar, 129 | }, app.config.jwt.secret, { 130 | expiresIn: '1h', 131 | }); 132 | await app.redis.set(`token_${regRes.id}`, token); 133 | 134 | ctx.redirect(`${app.config.authRedirectUrl}?token=${token}`); 135 | } catch (e) { 136 | ctx.body = { 137 | code: 403, 138 | message: 'Authing auth failed', 139 | error: e, 140 | }; 141 | return; 142 | } 143 | } 144 | 145 | // authing user register 146 | async authingRegister(authingUser) { 147 | const { service } = this.ctx; 148 | const user = authingUser; 149 | user.password = ''; 150 | // find same name user 151 | const exist = await service.user.findByName(user.name); 152 | if (!exist) { 153 | return service.user.create(authingUser); 154 | } 155 | return exist; 156 | } 157 | } 158 | 159 | module.exports = HomeController; 160 | -------------------------------------------------------------------------------- /backend/app/controller/post.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { Controller } = require('egg'); 4 | 5 | class PostController extends Controller { 6 | async index() { 7 | const { ctx } = this; 8 | const { query, model, service, helper } = ctx; 9 | const options = { 10 | limit: helper.parseInt(query.limit), 11 | offset: helper.parseInt(query.offset), 12 | include: [{ 13 | model: model.User, 14 | as: 'user', 15 | }], 16 | }; 17 | 18 | const data = await service.post.list(options); 19 | ctx.body = { 20 | code: 0, 21 | data: { 22 | count: data.count, 23 | items: data.rows, 24 | }, 25 | }; 26 | } 27 | 28 | async show() { 29 | const { ctx } = this; 30 | const { params, service, helper } = ctx; 31 | const id = helper.parseInt(params.id); 32 | const post = await service.post.find(id); 33 | ctx.body = { 34 | code: 0, 35 | data: post, 36 | }; 37 | } 38 | 39 | async create() { 40 | const { ctx } = this; 41 | const { service } = ctx; 42 | const body = ctx.request.body; 43 | const post = await service.post.create(body); 44 | ctx.status = 201; 45 | ctx.body = { 46 | code: 0, 47 | data: post, 48 | }; 49 | } 50 | 51 | async update() { 52 | const { ctx } = this; 53 | const { params, service, helper } = ctx; 54 | const body = ctx.request.body; 55 | const id = helper.parseInt(params.id); 56 | const res = await service.post.update({ 57 | id, 58 | updates: body, 59 | }); 60 | ctx.body = { 61 | code: 0, 62 | data: res, 63 | }; 64 | } 65 | 66 | async destroy() { 67 | const { ctx } = this; 68 | const { params, service, helper } = ctx; 69 | const id = helper.parseInt(params.id); 70 | await service.post.destroy(id); 71 | ctx.status = 200; 72 | ctx.body = { 73 | code: 0, 74 | success: true, 75 | }; 76 | } 77 | } 78 | 79 | module.exports = PostController; 80 | -------------------------------------------------------------------------------- /backend/app/controller/role.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { Controller } = require('egg'); 4 | 5 | class RoleController extends Controller { 6 | async index() { 7 | const { ctx } = this; 8 | const { query, service, helper } = ctx; 9 | const options = { 10 | limit: helper.parseInt(query.limit), 11 | offset: helper.parseInt(query.offset), 12 | }; 13 | const data = await service.role.list(options); 14 | ctx.body = { 15 | code: 0, 16 | data: { 17 | count: data.count, 18 | items: data.rows, 19 | }, 20 | }; 21 | } 22 | 23 | async show() { 24 | const { ctx } = this; 25 | const { params, service, helper } = ctx; 26 | const id = helper.parseInt(params.id); 27 | ctx.body = await service.role.find(id); 28 | } 29 | 30 | async create() { 31 | const { ctx } = this; 32 | const { service } = ctx; 33 | const body = ctx.request.body; 34 | const role = await service.role.create(body); 35 | ctx.status = 201; 36 | ctx.body = role; 37 | } 38 | 39 | async update() { 40 | const { ctx } = this; 41 | const { params, service, helper } = ctx; 42 | const body = ctx.request.body; 43 | const id = helper.parseInt(params.id); 44 | ctx.body = await service.role.update({ 45 | id, 46 | updates: body, 47 | }); 48 | } 49 | 50 | async destroy() { 51 | const { ctx } = this; 52 | const { params, service, helper } = ctx; 53 | const id = helper.parseInt(params.id); 54 | await service.role.destroy(id); 55 | ctx.status = 200; 56 | } 57 | } 58 | 59 | module.exports = RoleController; 60 | -------------------------------------------------------------------------------- /backend/app/controller/user.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { Controller } = require('egg'); 4 | 5 | class UserController extends Controller { 6 | async index() { 7 | const { ctx } = this; 8 | const { query, model, service, helper } = ctx; 9 | const options = { 10 | limit: helper.parseInt(query.limit), 11 | offset: helper.parseInt(query.offset), 12 | attributes: [ 'id', 'name', 'age', 'avatar', 'introduction', 'created_at' ], 13 | include: [{ 14 | model: model.Role, 15 | as: 'role', 16 | attributes: [ 'id', 'name' ], 17 | }], 18 | }; 19 | const data = await service.user.list(options); 20 | ctx.body = { 21 | code: 0, 22 | data: { 23 | count: data.count, 24 | items: data.rows, 25 | }, 26 | }; 27 | } 28 | 29 | async show() { 30 | const { ctx } = this; 31 | const { params, service, helper } = ctx; 32 | const id = helper.parseInt(params.id); 33 | ctx.body = await service.user.find(id); 34 | } 35 | 36 | async create() { 37 | const { ctx } = this; 38 | const { service, helper } = ctx; 39 | const body = ctx.request.body; 40 | // should encrypt password 41 | body.password = helper.encryptPwd(body.password); 42 | const user = await service.user.create(body); 43 | ctx.status = 201; 44 | ctx.body = user; 45 | } 46 | 47 | async update() { 48 | const { ctx } = this; 49 | const { params, service, helper } = ctx; 50 | const body = ctx.request.body; 51 | const id = helper.parseInt(params.id); 52 | ctx.body = await service.user.update({ 53 | id, 54 | updates: body, 55 | }); 56 | } 57 | 58 | async destroy() { 59 | const { ctx } = this; 60 | const { params, service, helper } = ctx; 61 | const id = helper.parseInt(params.id); 62 | await service.user.destroy(id); 63 | ctx.status = 200; 64 | } 65 | } 66 | 67 | module.exports = UserController; 68 | -------------------------------------------------------------------------------- /backend/app/extend/helper.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const crypto = require('crypto'); 4 | const qs = require('querystring'); 5 | 6 | module.exports = { 7 | parseInt(string) { 8 | if (typeof string === 'number') return string; 9 | if (!string) return string; 10 | return parseInt(string) || 0; 11 | }, 12 | 13 | /** 14 | * encrypt password 15 | * You should not use md5 in your online project 16 | * @param {string} password password string 17 | */ 18 | encryptPwd(password) { 19 | const md5 = crypto.createHash('md5'); 20 | return md5.update(password).digest('hex'); 21 | }, 22 | 23 | stringify(obj) { 24 | return qs.stringify(obj); 25 | }, 26 | }; 27 | -------------------------------------------------------------------------------- /backend/app/model/post.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports = app => { 4 | const { STRING, INTEGER, DATE, TEXT } = app.Sequelize; 5 | 6 | const Post = app.model.define('post', { 7 | id: { 8 | type: INTEGER, 9 | primaryKey: true, 10 | autoIncrement: true, 11 | }, 12 | title: STRING(128), 13 | content: TEXT, 14 | user_id: INTEGER, 15 | created_at: DATE, 16 | updated_at: DATE, 17 | }); 18 | 19 | Post.associate = function() { 20 | app.model.Post.belongsTo(app.model.User, { as: 'user', foreignKey: 'user_id' }); 21 | }; 22 | 23 | Post.findByIdWithUser = async function(id, userId) { 24 | return await this.findOne({ 25 | where: { id, user_id: userId }, 26 | }); 27 | }; 28 | 29 | return Post; 30 | }; 31 | -------------------------------------------------------------------------------- /backend/app/model/role.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports = app => { 4 | const { STRING, INTEGER, DATE } = app.Sequelize; 5 | 6 | const Role = app.model.define('role', { 7 | id: { type: INTEGER, primaryKey: true, autoIncrement: true }, 8 | name: STRING(30), 9 | created_at: DATE, 10 | updated_at: DATE, 11 | }); 12 | 13 | Role.associate = () => { 14 | app.model.Role.hasMany(app.model.User, { as: 'users' }); 15 | }; 16 | 17 | return Role; 18 | }; 19 | -------------------------------------------------------------------------------- /backend/app/model/user.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports = app => { 4 | const { STRING, INTEGER, DATE, TEXT } = app.Sequelize; 5 | 6 | const User = app.model.define('user', { 7 | id: { type: INTEGER, primaryKey: true, autoIncrement: true }, 8 | name: STRING(30), 9 | password: STRING(64), 10 | age: INTEGER, 11 | email: STRING(64), 12 | phone_number: STRING(64), 13 | register_type: { 14 | type: STRING(16), 15 | default: 'default', 16 | }, 17 | avatar: { 18 | type: STRING(128), 19 | allowNull: true, 20 | }, 21 | introduction: { 22 | type: TEXT, 23 | allowNull: true, 24 | }, 25 | created_at: DATE, 26 | updated_at: DATE, 27 | }); 28 | 29 | User.associate = () => { 30 | app.model.User.belongsTo(app.model.Role, { as: 'role', foreignKey: 'role_id' }); 31 | }; 32 | 33 | return User; 34 | }; 35 | -------------------------------------------------------------------------------- /backend/app/router.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const koajwt = require('koa-jwt2'); 4 | 5 | /** 6 | * @param {Egg.Application} app - egg application 7 | */ 8 | module.exports = app => { 9 | const { router, controller, jwt } = app; 10 | router.get('/', controller.home.index); 11 | 12 | router.get('/get-config', controller.home.getAppConfig); 13 | router.post('/login', controller.home.login); 14 | router.get('/user-info', jwt, controller.home.userInfo); 15 | const isRevokedAsync = function(req, payload) { 16 | return new Promise(resolve => { 17 | try { 18 | const userId = payload.id; 19 | const tokenKey = `token_${userId}`; 20 | const token = app.redis.get(tokenKey); 21 | if (token) { 22 | app.redis.del(tokenKey); 23 | } 24 | resolve(false); 25 | } catch (e) { 26 | resolve(true); 27 | } 28 | 29 | }); 30 | }; 31 | router.post('/logout', koajwt({ 32 | secret: app.config.jwt.secret, 33 | credentialsRequired: false, 34 | isRevoked: isRevokedAsync, 35 | }), controller.home.logout); 36 | 37 | router.get('/authing/auth', controller.home.authingAuth); 38 | 39 | 40 | router.resources('roles', '/roles', controller.role); 41 | router.resources('users', '/users', controller.user); 42 | router.resources('posts', '/posts', controller.post); 43 | }; 44 | -------------------------------------------------------------------------------- /backend/app/service/post.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { Service } = require('egg'); 4 | 5 | class PostService extends Service { 6 | async list(options) { 7 | const { ctx: { model } } = this; 8 | const opt = { 9 | ...options, 10 | order: [[ 'created_at', 'desc' ], [ 'id', 'desc' ]], 11 | }; 12 | if (opt.user_id) { 13 | opt.where = { 14 | user_id: opt.user_id, 15 | }; 16 | } 17 | return model.Post.findAndCountAll(opt); 18 | } 19 | 20 | async find(id) { 21 | const { ctx: { model } } = this; 22 | const post = await model.Post.findByPk(id, { 23 | include: [{ 24 | model: model.User, 25 | as: 'user', 26 | attributes: [ 'id', 'name', 'age', 'avatar' ], 27 | }], 28 | }); 29 | if (!post) { 30 | this.ctx.throw(404, 'post not found'); 31 | } 32 | return post; 33 | } 34 | 35 | async create(post) { 36 | const { ctx: { model } } = this; 37 | return model.Post.create(post); 38 | } 39 | 40 | async update({ id, user_id, updates }) { 41 | const { ctx: { model } } = this; 42 | const post = await model.Post.findByIdWithUser(id, user_id); 43 | if (!post) this.ctx.throw(404, 'post not found'); 44 | return post.update(updates); 45 | } 46 | 47 | async destroy(id) { 48 | const { ctx: { model } } = this; 49 | const post = await model.Post.findByPk(id); 50 | if (!post) this.ctx.throw(404, 'post not found'); 51 | return post.destroy(); 52 | } 53 | } 54 | 55 | module.exports = PostService; 56 | -------------------------------------------------------------------------------- /backend/app/service/role.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { Service } = require('egg'); 4 | 5 | class RoleService extends Service { 6 | async list(options) { 7 | const { ctx: { model } } = this; 8 | return model.Role.findAndCountAll({ 9 | ...options, 10 | order: [[ 'created_at', 'desc' ], [ 'id', 'desc' ]], 11 | }); 12 | } 13 | 14 | async find(id) { 15 | const { ctx: { model } } = this; 16 | const role = await model.Role.findByPk(id); 17 | if (!role) { 18 | this.ctx.throw(404, 'role not found'); 19 | } 20 | return role; 21 | } 22 | 23 | async create(role) { 24 | const { ctx: { model } } = this; 25 | return model.Role.create(role); 26 | } 27 | 28 | async update({ id, updates }) { 29 | const role = await this.ctx.model.Role.findByPk(id); 30 | if (!role) { 31 | this.ctx.throw(404, 'role not found'); 32 | } 33 | return role.update(updates); 34 | } 35 | 36 | async destroy(id) { 37 | const role = await this.ctx.model.Role.findByPk(id); 38 | if (!role) { 39 | this.ctx.throw(404, 'role not found'); 40 | } 41 | return role.destroy(); 42 | } 43 | } 44 | 45 | module.exports = RoleService; 46 | -------------------------------------------------------------------------------- /backend/app/service/user.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { Service } = require('egg'); 4 | 5 | 6 | class UserService extends Service { 7 | async list(options) { 8 | const { ctx: { model } } = this; 9 | return model.User.findAndCountAll({ 10 | ...options, 11 | order: [[ 'created_at', 'desc' ], [ 'id', 'desc' ]], 12 | }); 13 | } 14 | 15 | async find(id) { 16 | const { ctx: { model } } = this; 17 | const user = await model.User.findByPk(id, { 18 | include: [{ 19 | model: model.Role, 20 | as: 'role', 21 | attributes: [ 'id', 'name' ], 22 | }], 23 | }); 24 | if (!user) { 25 | this.ctx.throw(404, 'user not found'); 26 | } 27 | return user; 28 | } 29 | 30 | async findByName(name) { 31 | const { ctx: { model } } = this; 32 | const user = await model.User.findOne({ 33 | where: { 34 | name, 35 | }, 36 | include: [{ 37 | model: model.Role, 38 | as: 'role', 39 | attributes: [ 'id', 'name' ], 40 | }], 41 | }); 42 | return user; 43 | } 44 | 45 | async create(user) { 46 | const { ctx: { model } } = this; 47 | return model.User.create(user); 48 | } 49 | 50 | async update({ id, updates }) { 51 | const user = await this.ctx.model.User.findByPk(id); 52 | if (!user) { 53 | this.ctx.throw(404, 'user not found'); 54 | } 55 | return user.update(updates); 56 | } 57 | 58 | async destroy(id) { 59 | const user = await this.ctx.model.User.findByPk(id); 60 | if (!user) { 61 | this.ctx.throw(404, 'user not found'); 62 | } 63 | return user.destroy(); 64 | } 65 | } 66 | 67 | module.exports = UserService; 68 | -------------------------------------------------------------------------------- /backend/appveyor.yml: -------------------------------------------------------------------------------- 1 | environment: 2 | matrix: 3 | - nodejs_version: '10' 4 | 5 | install: 6 | - ps: Install-Product node $env:nodejs_version 7 | - npm i npminstall && node_modules\.bin\npminstall 8 | 9 | test_script: 10 | - node --version 11 | - npm --version 12 | - npm run test 13 | 14 | build: off 15 | -------------------------------------------------------------------------------- /backend/config/config.default.js: -------------------------------------------------------------------------------- 1 | /* eslint valid-jsdoc: "off" */ 2 | 3 | 'use strict'; 4 | 5 | const isLocal = process.env.EGG_SERVER_ENV === 'local'; 6 | if (!isLocal) { 7 | require('dotenv').config(); 8 | } 9 | 10 | /** 11 | * @param {Egg.EggAppInfo} appInfo app info 12 | */ 13 | module.exports = appInfo => { 14 | /** 15 | * built-in config 16 | * @type {Egg.EggAppConfig} 17 | **/ 18 | const config = exports = { 19 | env: 'prod', // 推荐云函数的 egg 运行环境变量修改为 prod 20 | rundir: '/tmp', 21 | logger: { 22 | dir: '/tmp', 23 | }, 24 | }; 25 | 26 | // use for cookie sign key, should change to your own and keep security 27 | config.keys = appInfo.name + '_1580783791359_8688'; 28 | 29 | // add your middleware config here 30 | config.middleware = []; 31 | 32 | // add your user config here 33 | const userConfig = { 34 | // TODO: should change to deploy url. 35 | deployUrl: 'https://service-duvw8ocm-1251556596.gz.apigw.tencentcs.com/release/', 36 | authRedirectUrl: 'https://sls-admin.yugasun.com/#/login', 37 | sequelize: { 38 | sync: true, // whether sync when app init 39 | dialect: 'postgres', 40 | host: process.env.DB_HOST, 41 | port: process.env.DB_PORT, 42 | database: process.env.DB_NAME, 43 | username: process.env.DB_USER, 44 | password: process.env.DB_PASSWORD, 45 | }, 46 | redis: { 47 | client: { 48 | port: process.env.REDIS_PORT, 49 | host: process.env.REDIS_HOST, 50 | password: process.env.REDIS_PASSWORD, 51 | db: 0, 52 | }, 53 | }, 54 | security: { 55 | csrf: { 56 | enable: false, 57 | }, 58 | }, 59 | cors: { 60 | origin: '*', 61 | allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH', 62 | }, 63 | jwt: { 64 | secret: process.env.AUTHING_APPSECRET, 65 | }, 66 | authing: { 67 | appId: process.env.AUTHING_APPID, 68 | appSecret: process.env.AUTHING_APPSECRET, 69 | }, 70 | }; 71 | 72 | return { 73 | ...config, 74 | ...userConfig, 75 | }; 76 | }; 77 | -------------------------------------------------------------------------------- /backend/config/config.local.js: -------------------------------------------------------------------------------- 1 | /* eslint valid-jsdoc: "off" */ 2 | 3 | 'use strict'; 4 | 5 | const path = require('path'); 6 | 7 | const isLocal = process.env.EGG_SERVER_ENV === 'local'; 8 | if (isLocal) { 9 | require('dotenv').config({ 10 | path: path.join(__dirname, '..', '.env.local'), 11 | }); 12 | } 13 | 14 | /** 15 | * @param {Egg.EggAppInfo} appInfo app info 16 | */ 17 | module.exports = appInfo => { 18 | /** 19 | * built-in config 20 | * @type {Egg.EggAppConfig} 21 | **/ 22 | const config = exports = {}; 23 | 24 | // use for cookie sign key, should change to your own and keep security 25 | config.keys = appInfo.name + '_1580783791359_8688'; 26 | 27 | // add your middleware config here 28 | config.middleware = []; 29 | 30 | // add your user config here 31 | const userConfig = { 32 | // myAppName: 'egg', 33 | deployUrl: 'http://127.0.0.1:7001/', 34 | authRedirectUrl: 'http://localhost:9528/#/login', 35 | sequelize: { 36 | sync: true, // whether sync when app init 37 | dialect: 'postgres', 38 | host: process.env.DB_HOST, 39 | port: process.env.DB_PORT, 40 | database: process.env.DB_NAME, 41 | username: process.env.DB_USER, 42 | password: process.env.DB_PASSWORD, 43 | }, 44 | redis: { 45 | client: { 46 | port: process.env.REDIS_PORT, 47 | host: process.env.REDIS_HOST, 48 | password: process.env.REDIS_PASSWORD, 49 | db: 0, 50 | }, 51 | }, 52 | security: { 53 | csrf: { 54 | enable: false, 55 | }, 56 | }, 57 | cors: { 58 | origin: '*', 59 | allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH', 60 | }, 61 | authing: { 62 | appId: process.env.AUTHING_APPID, 63 | appSecret: process.env.AUTHING_APPSECRET, 64 | }, 65 | jwt: { 66 | secret: '123456', 67 | }, 68 | }; 69 | 70 | return { 71 | ...config, 72 | ...userConfig, 73 | }; 74 | }; 75 | -------------------------------------------------------------------------------- /backend/config/plugin.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** @type Egg.EggPlugin */ 4 | module.exports = { 5 | // had enabled by egg 6 | static: { 7 | enable: false, 8 | }, 9 | sequelize: { 10 | enable: true, 11 | package: 'egg-sequelize', 12 | }, 13 | redis: { 14 | enable: true, 15 | package: 'egg-redis', 16 | }, 17 | jwt: { 18 | enable: true, 19 | package: 'egg-jwt', 20 | }, 21 | cors: { 22 | enable: true, 23 | package: 'egg-cors', 24 | }, 25 | }; 26 | -------------------------------------------------------------------------------- /backend/database/config.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports = { 4 | production: { 5 | // TODO: 修改为部署 serverless postgresql 的 public 配置 6 | host: 'postgres-xxx.sql.tencentcdb.com', 7 | post: 5432, 8 | username: 'tencentdb_xxx', 9 | password: 'xxx', 10 | database: 'tencentdb_xxx', 11 | dialect: 'postgres', 12 | }, 13 | test: { 14 | username: 'root', 15 | password: 'root', 16 | database: 'admin-system', 17 | host: '127.0.0.1', 18 | post: 5432, 19 | dialect: 'postgres', 20 | }, 21 | }; 22 | -------------------------------------------------------------------------------- /backend/database/db.sql: -------------------------------------------------------------------------------- 1 | DROP TABLE IF EXISTS `roles`; 2 | CREATE TABLE IF NOT EXIST `roles` ( 3 | `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'primary key', 4 | `name` varchar(30) DEFAULT NULL, 5 | `created_at` datetime DEFAULT NULL, 6 | `updated_at` datetime DEFAULT NULL, 7 | PRIMARY KEY (`id`) 8 | ) ENGINE=InnoDB; 9 | 10 | DROP TABLE IF EXISTS `users`; 11 | CREATE TABLE `users` ( 12 | `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'primary key', 13 | `name` varchar(30) DEFAULT NULL, 14 | `password` varchar(64) DEFAULT NULL, 15 | `age` int DEFAULT NULL, 16 | `avatar` varchar(128) DEFAULT NULL, 17 | `introduction` text, 18 | `created_at` datetime DEFAULT NULL, 19 | `updated_at` datetime DEFAULT NULL, 20 | `role_id` int DEFAULT NULL, 21 | PRIMARY KEY (`id`), 22 | KEY `users_role_id_foreign_idx` (`role_id`), 23 | CONSTRAINT `users_role_id_foreign_idx` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`) ON DELETE SET NULL ON UPDATE CASCADE 24 | ) ENGINE=InnoDB; 25 | 26 | DROP TABLE IF EXISTS `posts`; 27 | CREATE TABLE `posts` ( 28 | `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'primary key', 29 | `title` varchar(30) DEFAULT NULL, 30 | `content` varchar(255) DEFAULT NULL, 31 | `created_at` datetime DEFAULT NULL, 32 | `updated_at` datetime DEFAULT NULL, 33 | `user_id` int DEFAULT NULL, 34 | PRIMARY KEY (`id`), 35 | KEY `posts_user_id_foreign_idx` (`user_id`), 36 | CONSTRAINT `posts_user_id_foreign_idx` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE 37 | ) ENGINE=InnoDB; 38 | 39 | 40 | -- TRUNCATE `roles`; 41 | -- INSERT INTO `roles` (`id`, `name`, `created_at`, `updated_at`) VALUES 42 | -- (1, 'admin', '2020-02-04 09:54:25', '2020-02-04 09:54:25'), 43 | -- (2, 'editor', '2020-02-04 09:54:30', '2020-02-04 09:54:30'); 44 | 45 | -- TRUNCATE `users`; 46 | -- INSERT INTO `users` (`id`, `name`, `password`, `age`, `avatar`, `introduction`, `created_at`, `updated_at`, `role_id`) VALUES 47 | -- (1, 'admin', 'e10adc3949ba59abbe56e057f20f883e', 20, 'https://yugasun.com/static/avatar.jpg', 'Fullstack Engineer', '2020-02-04 09:55:23', '2020-02-04 09:55:23', 1); 48 | 49 | -- TRUNCATE `posts`; 50 | -- INSERT INTO `posts` (`id`, `title`, `content`, `created_at`, `updated_at`, `user_id`) VALUES 51 | -- (2, 'Awesome Egg.js', 'Egg.js is a awesome framework', '2020-02-04 09:57:24', '2020-02-04 09:57:24', 1), 52 | -- (3, 'Awesome Serverless', 'Build web, mobile and IoT applications using Tencent Cloud and API Gateway, Tencent Cloud Functions, and more.', '2020-02-04 10:00:23', '2020-02-04 10:00:23', 1); 53 | 54 | -- 2020-02-05 08:10:33 55 | -------------------------------------------------------------------------------- /backend/database/migrations/20200204074424-init-user.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports = { 4 | // The function called when performing a database upgrade, create a `users` table 5 | up: async (queryInterface, Sequelize) => { 6 | const { INTEGER, DATE, STRING, TEXT } = Sequelize; 7 | await queryInterface.createTable('users', { 8 | id: { type: INTEGER, primaryKey: true, autoIncrement: true }, 9 | name: STRING(30), 10 | password: STRING(64), 11 | age: INTEGER, 12 | avatar: { 13 | type: STRING(128), 14 | allowNull: true, 15 | }, 16 | introduction: { 17 | type: TEXT, 18 | allowNull: true, 19 | }, 20 | created_at: DATE, 21 | updated_at: DATE, 22 | }); 23 | }, 24 | // The function called when performing a database downgrade, delete the `users` table 25 | down: async queryInterface => { 26 | await queryInterface.dropTable('users'); 27 | }, 28 | }; 29 | -------------------------------------------------------------------------------- /backend/database/migrations/20200204074427-init-role.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports = { 4 | // The function called when performing a database upgrade, create a `users` table 5 | up: async (queryInterface, Sequelize) => { 6 | const { INTEGER, DATE, STRING } = Sequelize; 7 | await queryInterface.createTable('roles', { 8 | id: { type: INTEGER, primaryKey: true, autoIncrement: true }, 9 | name: STRING(30), 10 | created_at: DATE, 11 | updated_at: DATE, 12 | }); 13 | }, 14 | // The function called when performing a database downgrade, delete the `users` table 15 | down: async queryInterface => { 16 | await queryInterface.dropTable('roles'); 17 | }, 18 | }; 19 | -------------------------------------------------------------------------------- /backend/database/migrations/20200204074431-init-post.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports = { 4 | // The function called when performing a database upgrade, create a `posts` table 5 | up: async (queryInterface, Sequelize) => { 6 | const { INTEGER, DATE, STRING } = Sequelize; 7 | await queryInterface.createTable('posts', { 8 | id: { 9 | type: INTEGER, 10 | primaryKey: true, 11 | autoIncrement: true, 12 | }, 13 | title: STRING(30), 14 | content: STRING(255), 15 | created_at: DATE, 16 | updated_at: DATE, 17 | }); 18 | }, 19 | // The function called when performing a database downgrade, delete the `posts` table 20 | down: async queryInterface => { 21 | await queryInterface.dropTable('posts'); 22 | }, 23 | }; 24 | -------------------------------------------------------------------------------- /backend/database/migrations/20200204074502-add-associations.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports = { 4 | up: async (queryInterface, Sequelize) => { 5 | const { INTEGER } = Sequelize; 6 | await queryInterface.addColumn( 7 | 'users', // name of Source model 8 | 'role_id', // name of the key we're adding 9 | { 10 | type: INTEGER, 11 | references: { 12 | model: 'roles', // name of Target model 13 | key: 'id', // key in Target model that we're referencing 14 | }, 15 | onUpdate: 'CASCADE', 16 | onDelete: 'SET NULL', 17 | } 18 | ); 19 | await queryInterface.addColumn( 20 | 'posts', // name of Source model 21 | 'user_id', // name of the key we're adding 22 | { 23 | type: INTEGER, 24 | references: { 25 | model: 'users', // name of Target model 26 | key: 'id', // key in Target model that we're referencing 27 | }, 28 | onUpdate: 'CASCADE', 29 | onDelete: 'SET NULL', 30 | } 31 | ); 32 | }, 33 | 34 | down: async queryInterface => { 35 | await queryInterface.removeColumn( 36 | 'posts', // name of Source model 37 | 'user_id' // key we want to remove 38 | ); 39 | await queryInterface.removeColumn( 40 | 'users', // name of Source model 41 | 'role_id' // key we want to remove 42 | ); 43 | }, 44 | }; 45 | -------------------------------------------------------------------------------- /backend/docker-compose.yml: -------------------------------------------------------------------------------- 1 | # Use root/example as user/password credentials 2 | version: '3.1' 3 | 4 | services: 5 | db: 6 | image: postgres 7 | restart: always 8 | ports: 9 | - 5432:5432 10 | environment: 11 | POSTGRES_DB: admin-system 12 | POSTGRES_USER: root 13 | POSTGRES_PASSWORD: root 14 | 15 | adminer: 16 | image: adminer 17 | restart: always 18 | ports: 19 | - 8080:8080 20 | 21 | redis: 22 | image: redis 23 | restart: always 24 | ports: 25 | - 6379:6379 26 | -------------------------------------------------------------------------------- /backend/jsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": [ 3 | "**/*" 4 | ] 5 | } -------------------------------------------------------------------------------- /backend/layer/serverless.yml: -------------------------------------------------------------------------------- 1 | org: slsplus 2 | app: admin-system 3 | stage: dev 4 | 5 | component: layer 6 | name: admin-system-backend-layer 7 | 8 | inputs: 9 | region: ${env:REGION} 10 | name: ${name} 11 | src: 12 | src: ../node_modules 13 | targetDir: node_modules 14 | runtimes: 15 | - Nodejs10.15 16 | - Nodejs12.16 17 | -------------------------------------------------------------------------------- /backend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "admin-system", 3 | "version": "1.0.0", 4 | "description": "", 5 | "private": true, 6 | "egg": { 7 | "declarations": true 8 | }, 9 | "dependencies": { 10 | "dotenv": "^8.2.0", 11 | "egg": "^2.15.1", 12 | "egg-cors": "^2.2.3", 13 | "egg-jwt": "^3.1.7", 14 | "egg-redis": "^2.4.0", 15 | "egg-scripts": "^2.11.0", 16 | "egg-sequelize": "^5.2.1", 17 | "koa-jwt2": "^1.0.3", 18 | "pg": "^8.3.3", 19 | "querystring": "^0.2.0" 20 | }, 21 | "devDependencies": { 22 | "autod": "^3.0.1", 23 | "autod-egg": "^1.1.0", 24 | "egg-bin": "^4.11.0", 25 | "egg-ci": "^1.11.0", 26 | "egg-mock": "^3.21.0", 27 | "eslint": "^5.13.0", 28 | "eslint-config-egg": "^7.1.0", 29 | "factory-girl": "^5.0.4", 30 | "sequelize-cli": "^5.5.1" 31 | }, 32 | "engines": { 33 | "node": ">=10.0.0" 34 | }, 35 | "scripts": { 36 | "docker:up": "docker-compose up -d", 37 | "dev": "EGG_SERVER_ENV=local NODE_ENV=development egg-bin dev", 38 | "debug": "egg-bin debug", 39 | "lint": "eslint .", 40 | "db:migrate": "NODE_ENV=production sequelize db:migrate --config database/config.js", 41 | "db:migrate:undo": "NODE_ENV=production sequelize db:migrate:undo:all --config database/config.js", 42 | "db:migrate:test": "NODE_ENV=test sequelize db:migrate --config database/config.js", 43 | "db:migrate:test:undo": "NODE_ENV=test sequelize db:migrate:undo:all --config database/config.js" 44 | }, 45 | "ci": { 46 | "version": "10" 47 | }, 48 | "repository": { 49 | "type": "git", 50 | "url": "" 51 | }, 52 | "author": "yugasun", 53 | "license": "MIT" 54 | } 55 | -------------------------------------------------------------------------------- /backend/serverless.yml: -------------------------------------------------------------------------------- 1 | org: slsplus 2 | app: admin-system 3 | stage: dev 4 | 5 | component: egg 6 | name: admin-system-backend 7 | 8 | inputs: 9 | region: ${env:REGION} 10 | src: 11 | src: ./ 12 | exclude: 13 | - '.git/**' 14 | - 'docs/**' 15 | - 'test/**' 16 | - 'node_modules/**' 17 | functionName: serverless-admin-system 18 | runtime: Nodejs10.15 19 | layers: 20 | - name: ${output:${stage}:${app}:${name}-layer.name} 21 | version: ${output:${stage}:${app}:${name}-layer.version} 22 | functionConf: 23 | timeout: 120 24 | vpcConfig: 25 | vpcId: ${output:${stage}:${app}:${app}-vpc.vpcId} 26 | subnetId: ${output:${stage}:${app}:${app}-vpc.subnetId} 27 | environment: 28 | variables: 29 | NODE_ENV: production 30 | SERVERLESS: true 31 | DB_HOST: ${output:${stage}:${app}:${app}-db.private.host} 32 | DB_PORT: ${output:${stage}:${app}:${app}-db.private.port} 33 | DB_NAME: ${output:${stage}:${app}:${app}-db.private.dbname} 34 | DB_USER: ${output:${stage}:${app}:${app}-db.private.user} 35 | DB_PASSWORD: ${output:${stage}:${app}:${app}-db.private.password} 36 | apigatewayConf: 37 | environment: release 38 | protocols: 39 | - https 40 | -------------------------------------------------------------------------------- /backend/sls.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { Application } = require('egg'); 4 | 5 | Object.defineProperty(Application.prototype, Symbol.for('egg#eggPath'), { 6 | value: '/opt', 7 | }); 8 | 9 | const app = new Application({ 10 | env: 'prod', 11 | mode: 'single', 12 | }); 13 | 14 | app.binaryTypes = [ '*/*' ]; 15 | 16 | module.exports = app; 17 | -------------------------------------------------------------------------------- /backend/test/.setup.js: -------------------------------------------------------------------------------- 1 | const { app } = require('egg-mock/bootstrap'); 2 | const factories = require('./factories'); 3 | 4 | before(() => factories(app)); 5 | afterEach(async () => { 6 | // clear database after each test case 7 | await Promise.all([ 8 | // app.model.Post.destroy({ truncate: true, force: true, cascade: true }), 9 | // app.model.User.destroy({ truncate: true, force: true, cascade: true }), 10 | // app.model.Role.destroy({ truncate: true, force: true, cascade: true }), 11 | ]); 12 | }); -------------------------------------------------------------------------------- /backend/test/app/controller/home.test.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { app, assert } = require('egg-mock/bootstrap'); 4 | 5 | describe('test/app/controller/home.test.js', () => { 6 | it('should assert', () => { 7 | const pkg = require('../../../package.json.js'); 8 | assert(app.config.keys.startsWith(pkg.name)); 9 | 10 | // const ctx = app.mockContext({}); 11 | // yield ctx.service.xx(); 12 | }); 13 | 14 | it('should GET /', () => { 15 | return app.httpRequest() 16 | .get('/') 17 | .expect('hi, egg') 18 | .expect(200); 19 | }); 20 | }); 21 | -------------------------------------------------------------------------------- /backend/test/app/controller/post.test.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const { assert, app } = require('egg-mock/bootstrap'); 3 | 4 | 5 | describe('test/app/controller/post.test.js', () => { 6 | describe('GET /posts', () => { 7 | it('should work', async () => { 8 | // Quickly create some posts object into the database via factory-girl 9 | await app.factory.createMany('post', 3); 10 | const res = await app.httpRequest().get('/posts?limit=2'); 11 | assert(res.status === 200); 12 | const { rows } = res.body; 13 | assert(rows.length === 2); 14 | assert(rows[0].title); 15 | assert(rows[0].content); 16 | }); 17 | }); 18 | 19 | describe('GET /posts/:id', () => { 20 | it('should work', async () => { 21 | const post = await app.factory.create('post'); 22 | const res = await app.httpRequest().get(`/posts/${post.id}`); 23 | assert(res.status === 200); 24 | assert(res.body.age === post.age); 25 | }); 26 | }); 27 | 28 | describe('POST /posts', () => { 29 | it('should work', async () => { 30 | app.mockCsrf(); 31 | let res = await app.httpRequest().post('/posts') 32 | .send({ 33 | title: 'title', 34 | content: 'content', 35 | }); 36 | assert(res.status === 201); 37 | assert(res.body.id); 38 | 39 | res = await app.httpRequest().get(`/posts/${res.body.id}`); 40 | assert(res.status === 200); 41 | assert(res.body.title === 'title'); 42 | }); 43 | }); 44 | 45 | describe('DELETE /posts/:id', () => { 46 | it('should work', async () => { 47 | const post = await app.factory.create('post'); 48 | 49 | app.mockCsrf(); 50 | const res = await app.httpRequest().delete(`/posts/${post.id}`); 51 | assert(res.status === 200); 52 | }); 53 | }); 54 | }); 55 | -------------------------------------------------------------------------------- /backend/test/app/controller/role.test.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const { assert, app } = require('egg-mock/bootstrap'); 3 | 4 | 5 | describe('test/app/controller/role.test.js', () => { 6 | describe('GET /roles', () => { 7 | it('should work', async () => { 8 | // Quickly create some roles object into the database via factory-girl 9 | await app.factory.createMany('role', 3); 10 | const res = await app.httpRequest().get('/roles?limit=2'); 11 | assert(res.status === 200); 12 | const { rows } = res.body; 13 | assert(rows.length === 2); 14 | assert(rows[0].name); 15 | }); 16 | }); 17 | 18 | describe('GET /roles/:id', () => { 19 | it('should work', async () => { 20 | const role = await app.factory.create('role'); 21 | const res = await app.httpRequest().get(`/roles/${role.id}`); 22 | assert(res.status === 200); 23 | assert(res.body.name === role.name); 24 | }); 25 | }); 26 | 27 | describe('POST /roles', () => { 28 | it('should work', async () => { 29 | app.mockCsrf(); 30 | let res = await app.httpRequest().post('/roles') 31 | .send({ 32 | name: 'name', 33 | }); 34 | assert(res.status === 201); 35 | assert(res.body.id); 36 | 37 | res = await app.httpRequest().get(`/roles/${res.body.id}`); 38 | assert(res.status === 200); 39 | assert(res.body.name === 'name'); 40 | }); 41 | }); 42 | 43 | describe('DELETE /roles/:id', () => { 44 | it('should work', async () => { 45 | const role = await app.factory.create('role'); 46 | 47 | app.mockCsrf(); 48 | const res = await app.httpRequest().delete(`/roles/${role.id}`); 49 | assert(res.status === 200); 50 | }); 51 | }); 52 | }); 53 | -------------------------------------------------------------------------------- /backend/test/app/controller/user.test.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const { assert, app } = require('egg-mock/bootstrap'); 3 | 4 | 5 | describe('test/app/controller/user.test.js', () => { 6 | describe('GET /users', () => { 7 | it('should work', async () => { 8 | // Quickly create some users object into the database via factory-girl 9 | await app.factory.createMany('user', 3); 10 | const res = await app.httpRequest().get('/users?limit=2'); 11 | assert(res.status === 200); 12 | const { rows } = res.body; 13 | assert(rows.length === 2); 14 | assert(rows[0].name); 15 | assert(rows[0].age); 16 | }); 17 | }); 18 | 19 | describe('GET /users/:id', () => { 20 | it('should work', async () => { 21 | const user = await app.factory.create('user'); 22 | const res = await app.httpRequest().get(`/users/${user.id}`); 23 | assert(res.status === 200); 24 | assert(res.body.age === user.age); 25 | }); 26 | }); 27 | 28 | describe('POST /users', () => { 29 | it('should work', async () => { 30 | app.mockCsrf(); 31 | let res = await app.httpRequest().post('/users') 32 | .send({ 33 | age: 10, 34 | name: 'name', 35 | }); 36 | assert(res.status === 201); 37 | assert(res.body.id); 38 | 39 | res = await app.httpRequest().get(`/users/${res.body.id}`); 40 | assert(res.status === 200); 41 | assert(res.body.name === 'name'); 42 | }); 43 | }); 44 | 45 | describe('DELETE /users/:id', () => { 46 | it('should work', async () => { 47 | const user = await app.factory.create('user'); 48 | 49 | app.mockCsrf(); 50 | const res = await app.httpRequest().delete(`/users/${user.id}`); 51 | assert(res.status === 200); 52 | }); 53 | }); 54 | }); 55 | -------------------------------------------------------------------------------- /backend/test/factories.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { factory } = require('factory-girl'); 4 | 5 | module.exports = app => { 6 | // Factory instance can be accessed via app.factory 7 | app.factory = factory; 8 | 9 | 10 | // Define user and default data 11 | factory.define('role', app.model.Role, { 12 | name: factory.sequence('Role.name', n => `name_${n}`), 13 | }); 14 | 15 | factory.define('user', app.model.User, { 16 | name: factory.sequence('User.name', n => `name_${n}`), 17 | age: 18, 18 | avatar: 'https://yugasun.com/static/avatar.jpg', 19 | introduction: 'Fullstack Engineer', 20 | role_id: factory.assoc('role', 'id'), 21 | }); 22 | 23 | factory.define('post', app.model.Post, { 24 | title: factory.sequence('Post.title', n => `title_${n}`), 25 | content: 'Awesome egg', 26 | user_id: factory.assoc('user', 'id'), 27 | }); 28 | }; 29 | -------------------------------------------------------------------------------- /backend/typings/app/controller/index.d.ts: -------------------------------------------------------------------------------- 1 | // This file is created by egg-ts-helper@1.25.6 2 | // Do not modify this file!!!!!!!!! 3 | 4 | import 'egg'; 5 | import ExportHome = require('../../../app/controller/home'); 6 | import ExportPost = require('../../../app/controller/post'); 7 | import ExportRole = require('../../../app/controller/role'); 8 | import ExportUser = require('../../../app/controller/user'); 9 | 10 | declare module 'egg' { 11 | interface IController { 12 | home: ExportHome; 13 | post: ExportPost; 14 | role: ExportRole; 15 | user: ExportUser; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /backend/typings/app/extend/helper.d.ts: -------------------------------------------------------------------------------- 1 | // This file is created by egg-ts-helper@1.25.6 2 | // Do not modify this file!!!!!!!!! 3 | 4 | import 'egg'; 5 | import ExtendIHelper = require('../../../app/extend/helper'); 6 | type ExtendIHelperType = typeof ExtendIHelper; 7 | declare module 'egg' { 8 | interface IHelper extends ExtendIHelperType { } 9 | } -------------------------------------------------------------------------------- /backend/typings/app/index.d.ts: -------------------------------------------------------------------------------- 1 | // This file is created by egg-ts-helper@1.25.6 2 | // Do not modify this file!!!!!!!!! 3 | 4 | import 'egg'; 5 | export * from 'egg'; 6 | export as namespace Egg; 7 | -------------------------------------------------------------------------------- /backend/typings/app/model/index.d.ts: -------------------------------------------------------------------------------- 1 | // This file is created by egg-ts-helper@1.25.6 2 | // Do not modify this file!!!!!!!!! 3 | 4 | import 'egg'; 5 | import ExportPost = require('../../../app/model/post'); 6 | import ExportRole = require('../../../app/model/role'); 7 | import ExportUser = require('../../../app/model/user'); 8 | 9 | declare module 'egg' { 10 | interface IModel { 11 | Post: ReturnType; 12 | Role: ReturnType; 13 | User: ReturnType; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /backend/typings/app/service/index.d.ts: -------------------------------------------------------------------------------- 1 | // This file is created by egg-ts-helper@1.25.6 2 | // Do not modify this file!!!!!!!!! 3 | 4 | import 'egg'; 5 | import ExportPost = require('../../../app/service/post'); 6 | import ExportRole = require('../../../app/service/role'); 7 | import ExportUser = require('../../../app/service/user'); 8 | 9 | declare module 'egg' { 10 | interface IService { 11 | post: ExportPost; 12 | role: ExportRole; 13 | user: ExportUser; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /backend/typings/config/index.d.ts: -------------------------------------------------------------------------------- 1 | // This file is created by egg-ts-helper@1.25.6 2 | // Do not modify this file!!!!!!!!! 3 | 4 | import 'egg'; 5 | import { EggAppConfig } from 'egg'; 6 | import ExportConfigDefault = require('../../config/config.default'); 7 | type ConfigDefault = ReturnType; 8 | type NewEggAppConfig = ConfigDefault; 9 | declare module 'egg' { 10 | interface EggAppConfig extends NewEggAppConfig { } 11 | } -------------------------------------------------------------------------------- /backend/typings/config/plugin.d.ts: -------------------------------------------------------------------------------- 1 | // This file is created by egg-ts-helper@1.25.6 2 | // Do not modify this file!!!!!!!!! 3 | 4 | import 'egg'; 5 | import 'egg-onerror'; 6 | import 'egg-session'; 7 | import 'egg-i18n'; 8 | import 'egg-watcher'; 9 | import 'egg-multipart'; 10 | import 'egg-security'; 11 | import 'egg-development'; 12 | import 'egg-logrotator'; 13 | import 'egg-schedule'; 14 | import 'egg-jsonp'; 15 | import 'egg-view'; 16 | import 'egg-sequelize'; 17 | import 'egg-redis'; 18 | import 'egg-jwt'; 19 | import 'egg-cors'; 20 | import { EggPluginItem } from 'egg'; 21 | declare module 'egg' { 22 | interface EggPlugin { 23 | onerror?: EggPluginItem; 24 | session?: EggPluginItem; 25 | i18n?: EggPluginItem; 26 | watcher?: EggPluginItem; 27 | multipart?: EggPluginItem; 28 | security?: EggPluginItem; 29 | development?: EggPluginItem; 30 | logrotator?: EggPluginItem; 31 | schedule?: EggPluginItem; 32 | static?: EggPluginItem; 33 | jsonp?: EggPluginItem; 34 | view?: EggPluginItem; 35 | sequelize?: EggPluginItem; 36 | redis?: EggPluginItem; 37 | jwt?: EggPluginItem; 38 | cors?: EggPluginItem; 39 | } 40 | } -------------------------------------------------------------------------------- /db/serverless.yml: -------------------------------------------------------------------------------- 1 | org: slsplus 2 | app: admin-system 3 | stage: dev 4 | 5 | component: postgresql 6 | name: admin-system-db 7 | 8 | inputs: 9 | region: ${env:REGION} 10 | zone: ${env:ZONE} 11 | dBInstanceName: ${name} 12 | vpcConfig: 13 | vpcId: ${output:${stage}:${app}:${app}-vpc.vpcId} 14 | subnetId: ${output:${stage}:${app}:${app}-vpc.subnetId} 15 | extranetAccess: true 16 | -------------------------------------------------------------------------------- /frontend/.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | end_of_line = lf 9 | insert_final_newline = true 10 | trim_trailing_whitespace = true 11 | 12 | [*.md] 13 | insert_final_newline = false 14 | trim_trailing_whitespace = false 15 | -------------------------------------------------------------------------------- /frontend/.env.development: -------------------------------------------------------------------------------- 1 | # just a flag 2 | ENV = 'development' 3 | 4 | # base api 5 | VUE_APP_BASE_API = 'http://127.0.0.1:7001/' 6 | 7 | # vue-cli uses the VUE_CLI_BABEL_TRANSPILE_MODULES environment variable, 8 | # to control whether the babel-plugin-dynamic-import-node plugin is enabled. 9 | # It only does one thing by converting all import() to require(). 10 | # This configuration can significantly increase the speed of hot updates, 11 | # when you have a large number of pages. 12 | # Detail: https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/babel-preset-app/index.js 13 | 14 | VUE_CLI_BABEL_TRANSPILE_MODULES = true 15 | -------------------------------------------------------------------------------- /frontend/.env.production: -------------------------------------------------------------------------------- 1 | # just a flag 2 | ENV = 'production' 3 | 4 | # base api 5 | VUE_APP_BASE_API = '/prod-api' 6 | 7 | -------------------------------------------------------------------------------- /frontend/.eslintignore: -------------------------------------------------------------------------------- 1 | build/*.js 2 | src/assets 3 | public 4 | dist 5 | -------------------------------------------------------------------------------- /frontend/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | parserOptions: { 4 | parser: 'babel-eslint', 5 | sourceType: 'module' 6 | }, 7 | env: { 8 | browser: true, 9 | node: true, 10 | es6: true, 11 | }, 12 | extends: ['plugin:vue/recommended', 'eslint:recommended'], 13 | 14 | // add your custom rules here 15 | //it is base on https://github.com/vuejs/eslint-config-vue 16 | rules: { 17 | "vue/max-attributes-per-line": [2, { 18 | "singleline": 10, 19 | "multiline": { 20 | "max": 1, 21 | "allowFirstLine": false 22 | } 23 | }], 24 | "vue/singleline-html-element-content-newline": "off", 25 | "vue/multiline-html-element-content-newline":"off", 26 | "vue/name-property-casing": ["error", "PascalCase"], 27 | "vue/no-v-html": "off", 28 | 'accessor-pairs': 2, 29 | 'arrow-spacing': [2, { 30 | 'before': true, 31 | 'after': true 32 | }], 33 | 'block-spacing': [2, 'always'], 34 | 'brace-style': [2, '1tbs', { 35 | 'allowSingleLine': true 36 | }], 37 | 'camelcase': [0, { 38 | 'properties': 'always' 39 | }], 40 | 'comma-dangle': [2, 'never'], 41 | 'comma-spacing': [2, { 42 | 'before': false, 43 | 'after': true 44 | }], 45 | 'comma-style': [2, 'last'], 46 | 'constructor-super': 2, 47 | 'curly': [2, 'multi-line'], 48 | 'dot-location': [2, 'property'], 49 | 'eol-last': 2, 50 | 'eqeqeq': ["error", "always", {"null": "ignore"}], 51 | 'generator-star-spacing': [2, { 52 | 'before': true, 53 | 'after': true 54 | }], 55 | 'handle-callback-err': [2, '^(err|error)$'], 56 | 'indent': [2, 2, { 57 | 'SwitchCase': 1 58 | }], 59 | 'jsx-quotes': [2, 'prefer-single'], 60 | 'key-spacing': [2, { 61 | 'beforeColon': false, 62 | 'afterColon': true 63 | }], 64 | 'keyword-spacing': [2, { 65 | 'before': true, 66 | 'after': true 67 | }], 68 | 'new-cap': [2, { 69 | 'newIsCap': true, 70 | 'capIsNew': false 71 | }], 72 | 'new-parens': 2, 73 | 'no-array-constructor': 2, 74 | 'no-caller': 2, 75 | 'no-console': 'off', 76 | 'no-class-assign': 2, 77 | 'no-cond-assign': 2, 78 | 'no-const-assign': 2, 79 | 'no-control-regex': 0, 80 | 'no-delete-var': 2, 81 | 'no-dupe-args': 2, 82 | 'no-dupe-class-members': 2, 83 | 'no-dupe-keys': 2, 84 | 'no-duplicate-case': 2, 85 | 'no-empty-character-class': 2, 86 | 'no-empty-pattern': 2, 87 | 'no-eval': 2, 88 | 'no-ex-assign': 2, 89 | 'no-extend-native': 2, 90 | 'no-extra-bind': 2, 91 | 'no-extra-boolean-cast': 2, 92 | 'no-extra-parens': [2, 'functions'], 93 | 'no-fallthrough': 2, 94 | 'no-floating-decimal': 2, 95 | 'no-func-assign': 2, 96 | 'no-implied-eval': 2, 97 | 'no-inner-declarations': [2, 'functions'], 98 | 'no-invalid-regexp': 2, 99 | 'no-irregular-whitespace': 2, 100 | 'no-iterator': 2, 101 | 'no-label-var': 2, 102 | 'no-labels': [2, { 103 | 'allowLoop': false, 104 | 'allowSwitch': false 105 | }], 106 | 'no-lone-blocks': 2, 107 | 'no-mixed-spaces-and-tabs': 2, 108 | 'no-multi-spaces': 2, 109 | 'no-multi-str': 2, 110 | 'no-multiple-empty-lines': [2, { 111 | 'max': 1 112 | }], 113 | 'no-native-reassign': 2, 114 | 'no-negated-in-lhs': 2, 115 | 'no-new-object': 2, 116 | 'no-new-require': 2, 117 | 'no-new-symbol': 2, 118 | 'no-new-wrappers': 2, 119 | 'no-obj-calls': 2, 120 | 'no-octal': 2, 121 | 'no-octal-escape': 2, 122 | 'no-path-concat': 2, 123 | 'no-proto': 2, 124 | 'no-redeclare': 2, 125 | 'no-regex-spaces': 2, 126 | 'no-return-assign': [2, 'except-parens'], 127 | 'no-self-assign': 2, 128 | 'no-self-compare': 2, 129 | 'no-sequences': 2, 130 | 'no-shadow-restricted-names': 2, 131 | 'no-spaced-func': 2, 132 | 'no-sparse-arrays': 2, 133 | 'no-this-before-super': 2, 134 | 'no-throw-literal': 2, 135 | 'no-trailing-spaces': 2, 136 | 'no-undef': 2, 137 | 'no-undef-init': 2, 138 | 'no-unexpected-multiline': 2, 139 | 'no-unmodified-loop-condition': 2, 140 | 'no-unneeded-ternary': [2, { 141 | 'defaultAssignment': false 142 | }], 143 | 'no-unreachable': 2, 144 | 'no-unsafe-finally': 2, 145 | 'no-unused-vars': [2, { 146 | 'vars': 'all', 147 | 'args': 'none' 148 | }], 149 | 'no-useless-call': 2, 150 | 'no-useless-computed-key': 2, 151 | 'no-useless-constructor': 2, 152 | 'no-useless-escape': 0, 153 | 'no-whitespace-before-property': 2, 154 | 'no-with': 2, 155 | 'one-var': [2, { 156 | 'initialized': 'never' 157 | }], 158 | 'operator-linebreak': [2, 'after', { 159 | 'overrides': { 160 | '?': 'before', 161 | ':': 'before' 162 | } 163 | }], 164 | 'padded-blocks': [2, 'never'], 165 | 'quotes': [2, 'single', { 166 | 'avoidEscape': true, 167 | 'allowTemplateLiterals': true 168 | }], 169 | 'semi': [2, 'never'], 170 | 'semi-spacing': [2, { 171 | 'before': false, 172 | 'after': true 173 | }], 174 | 'space-before-blocks': [2, 'always'], 175 | 'space-before-function-paren': [2, 'never'], 176 | 'space-in-parens': [2, 'never'], 177 | 'space-infix-ops': 2, 178 | 'space-unary-ops': [2, { 179 | 'words': true, 180 | 'nonwords': false 181 | }], 182 | 'spaced-comment': [2, 'always', { 183 | 'markers': ['global', 'globals', 'eslint', 'eslint-disable', '*package', '!', ','] 184 | }], 185 | 'template-curly-spacing': [2, 'never'], 186 | 'use-isnan': 2, 187 | 'valid-typeof': 2, 188 | 'wrap-iife': [2, 'any'], 189 | 'yield-star-spacing': [2, 'both'], 190 | 'yoda': [2, 'never'], 191 | 'prefer-const': 2, 192 | 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0, 193 | 'object-curly-spacing': [2, 'always', { 194 | objectsInObjects: false 195 | }], 196 | 'array-bracket-spacing': [2, 'never'] 197 | } 198 | } 199 | -------------------------------------------------------------------------------- /frontend/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules/ 3 | dist/ 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | package-lock.json 8 | tests/**/coverage/ 9 | 10 | # Editor directories and files 11 | .idea 12 | .vscode 13 | *.suo 14 | *.ntvs* 15 | *.njsproj 16 | *.sln 17 | -------------------------------------------------------------------------------- /frontend/.npmrc: -------------------------------------------------------------------------------- 1 | phantomjs_cdnurl=http://cnpmjs.org/downloads 2 | sass_binary_site=https://npm.taobao.org/mirrors/node-sass/ 3 | registry=https://registry.npm.taobao.org 4 | -------------------------------------------------------------------------------- /frontend/.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 10 3 | script: npm run test 4 | notifications: 5 | email: false 6 | -------------------------------------------------------------------------------- /frontend/README-zh.md: -------------------------------------------------------------------------------- 1 | # vue-admin-template 2 | 3 | > 这是一个极简的 vue admin 管理后台。它只包含了 Element UI & axios & iconfont & permission control & lint,这些搭建后台必要的东西。 4 | 5 | [线上地址](http://panjiachen.github.io/vue-admin-template) 6 | 7 | [国内访问](https://panjiachen.gitee.io/vue-admin-template) 8 | 9 | 目前版本为 `v4.0+` 基于 `vue-cli` 进行构建,若你想使用旧版本,可以切换分支到[tag/3.11.0](https://github.com/PanJiaChen/vue-admin-template/tree/tag/3.11.0),它不依赖 `vue-cli`。 10 | 11 | ## Extra 12 | 13 | 如果你想要根据用户角色来动态生成侧边栏和 router,你可以使用该分支[permission-control](https://github.com/PanJiaChen/vue-admin-template/tree/permission-control) 14 | 15 | ## 相关项目 16 | 17 | - [vue-element-admin](https://github.com/PanJiaChen/vue-element-admin) 18 | 19 | - [electron-vue-admin](https://github.com/PanJiaChen/electron-vue-admin) 20 | 21 | - [vue-typescript-admin-template](https://github.com/Armour/vue-typescript-admin-template) 22 | 23 | - [awesome-project](https://github.com/PanJiaChen/vue-element-admin/issues/2312) 24 | 25 | 写了一个系列的教程配套文章,如何从零构建后一个完整的后台项目: 26 | 27 | - [手摸手,带你用 vue 撸后台 系列一(基础篇)](https://juejin.im/post/59097cd7a22b9d0065fb61d2) 28 | - [手摸手,带你用 vue 撸后台 系列二(登录权限篇)](https://juejin.im/post/591aa14f570c35006961acac) 29 | - [手摸手,带你用 vue 撸后台 系列三 (实战篇)](https://juejin.im/post/593121aa0ce4630057f70d35) 30 | - [手摸手,带你用 vue 撸后台 系列四(vueAdmin 一个极简的后台基础模板,专门针对本项目的文章,算作是一篇文档)](https://juejin.im/post/595b4d776fb9a06bbe7dba56) 31 | - [手摸手,带你封装一个 vue component](https://segmentfault.com/a/1190000009090836) 32 | 33 | ## Build Setup 34 | 35 | ```bash 36 | # 克隆项目 37 | git clone https://github.com/PanJiaChen/vue-admin-template.git 38 | 39 | # 进入项目目录 40 | cd vue-admin-template 41 | 42 | # 安装依赖 43 | npm install 44 | 45 | # 建议不要直接使用 cnpm 安装以来,会有各种诡异的 bug。可以通过如下操作解决 npm 下载速度慢的问题 46 | npm install --registry=https://registry.npm.taobao.org 47 | 48 | # 启动服务 49 | npm run dev 50 | ``` 51 | 52 | 浏览器访问 [http://localhost:9528](http://localhost:9528) 53 | 54 | ## 发布 55 | 56 | ```bash 57 | # 构建测试环境 58 | npm run build:stage 59 | 60 | # 构建生产环境 61 | npm run build:prod 62 | ``` 63 | 64 | ## 其它 65 | 66 | ```bash 67 | # 预览发布环境效果 68 | npm run preview 69 | 70 | # 预览发布环境效果 + 静态资源分析 71 | npm run preview -- --report 72 | 73 | # 代码格式检查 74 | npm run lint 75 | 76 | # 代码格式检查并自动修复 77 | npm run lint -- --fix 78 | ``` 79 | 80 | 更多信息请参考 [使用文档](https://panjiachen.github.io/vue-element-admin-site/zh/) 81 | 82 | ## Demo 83 | 84 | ![demo](https://github.com/PanJiaChen/PanJiaChen.github.io/blob/master/images/demo.gif) 85 | 86 | ## Browsers support 87 | 88 | Modern browsers and Internet Explorer 10+. 89 | 90 | | [IE / Edge](http://godban.github.io/browsers-support-badges/)
IE / Edge | [Firefox](http://godban.github.io/browsers-support-badges/)
Firefox | [Chrome](http://godban.github.io/browsers-support-badges/)
Chrome | [Safari](http://godban.github.io/browsers-support-badges/)
Safari | 91 | | --------- | --------- | --------- | --------- | 92 | | IE10, IE11, Edge| last 2 versions| last 2 versions| last 2 versions 93 | 94 | ## License 95 | 96 | [MIT](https://github.com/PanJiaChen/vue-admin-template/blob/master/LICENSE) license. 97 | 98 | Copyright (c) 2017-present PanJiaChen 99 | -------------------------------------------------------------------------------- /frontend/README.md: -------------------------------------------------------------------------------- 1 | # vue-admin-template 2 | 3 | English | [简体中文](./README-zh.md) 4 | 5 | > A minimal vue admin template with Element UI & axios & iconfont & permission control & lint 6 | 7 | **Live demo:** http://panjiachen.github.io/vue-admin-template 8 | 9 | **The current version is `v4.0+` build on `vue-cli`. If you want to use the old version , you can switch branch to [tag/3.11.0](https://github.com/PanJiaChen/vue-admin-template/tree/tag/3.11.0), it does not rely on `vue-cli`** 10 | 11 | ## Build Setup 12 | 13 | ```bash 14 | # clone the project 15 | git clone https://github.com/PanJiaChen/vue-admin-template.git 16 | 17 | # enter the project directory 18 | cd vue-admin-template 19 | 20 | # install dependency 21 | npm install 22 | 23 | # develop 24 | npm run dev 25 | ``` 26 | 27 | This will automatically open http://localhost:9528 28 | 29 | ## Build 30 | 31 | ```bash 32 | # build for test environment 33 | npm run build:stage 34 | 35 | # build for production environment 36 | npm run build:prod 37 | ``` 38 | 39 | ## Advanced 40 | 41 | ```bash 42 | # preview the release environment effect 43 | npm run preview 44 | 45 | # preview the release environment effect + static resource analysis 46 | npm run preview -- --report 47 | 48 | # code format check 49 | npm run lint 50 | 51 | # code format check and auto fix 52 | npm run lint -- --fix 53 | ``` 54 | 55 | Refer to [Documentation](https://panjiachen.github.io/vue-element-admin-site/guide/essentials/deploy.html) for more information 56 | 57 | ## Demo 58 | 59 | ![demo](https://github.com/PanJiaChen/PanJiaChen.github.io/blob/master/images/demo.gif) 60 | 61 | ## Extra 62 | 63 | If you want router permission && generate menu by user roles , you can use this branch [permission-control](https://github.com/PanJiaChen/vue-admin-template/tree/permission-control) 64 | 65 | For `typescript` version, you can use [vue-typescript-admin-template](https://github.com/Armour/vue-typescript-admin-template) (Credits: [@Armour](https://github.com/Armour)) 66 | 67 | ## Related Project 68 | 69 | - [vue-element-admin](https://github.com/PanJiaChen/vue-element-admin) 70 | 71 | - [electron-vue-admin](https://github.com/PanJiaChen/electron-vue-admin) 72 | 73 | - [vue-typescript-admin-template](https://github.com/Armour/vue-typescript-admin-template) 74 | 75 | - [awesome-project](https://github.com/PanJiaChen/vue-element-admin/issues/2312) 76 | 77 | ## Browsers support 78 | 79 | Modern browsers and Internet Explorer 10+. 80 | 81 | | [IE / Edge](http://godban.github.io/browsers-support-badges/)
IE / Edge | [Firefox](http://godban.github.io/browsers-support-badges/)
Firefox | [Chrome](http://godban.github.io/browsers-support-badges/)
Chrome | [Safari](http://godban.github.io/browsers-support-badges/)
Safari | 82 | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | 83 | | IE10, IE11, Edge | last 2 versions | last 2 versions | last 2 versions | 84 | 85 | ## License 86 | 87 | [MIT](https://github.com/PanJiaChen/vue-admin-template/blob/master/LICENSE) license. 88 | 89 | Copyright (c) 2017-present PanJiaChen 90 | -------------------------------------------------------------------------------- /frontend/babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: [ 3 | '@vue/app' 4 | ] 5 | } 6 | -------------------------------------------------------------------------------- /frontend/build/index.js: -------------------------------------------------------------------------------- 1 | const { run } = require('runjs') 2 | const chalk = require('chalk') 3 | const config = require('../vue.config.js.js') 4 | const rawArgv = process.argv.slice(2) 5 | const args = rawArgv.join(' ') 6 | 7 | if (process.env.npm_config_preview || rawArgv.includes('--preview')) { 8 | const report = rawArgv.includes('--report') 9 | 10 | run(`vue-cli-service build ${args}`) 11 | 12 | const port = 9526 13 | const publicPath = config.publicPath 14 | 15 | var connect = require('connect') 16 | var serveStatic = require('serve-static') 17 | const app = connect() 18 | 19 | app.use( 20 | publicPath, 21 | serveStatic('./dist', { 22 | index: ['index.html', '/'] 23 | }) 24 | ) 25 | 26 | app.listen(port, function() { 27 | console.log(chalk.green(`> Preview at http://localhost:${port}${publicPath}`)) 28 | if (report) { 29 | console.log(chalk.green(`> Report at http://localhost:${port}${publicPath}report.html`)) 30 | } 31 | }) 32 | } else { 33 | run(`vue-cli-service build ${args}`) 34 | } 35 | -------------------------------------------------------------------------------- /frontend/jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | moduleFileExtensions: ['js', 'jsx', 'json', 'vue'], 3 | transform: { 4 | '^.+\\.vue$': 'vue-jest', 5 | '.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$': 6 | 'jest-transform-stub', 7 | '^.+\\.jsx?$': 'babel-jest' 8 | }, 9 | moduleNameMapper: { 10 | '^@/(.*)$': '/src/$1' 11 | }, 12 | snapshotSerializers: ['jest-serializer-vue'], 13 | testMatch: [ 14 | '**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)' 15 | ], 16 | collectCoverageFrom: ['src/utils/**/*.{js,vue}', '!src/utils/auth.js', '!src/utils/request.js', 'src/components/**/*.{js,vue}'], 17 | coverageDirectory: '/tests/unit/coverage', 18 | // 'collectCoverage': true, 19 | 'coverageReporters': [ 20 | 'lcov', 21 | 'text-summary' 22 | ], 23 | testURL: 'http://localhost/' 24 | } 25 | -------------------------------------------------------------------------------- /frontend/jsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": "./", 4 | "paths": { 5 | "@/*": ["src/*"] 6 | } 7 | }, 8 | "exclude": ["node_modules", "dist"] 9 | } 10 | -------------------------------------------------------------------------------- /frontend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "vue-admin-template", 3 | "version": "4.2.1", 4 | "description": "A vue admin template with Element UI & axios & iconfont & permission control & lint", 5 | "author": "Pan ", 6 | "license": "MIT", 7 | "scripts": { 8 | "dev": "vue-cli-service serve", 9 | "build": "vue-cli-service build", 10 | "preview": "node build/index.js --preview", 11 | "lint": "eslint --ext .js,.vue src", 12 | "test:unit": "jest --clearCache && vue-cli-service test:unit", 13 | "test:ci": "npm run lint && npm run test:unit", 14 | "svgo": "svgo -f src/icons/svg --config=src/icons/svgo.yml" 15 | }, 16 | "dependencies": { 17 | "@authing/sso": "^1.4.0", 18 | "authing-js-sdk": "^3.7.0", 19 | "axios": "0.18.1", 20 | "element-ui": "2.13.0", 21 | "js-cookie": "2.2.0", 22 | "normalize.css": "7.0.0", 23 | "nprogress": "0.2.0", 24 | "path-to-regexp": "2.4.0", 25 | "vue": "2.6.10", 26 | "vue-router": "3.0.6", 27 | "vuex": "3.1.0" 28 | }, 29 | "devDependencies": { 30 | "@babel/core": "7.0.0", 31 | "@babel/register": "7.0.0", 32 | "@vue/cli-plugin-babel": "3.6.0", 33 | "@vue/cli-plugin-eslint": "^3.9.1", 34 | "@vue/cli-plugin-unit-jest": "3.6.3", 35 | "@vue/cli-service": "3.6.0", 36 | "@vue/test-utils": "1.0.0-beta.29", 37 | "autoprefixer": "^9.5.1", 38 | "babel-core": "7.0.0-bridge.0", 39 | "babel-eslint": "10.0.1", 40 | "babel-jest": "23.6.0", 41 | "chalk": "2.4.2", 42 | "connect": "3.6.6", 43 | "eslint": "5.15.3", 44 | "eslint-plugin-vue": "5.2.2", 45 | "html-webpack-plugin": "3.2.0", 46 | "mockjs": "1.0.1-beta3", 47 | "node-sass": "^4.9.0", 48 | "runjs": "^4.3.2", 49 | "sass-loader": "^7.1.0", 50 | "script-ext-html-webpack-plugin": "2.1.3", 51 | "script-loader": "0.7.2", 52 | "serve-static": "^1.13.2", 53 | "svg-sprite-loader": "4.1.3", 54 | "svgo": "1.2.2", 55 | "vue-template-compiler": "2.6.10" 56 | }, 57 | "engines": { 58 | "node": ">=8.9", 59 | "npm": ">= 3.0.0" 60 | }, 61 | "browserslist": [ 62 | "> 1%", 63 | "last 2 versions" 64 | ] 65 | } 66 | -------------------------------------------------------------------------------- /frontend/postcss.config.js: -------------------------------------------------------------------------------- 1 | // https://github.com/michael-ciniawsky/postcss-load-config 2 | 3 | module.exports = { 4 | 'plugins': { 5 | // to edit target browsers: use "browserslist" field in package.json 6 | 'autoprefixer': {} 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /frontend/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/serverless-plus/serverless-admin-system/13f84d497abd92d3d16cc4ea880ccfa0eda1016e/frontend/public/favicon.ico -------------------------------------------------------------------------------- /frontend/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 10 | 11 | <%= webpackConfig.name %> 12 | <% if (process.env.NODE_ENV === 'production') { %> 13 | 14 | <% } %> 15 | 16 | 17 | 23 |
24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /frontend/serverless.yml: -------------------------------------------------------------------------------- 1 | org: slsplus 2 | app: admin-system 3 | stage: dev 4 | 5 | component: website 6 | name: admin-system-frontend 7 | 8 | # more configuration for @serverless/tencent-website, 9 | # refer to: https://github.com/serverless-components/tencent-website/blob/master/docs/configure.md 10 | inputs: 11 | src: 12 | src: ./ 13 | dist: ./dist 14 | hook: npm run build 15 | envPath: ./ 16 | index: index.html 17 | error: index.html 18 | env: 19 | # get api url after below api service deployed. 20 | apiUrl: ${output:${stage}:${app}:admin-system-backend.apigw.url} 21 | protocol: https 22 | bucketName: ${app} 23 | region: ${env:REGION} 24 | hosts: 25 | - host: sls-admin.yugasun.com 26 | async: false 27 | area: mainland 28 | autoRefresh: true 29 | # after cdn created, just set onlyRefresh to true for refresh 30 | onlyRefresh: true 31 | https: 32 | switch: on 33 | http2: on 34 | certInfo: 35 | certId: ajzvLP82 36 | forceRedirect: 37 | switch: on 38 | redirectType: https 39 | redirectStatusCode: 301 40 | -------------------------------------------------------------------------------- /frontend/src/App.vue: -------------------------------------------------------------------------------- 1 | 6 | 7 | 12 | -------------------------------------------------------------------------------- /frontend/src/api/post.js: -------------------------------------------------------------------------------- 1 | import request from '@/utils/request' 2 | 3 | export function getList(params) { 4 | return request({ 5 | url: '/posts', 6 | method: 'get', 7 | params 8 | }) 9 | } 10 | 11 | export function create(data) { 12 | return request({ 13 | url: '/posts', 14 | method: 'post', 15 | data 16 | }) 17 | } 18 | 19 | export function destroy(id) { 20 | return request({ 21 | url: `/posts/${id}`, 22 | method: 'delete' 23 | }) 24 | } 25 | -------------------------------------------------------------------------------- /frontend/src/api/user.js: -------------------------------------------------------------------------------- 1 | import request from '@/utils/request' 2 | 3 | export function login(data) { 4 | return request({ 5 | url: '/login', 6 | method: 'post', 7 | data 8 | }) 9 | } 10 | 11 | export function getInfo(token) { 12 | return request({ 13 | url: '/user-info', 14 | method: 'get' 15 | }) 16 | } 17 | 18 | export function logout() { 19 | return request({ 20 | url: '/logout', 21 | method: 'post' 22 | }) 23 | } 24 | 25 | export function getList() { 26 | return request({ 27 | url: '/users', 28 | method: 'get' 29 | }) 30 | } 31 | -------------------------------------------------------------------------------- /frontend/src/assets/404_images/404.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/serverless-plus/serverless-admin-system/13f84d497abd92d3d16cc4ea880ccfa0eda1016e/frontend/src/assets/404_images/404.png -------------------------------------------------------------------------------- /frontend/src/assets/404_images/404_cloud.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/serverless-plus/serverless-admin-system/13f84d497abd92d3d16cc4ea880ccfa0eda1016e/frontend/src/assets/404_images/404_cloud.png -------------------------------------------------------------------------------- /frontend/src/assets/authing.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/serverless-plus/serverless-admin-system/13f84d497abd92d3d16cc4ea880ccfa0eda1016e/frontend/src/assets/authing.png -------------------------------------------------------------------------------- /frontend/src/components/Breadcrumb/index.vue: -------------------------------------------------------------------------------- 1 | 11 | 12 | 65 | 66 | 79 | -------------------------------------------------------------------------------- /frontend/src/components/Hamburger/index.vue: -------------------------------------------------------------------------------- 1 | 15 | 16 | 32 | 33 | 45 | -------------------------------------------------------------------------------- /frontend/src/components/SvgIcon/index.vue: -------------------------------------------------------------------------------- 1 | 7 | 8 | 47 | 48 | 63 | -------------------------------------------------------------------------------- /frontend/src/icons/index.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import SvgIcon from '@/components/SvgIcon'// svg component 3 | 4 | // register globally 5 | Vue.component('svg-icon', SvgIcon) 6 | 7 | const req = require.context('./svg', false, /\.svg$/) 8 | const requireAll = requireContext => requireContext.keys().map(requireContext) 9 | requireAll(req) 10 | -------------------------------------------------------------------------------- /frontend/src/icons/svg/dashboard.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /frontend/src/icons/svg/example.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /frontend/src/icons/svg/eye-open.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /frontend/src/icons/svg/eye.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /frontend/src/icons/svg/form.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /frontend/src/icons/svg/link.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /frontend/src/icons/svg/nested.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /frontend/src/icons/svg/password.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /frontend/src/icons/svg/table.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /frontend/src/icons/svg/tree.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /frontend/src/icons/svg/user.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /frontend/src/icons/svgo.yml: -------------------------------------------------------------------------------- 1 | # replace default config 2 | 3 | # multipass: true 4 | # full: true 5 | 6 | plugins: 7 | 8 | # - name 9 | # 10 | # or: 11 | # - name: false 12 | # - name: true 13 | # 14 | # or: 15 | # - name: 16 | # param1: 1 17 | # param2: 2 18 | 19 | - removeAttrs: 20 | attrs: 21 | - 'fill' 22 | - 'fill-rule' 23 | -------------------------------------------------------------------------------- /frontend/src/layout/components/AppMain.vue: -------------------------------------------------------------------------------- 1 | 8 | 9 | 19 | 20 | 32 | 33 | 41 | -------------------------------------------------------------------------------- /frontend/src/layout/components/Navbar.vue: -------------------------------------------------------------------------------- 1 | 38 | 39 | 66 | 67 | 145 | -------------------------------------------------------------------------------- /frontend/src/layout/components/Sidebar/FixiOSBug.js: -------------------------------------------------------------------------------- 1 | export default { 2 | computed: { 3 | device() { 4 | return this.$store.state.app.device 5 | } 6 | }, 7 | mounted() { 8 | // In order to fix the click on menu on the ios device will trigger the mouseleave bug 9 | // https://github.com/PanJiaChen/vue-element-admin/issues/1135 10 | this.fixBugIniOS() 11 | }, 12 | methods: { 13 | fixBugIniOS() { 14 | const $subMenu = this.$refs.subMenu 15 | if ($subMenu) { 16 | const handleMouseleave = $subMenu.handleMouseleave 17 | $subMenu.handleMouseleave = (e) => { 18 | if (this.device === 'mobile') { 19 | return 20 | } 21 | handleMouseleave(e) 22 | } 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /frontend/src/layout/components/Sidebar/Item.vue: -------------------------------------------------------------------------------- 1 | 30 | -------------------------------------------------------------------------------- /frontend/src/layout/components/Sidebar/Link.vue: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 37 | -------------------------------------------------------------------------------- /frontend/src/layout/components/Sidebar/Logo.vue: -------------------------------------------------------------------------------- 1 | 15 | 16 | 33 | 34 | 83 | -------------------------------------------------------------------------------- /frontend/src/layout/components/Sidebar/SidebarItem.vue: -------------------------------------------------------------------------------- 1 | 26 | 27 | 96 | -------------------------------------------------------------------------------- /frontend/src/layout/components/Sidebar/index.vue: -------------------------------------------------------------------------------- 1 | 20 | 21 | 57 | -------------------------------------------------------------------------------- /frontend/src/layout/components/index.js: -------------------------------------------------------------------------------- 1 | export { default as Navbar } from './Navbar' 2 | export { default as Sidebar } from './Sidebar' 3 | export { default as AppMain } from './AppMain' 4 | -------------------------------------------------------------------------------- /frontend/src/layout/index.vue: -------------------------------------------------------------------------------- 1 | 13 | 14 | 52 | 53 | 94 | -------------------------------------------------------------------------------- /frontend/src/layout/mixin/ResizeHandler.js: -------------------------------------------------------------------------------- 1 | import store from '@/store' 2 | 3 | const { body } = document 4 | const WIDTH = 992 // refer to Bootstrap's responsive design 5 | 6 | export default { 7 | watch: { 8 | $route(route) { 9 | if (this.device === 'mobile' && this.sidebar.opened) { 10 | store.dispatch('app/closeSideBar', { withoutAnimation: false }) 11 | } 12 | } 13 | }, 14 | beforeMount() { 15 | window.addEventListener('resize', this.$_resizeHandler) 16 | }, 17 | beforeDestroy() { 18 | window.removeEventListener('resize', this.$_resizeHandler) 19 | }, 20 | mounted() { 21 | const isMobile = this.$_isMobile() 22 | if (isMobile) { 23 | store.dispatch('app/toggleDevice', 'mobile') 24 | store.dispatch('app/closeSideBar', { withoutAnimation: true }) 25 | } 26 | }, 27 | methods: { 28 | // use $_ for mixins properties 29 | // https://vuejs.org/v2/style-guide/index.html#Private-property-names-essential 30 | $_isMobile() { 31 | const rect = body.getBoundingClientRect() 32 | return rect.width - 1 < WIDTH 33 | }, 34 | $_resizeHandler() { 35 | if (!document.hidden) { 36 | const isMobile = this.$_isMobile() 37 | store.dispatch('app/toggleDevice', isMobile ? 'mobile' : 'desktop') 38 | 39 | if (isMobile) { 40 | store.dispatch('app/closeSideBar', { withoutAnimation: true }) 41 | } 42 | } 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /frontend/src/main.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | 3 | import 'normalize.css/normalize.css' // A modern alternative to CSS resets 4 | 5 | import ElementUI from 'element-ui' 6 | import 'element-ui/lib/theme-chalk/index.css' 7 | import locale from 'element-ui/lib/locale/lang/en' // lang i18n 8 | 9 | import '@/styles/index.scss' // global css 10 | 11 | import App from './App' 12 | import store from './store' 13 | import router from './router' 14 | 15 | import '@/icons' // icon 16 | import '@/permission' // permission control 17 | 18 | // set ElementUI lang to EN 19 | Vue.use(ElementUI, { locale }) 20 | // 如果想要中文版 element-ui,按如下方式声明 21 | // Vue.use(ElementUI) 22 | 23 | Vue.config.productionTip = false 24 | 25 | new Vue({ 26 | el: '#app', 27 | router, 28 | store, 29 | render: h => h(App) 30 | }) 31 | -------------------------------------------------------------------------------- /frontend/src/permission.js: -------------------------------------------------------------------------------- 1 | import router from './router' 2 | import store from './store' 3 | import { Message } from 'element-ui' 4 | import NProgress from 'nprogress' // progress bar 5 | import 'nprogress/nprogress.css' // progress bar style 6 | import { getToken } from '@/utils/auth' // get token from cookie 7 | import getPageTitle from '@/utils/get-page-title' 8 | 9 | NProgress.configure({ showSpinner: false }) // NProgress Configuration 10 | 11 | const whiteList = ['/login'] // no redirect whitelist 12 | 13 | router.beforeEach(async(to, from, next) => { 14 | // start progress bar 15 | NProgress.start() 16 | 17 | // set page title 18 | document.title = getPageTitle(to.meta.title) 19 | 20 | // determine whether the user has logged in 21 | const hasToken = getToken() 22 | 23 | if (hasToken) { 24 | if (to.path === '/login') { 25 | // if is logged in, redirect to the home page 26 | next({ path: '/' }) 27 | NProgress.done() 28 | } else { 29 | const hasGetUserInfo = store.getters.name 30 | if (hasGetUserInfo) { 31 | next() 32 | } else { 33 | try { 34 | // get user info 35 | await store.dispatch('user/getInfo') 36 | 37 | next() 38 | } catch (error) { 39 | // remove token and go to login page to re-login 40 | await store.dispatch('user/resetToken') 41 | Message.error(error || 'Has Error') 42 | next(`/login?redirect=${to.path}`) 43 | NProgress.done() 44 | } 45 | } 46 | } 47 | } else { 48 | /* has no token*/ 49 | 50 | if (whiteList.indexOf(to.path) !== -1) { 51 | // in the free login whitelist, go directly 52 | next() 53 | } else { 54 | // other pages that do not have permission to access are redirected to the login page. 55 | next(`/login?redirect=${to.path}`) 56 | NProgress.done() 57 | } 58 | } 59 | }) 60 | 61 | router.afterEach(() => { 62 | // finish progress bar 63 | NProgress.done() 64 | }) 65 | -------------------------------------------------------------------------------- /frontend/src/router/index.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import Router from 'vue-router' 3 | 4 | Vue.use(Router) 5 | 6 | /* Layout */ 7 | import Layout from '@/layout' 8 | 9 | /** 10 | * Note: sub-menu only appear when route children.length >= 1 11 | * Detail see: https://panjiachen.github.io/vue-element-admin-site/guide/essentials/router-and-nav.html 12 | * 13 | * hidden: true if set true, item will not show in the sidebar(default is false) 14 | * alwaysShow: true if set true, will always show the root menu 15 | * if not set alwaysShow, when item has more than one children route, 16 | * it will becomes nested mode, otherwise not show the root menu 17 | * redirect: noRedirect if set noRedirect will no redirect in the breadcrumb 18 | * name:'router-name' the name is used by (must set!!!) 19 | * meta : { 20 | roles: ['admin','editor'] control the page roles (you can set multiple roles) 21 | title: 'title' the name show in sidebar and breadcrumb (recommend set) 22 | icon: 'svg-name' the icon show in the sidebar 23 | breadcrumb: false if set false, the item will hidden in breadcrumb(default is true) 24 | activeMenu: '/example/list' if set path, the sidebar will highlight the path you set 25 | } 26 | */ 27 | 28 | /** 29 | * constantRoutes 30 | * a base page that does not have permission requirements 31 | * all roles can be accessed 32 | */ 33 | export const constantRoutes = [ 34 | { 35 | path: '/login', 36 | component: () => import('@/views/login'), 37 | hidden: true 38 | }, 39 | 40 | { 41 | path: '/404', 42 | component: () => import('@/views/404'), 43 | hidden: true 44 | }, 45 | 46 | { 47 | path: '/', 48 | component: Layout, 49 | redirect: '/dashboard', 50 | children: [{ 51 | path: 'dashboard', 52 | name: 'Dashboard', 53 | component: () => import('@/views/dashboard'), 54 | meta: { title: 'Dashboard', icon: 'dashboard' } 55 | }] 56 | }, 57 | 58 | { 59 | path: '/posts', 60 | component: Layout, 61 | redirect: '/posts/list', 62 | name: 'Posts', 63 | meta: { title: 'Posts', icon: 'example' }, 64 | children: [ 65 | { 66 | path: 'list', 67 | name: 'List', 68 | component: () => import('@/views/posts'), 69 | meta: { title: 'PostsList', icon: 'table' } 70 | }, 71 | { 72 | path: 'create', 73 | name: 'PostsCreate', 74 | component: () => import('@/views/posts/create'), 75 | meta: { title: 'PostsCreate', icon: 'form' } 76 | } 77 | ] 78 | }, 79 | 80 | { 81 | path: '/nested', 82 | component: Layout, 83 | redirect: '/nested/menu1', 84 | name: 'Nested', 85 | meta: { 86 | title: 'Nested', 87 | icon: 'nested' 88 | }, 89 | children: [ 90 | { 91 | path: 'menu1', 92 | component: () => import('@/views/nested/menu1'), // Parent router-view 93 | name: 'Menu1', 94 | meta: { title: 'Menu1' }, 95 | children: [ 96 | { 97 | path: 'menu1-1', 98 | component: () => import('@/views/nested/menu1/menu1-1'), 99 | name: 'Menu1-1', 100 | meta: { title: 'Menu1-1' } 101 | }, 102 | { 103 | path: 'menu1-2', 104 | component: () => import('@/views/nested/menu1/menu1-2'), 105 | name: 'Menu1-2', 106 | meta: { title: 'Menu1-2' }, 107 | children: [ 108 | { 109 | path: 'menu1-2-1', 110 | component: () => import('@/views/nested/menu1/menu1-2/menu1-2-1'), 111 | name: 'Menu1-2-1', 112 | meta: { title: 'Menu1-2-1' } 113 | }, 114 | { 115 | path: 'menu1-2-2', 116 | component: () => import('@/views/nested/menu1/menu1-2/menu1-2-2'), 117 | name: 'Menu1-2-2', 118 | meta: { title: 'Menu1-2-2' } 119 | } 120 | ] 121 | }, 122 | { 123 | path: 'menu1-3', 124 | component: () => import('@/views/nested/menu1/menu1-3'), 125 | name: 'Menu1-3', 126 | meta: { title: 'Menu1-3' } 127 | } 128 | ] 129 | }, 130 | { 131 | path: 'menu2', 132 | component: () => import('@/views/nested/menu2'), 133 | meta: { title: 'menu2' } 134 | } 135 | ] 136 | }, 137 | 138 | { 139 | path: 'external-link', 140 | component: Layout, 141 | children: [ 142 | { 143 | path: 'https://github.com/yugasun/serverless-admin-system', 144 | meta: { title: 'External Link', icon: 'link' } 145 | } 146 | ] 147 | }, 148 | 149 | // 404 page must be placed at the end !!! 150 | { path: '*', redirect: '/404', hidden: true } 151 | ] 152 | 153 | const createRouter = () => new Router({ 154 | // mode: 'history', // require service support 155 | scrollBehavior: () => ({ y: 0 }), 156 | routes: constantRoutes 157 | }) 158 | 159 | const router = createRouter() 160 | 161 | // Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465 162 | export function resetRouter() { 163 | const newRouter = createRouter() 164 | router.matcher = newRouter.matcher // reset router 165 | } 166 | 167 | export default router 168 | -------------------------------------------------------------------------------- /frontend/src/settings.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | title: 'Serverless Admin System', 3 | 4 | /** 5 | * @type {boolean} true | false 6 | * @description Whether fix the header 7 | */ 8 | fixedHeader: false, 9 | 10 | /** 11 | * @type {boolean} true | false 12 | * @description Whether show the logo in sidebar 13 | */ 14 | sidebarLogo: false 15 | } 16 | -------------------------------------------------------------------------------- /frontend/src/store/getters.js: -------------------------------------------------------------------------------- 1 | const getters = { 2 | sidebar: state => state.app.sidebar, 3 | device: state => state.app.device, 4 | token: state => state.user.token, 5 | avatar: state => state.user.avatar, 6 | name: state => state.user.name 7 | } 8 | export default getters 9 | -------------------------------------------------------------------------------- /frontend/src/store/index.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import Vuex from 'vuex' 3 | import getters from './getters' 4 | import app from './modules/app' 5 | import settings from './modules/settings' 6 | import user from './modules/user' 7 | 8 | Vue.use(Vuex) 9 | 10 | const store = new Vuex.Store({ 11 | modules: { 12 | app, 13 | settings, 14 | user 15 | }, 16 | getters 17 | }) 18 | 19 | export default store 20 | -------------------------------------------------------------------------------- /frontend/src/store/modules/app.js: -------------------------------------------------------------------------------- 1 | import Cookies from 'js-cookie' 2 | 3 | const state = { 4 | sidebar: { 5 | opened: Cookies.get('sidebarStatus') ? !!+Cookies.get('sidebarStatus') : true, 6 | withoutAnimation: false 7 | }, 8 | device: 'desktop' 9 | } 10 | 11 | const mutations = { 12 | TOGGLE_SIDEBAR: state => { 13 | state.sidebar.opened = !state.sidebar.opened 14 | state.sidebar.withoutAnimation = false 15 | if (state.sidebar.opened) { 16 | Cookies.set('sidebarStatus', 1) 17 | } else { 18 | Cookies.set('sidebarStatus', 0) 19 | } 20 | }, 21 | CLOSE_SIDEBAR: (state, withoutAnimation) => { 22 | Cookies.set('sidebarStatus', 0) 23 | state.sidebar.opened = false 24 | state.sidebar.withoutAnimation = withoutAnimation 25 | }, 26 | TOGGLE_DEVICE: (state, device) => { 27 | state.device = device 28 | } 29 | } 30 | 31 | const actions = { 32 | toggleSideBar({ commit }) { 33 | commit('TOGGLE_SIDEBAR') 34 | }, 35 | closeSideBar({ commit }, { withoutAnimation }) { 36 | commit('CLOSE_SIDEBAR', withoutAnimation) 37 | }, 38 | toggleDevice({ commit }, device) { 39 | commit('TOGGLE_DEVICE', device) 40 | } 41 | } 42 | 43 | export default { 44 | namespaced: true, 45 | state, 46 | mutations, 47 | actions 48 | } 49 | -------------------------------------------------------------------------------- /frontend/src/store/modules/settings.js: -------------------------------------------------------------------------------- 1 | import defaultSettings from '@/settings' 2 | 3 | const { showSettings, fixedHeader, sidebarLogo } = defaultSettings 4 | 5 | const state = { 6 | showSettings: showSettings, 7 | fixedHeader: fixedHeader, 8 | sidebarLogo: sidebarLogo 9 | } 10 | 11 | const mutations = { 12 | CHANGE_SETTING: (state, { key, value }) => { 13 | if (state.hasOwnProperty(key)) { 14 | state[key] = value 15 | } 16 | } 17 | } 18 | 19 | const actions = { 20 | changeSetting({ commit }, data) { 21 | commit('CHANGE_SETTING', data) 22 | } 23 | } 24 | 25 | export default { 26 | namespaced: true, 27 | state, 28 | mutations, 29 | actions 30 | } 31 | 32 | -------------------------------------------------------------------------------- /frontend/src/store/modules/user.js: -------------------------------------------------------------------------------- 1 | import AuthingSSO from '@authing/sso' 2 | import { login, logout, getInfo } from '@/api/user' 3 | import { getToken, setToken, removeToken } from '@/utils/auth' 4 | import { resetRouter } from '@/router' 5 | 6 | const authing = new AuthingSSO({ 7 | appId: '5e44f4bf31466018397e69b5', 8 | appType: 'oidc', // 默认 oidc 9 | appDomain: 'sls-admin.authing.cn' 10 | }) 11 | 12 | const getDefaultState = () => { 13 | return { 14 | authing, 15 | token: getToken(), 16 | name: '', 17 | avatar: '' 18 | } 19 | } 20 | 21 | const state = getDefaultState() 22 | 23 | const mutations = { 24 | RESET_STATE: (state) => { 25 | Object.assign(state, getDefaultState()) 26 | }, 27 | SET_TOKEN: (state, token) => { 28 | state.token = token 29 | }, 30 | SET_NAME: (state, name) => { 31 | state.name = name 32 | }, 33 | SET_AVATAR: (state, avatar) => { 34 | state.avatar = avatar 35 | } 36 | } 37 | 38 | const actions = { 39 | // user login 40 | login({ commit }, userInfo) { 41 | const { username, password } = userInfo 42 | return new Promise((resolve, reject) => { 43 | login({ username: username.trim(), password: password }).then(response => { 44 | const { token } = response 45 | commit('SET_TOKEN', token) 46 | setToken(token) 47 | resolve() 48 | }).catch(error => { 49 | reject(error) 50 | }) 51 | }) 52 | }, 53 | 54 | // get user info 55 | getInfo({ commit, state }) { 56 | return new Promise((resolve, reject) => { 57 | getInfo(state.token).then(response => { 58 | const { data } = response 59 | 60 | if (!data) { 61 | reject('Verification failed, please Login again.') 62 | } 63 | 64 | const { name, avatar } = data 65 | 66 | commit('SET_NAME', name) 67 | commit('SET_AVATAR', avatar) 68 | resolve(data) 69 | }).catch(error => { 70 | reject(error) 71 | }) 72 | }) 73 | }, 74 | 75 | // user logout 76 | logout({ commit, state }) { 77 | return new Promise((resolve, reject) => { 78 | logout(state.token).then(async() => { 79 | removeToken() // must remove token first 80 | resetRouter() 81 | commit('RESET_STATE') 82 | await state.authing.logout() 83 | resolve() 84 | }).catch(error => { 85 | reject(error) 86 | }) 87 | }) 88 | }, 89 | 90 | // remove token 91 | resetToken({ commit }) { 92 | return new Promise(resolve => { 93 | removeToken() // must remove token first 94 | commit('RESET_STATE') 95 | resolve() 96 | }) 97 | }, 98 | 99 | authingLogin({ commit }, token) { 100 | commit('SET_TOKEN', token) 101 | setToken(token) 102 | } 103 | } 104 | 105 | export default { 106 | namespaced: true, 107 | state, 108 | mutations, 109 | actions 110 | } 111 | 112 | -------------------------------------------------------------------------------- /frontend/src/styles/element-ui.scss: -------------------------------------------------------------------------------- 1 | // cover some element-ui styles 2 | 3 | .el-breadcrumb__inner, 4 | .el-breadcrumb__inner a { 5 | font-weight: 400 !important; 6 | } 7 | 8 | .el-upload { 9 | input[type="file"] { 10 | display: none !important; 11 | } 12 | } 13 | 14 | .el-upload__input { 15 | display: none; 16 | } 17 | 18 | 19 | // to fixed https://github.com/ElemeFE/element/issues/2461 20 | .el-dialog { 21 | transform: none; 22 | left: 0; 23 | position: relative; 24 | margin: 0 auto; 25 | } 26 | 27 | // refine element ui upload 28 | .upload-container { 29 | .el-upload { 30 | width: 100%; 31 | 32 | .el-upload-dragger { 33 | width: 100%; 34 | height: 200px; 35 | } 36 | } 37 | } 38 | 39 | // dropdown 40 | .el-dropdown-menu { 41 | a { 42 | display: block 43 | } 44 | } 45 | 46 | // to fix el-date-picker css style 47 | .el-range-separator { 48 | box-sizing: content-box; 49 | } 50 | -------------------------------------------------------------------------------- /frontend/src/styles/index.scss: -------------------------------------------------------------------------------- 1 | @import './variables.scss'; 2 | @import './mixin.scss'; 3 | @import './transition.scss'; 4 | @import './element-ui.scss'; 5 | @import './sidebar.scss'; 6 | 7 | body { 8 | height: 100%; 9 | -moz-osx-font-smoothing: grayscale; 10 | -webkit-font-smoothing: antialiased; 11 | text-rendering: optimizeLegibility; 12 | font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, Arial, sans-serif; 13 | } 14 | 15 | label { 16 | font-weight: 700; 17 | } 18 | 19 | html { 20 | height: 100%; 21 | box-sizing: border-box; 22 | } 23 | 24 | #app { 25 | height: 100%; 26 | } 27 | 28 | *, 29 | *:before, 30 | *:after { 31 | box-sizing: inherit; 32 | } 33 | 34 | a:focus, 35 | a:active { 36 | outline: none; 37 | } 38 | 39 | a, 40 | a:focus, 41 | a:hover { 42 | cursor: pointer; 43 | color: inherit; 44 | text-decoration: none; 45 | } 46 | 47 | div:focus { 48 | outline: none; 49 | } 50 | 51 | .clearfix { 52 | &:after { 53 | visibility: hidden; 54 | display: block; 55 | font-size: 0; 56 | content: " "; 57 | clear: both; 58 | height: 0; 59 | } 60 | } 61 | 62 | // main-container global css 63 | .app-container { 64 | padding: 20px; 65 | } 66 | -------------------------------------------------------------------------------- /frontend/src/styles/mixin.scss: -------------------------------------------------------------------------------- 1 | @mixin clearfix { 2 | &:after { 3 | content: ""; 4 | display: table; 5 | clear: both; 6 | } 7 | } 8 | 9 | @mixin scrollBar { 10 | &::-webkit-scrollbar-track-piece { 11 | background: #d3dce6; 12 | } 13 | 14 | &::-webkit-scrollbar { 15 | width: 6px; 16 | } 17 | 18 | &::-webkit-scrollbar-thumb { 19 | background: #99a9bf; 20 | border-radius: 20px; 21 | } 22 | } 23 | 24 | @mixin relative { 25 | position: relative; 26 | width: 100%; 27 | height: 100%; 28 | } 29 | -------------------------------------------------------------------------------- /frontend/src/styles/sidebar.scss: -------------------------------------------------------------------------------- 1 | #app { 2 | 3 | .main-container { 4 | min-height: 100%; 5 | transition: margin-left .28s; 6 | margin-left: $sideBarWidth; 7 | position: relative; 8 | } 9 | 10 | .sidebar-container { 11 | transition: width 0.28s; 12 | width: $sideBarWidth !important; 13 | background-color: $menuBg; 14 | height: 100%; 15 | position: fixed; 16 | font-size: 0px; 17 | top: 0; 18 | bottom: 0; 19 | left: 0; 20 | z-index: 1001; 21 | overflow: hidden; 22 | 23 | // reset element-ui css 24 | .horizontal-collapse-transition { 25 | transition: 0s width ease-in-out, 0s padding-left ease-in-out, 0s padding-right ease-in-out; 26 | } 27 | 28 | .scrollbar-wrapper { 29 | overflow-x: hidden !important; 30 | } 31 | 32 | .el-scrollbar__bar.is-vertical { 33 | right: 0px; 34 | } 35 | 36 | .el-scrollbar { 37 | height: 100%; 38 | } 39 | 40 | &.has-logo { 41 | .el-scrollbar { 42 | height: calc(100% - 50px); 43 | } 44 | } 45 | 46 | .is-horizontal { 47 | display: none; 48 | } 49 | 50 | a { 51 | display: inline-block; 52 | width: 100%; 53 | overflow: hidden; 54 | } 55 | 56 | .svg-icon { 57 | margin-right: 16px; 58 | } 59 | 60 | .el-menu { 61 | border: none; 62 | height: 100%; 63 | width: 100% !important; 64 | } 65 | 66 | // menu hover 67 | .submenu-title-noDropdown, 68 | .el-submenu__title { 69 | &:hover { 70 | background-color: $menuHover !important; 71 | } 72 | } 73 | 74 | .is-active>.el-submenu__title { 75 | color: $subMenuActiveText !important; 76 | } 77 | 78 | & .nest-menu .el-submenu>.el-submenu__title, 79 | & .el-submenu .el-menu-item { 80 | min-width: $sideBarWidth !important; 81 | background-color: $subMenuBg !important; 82 | 83 | &:hover { 84 | background-color: $subMenuHover !important; 85 | } 86 | } 87 | } 88 | 89 | .hideSidebar { 90 | .sidebar-container { 91 | width: 54px !important; 92 | } 93 | 94 | .main-container { 95 | margin-left: 54px; 96 | } 97 | 98 | .submenu-title-noDropdown { 99 | padding: 0 !important; 100 | position: relative; 101 | 102 | .el-tooltip { 103 | padding: 0 !important; 104 | 105 | .svg-icon { 106 | margin-left: 20px; 107 | } 108 | } 109 | } 110 | 111 | .el-submenu { 112 | overflow: hidden; 113 | 114 | &>.el-submenu__title { 115 | padding: 0 !important; 116 | 117 | .svg-icon { 118 | margin-left: 20px; 119 | } 120 | 121 | .el-submenu__icon-arrow { 122 | display: none; 123 | } 124 | } 125 | } 126 | 127 | .el-menu--collapse { 128 | .el-submenu { 129 | &>.el-submenu__title { 130 | &>span { 131 | height: 0; 132 | width: 0; 133 | overflow: hidden; 134 | visibility: hidden; 135 | display: inline-block; 136 | } 137 | } 138 | } 139 | } 140 | } 141 | 142 | .el-menu--collapse .el-menu .el-submenu { 143 | min-width: $sideBarWidth !important; 144 | } 145 | 146 | // mobile responsive 147 | .mobile { 148 | .main-container { 149 | margin-left: 0px; 150 | } 151 | 152 | .sidebar-container { 153 | transition: transform .28s; 154 | width: $sideBarWidth !important; 155 | } 156 | 157 | &.hideSidebar { 158 | .sidebar-container { 159 | pointer-events: none; 160 | transition-duration: 0.3s; 161 | transform: translate3d(-$sideBarWidth, 0, 0); 162 | } 163 | } 164 | } 165 | 166 | .withoutAnimation { 167 | 168 | .main-container, 169 | .sidebar-container { 170 | transition: none; 171 | } 172 | } 173 | } 174 | 175 | // when menu collapsed 176 | .el-menu--vertical { 177 | &>.el-menu { 178 | .svg-icon { 179 | margin-right: 16px; 180 | } 181 | } 182 | 183 | .nest-menu .el-submenu>.el-submenu__title, 184 | .el-menu-item { 185 | &:hover { 186 | // you can use $subMenuHover 187 | background-color: $menuHover !important; 188 | } 189 | } 190 | 191 | // the scroll bar appears when the subMenu is too long 192 | >.el-menu--popup { 193 | max-height: 100vh; 194 | overflow-y: auto; 195 | 196 | &::-webkit-scrollbar-track-piece { 197 | background: #d3dce6; 198 | } 199 | 200 | &::-webkit-scrollbar { 201 | width: 6px; 202 | } 203 | 204 | &::-webkit-scrollbar-thumb { 205 | background: #99a9bf; 206 | border-radius: 20px; 207 | } 208 | } 209 | } 210 | -------------------------------------------------------------------------------- /frontend/src/styles/transition.scss: -------------------------------------------------------------------------------- 1 | // global transition css 2 | 3 | /* fade */ 4 | .fade-enter-active, 5 | .fade-leave-active { 6 | transition: opacity 0.28s; 7 | } 8 | 9 | .fade-enter, 10 | .fade-leave-active { 11 | opacity: 0; 12 | } 13 | 14 | /* fade-transform */ 15 | .fade-transform-leave-active, 16 | .fade-transform-enter-active { 17 | transition: all .5s; 18 | } 19 | 20 | .fade-transform-enter { 21 | opacity: 0; 22 | transform: translateX(-30px); 23 | } 24 | 25 | .fade-transform-leave-to { 26 | opacity: 0; 27 | transform: translateX(30px); 28 | } 29 | 30 | /* breadcrumb transition */ 31 | .breadcrumb-enter-active, 32 | .breadcrumb-leave-active { 33 | transition: all .5s; 34 | } 35 | 36 | .breadcrumb-enter, 37 | .breadcrumb-leave-active { 38 | opacity: 0; 39 | transform: translateX(20px); 40 | } 41 | 42 | .breadcrumb-move { 43 | transition: all .5s; 44 | } 45 | 46 | .breadcrumb-leave-active { 47 | position: absolute; 48 | } 49 | -------------------------------------------------------------------------------- /frontend/src/styles/variables.scss: -------------------------------------------------------------------------------- 1 | // sidebar 2 | $menuText:#bfcbd9; 3 | $menuActiveText:#409EFF; 4 | $subMenuActiveText:#f4f4f5; //https://github.com/ElemeFE/element/issues/12951 5 | 6 | $menuBg:#304156; 7 | $menuHover:#263445; 8 | 9 | $subMenuBg:#1f2d3d; 10 | $subMenuHover:#001528; 11 | 12 | $sideBarWidth: 210px; 13 | 14 | // the :export directive is the magic sauce for webpack 15 | // https://www.bluematador.com/blog/how-to-share-variables-between-js-and-sass 16 | :export { 17 | menuText: $menuText; 18 | menuActiveText: $menuActiveText; 19 | subMenuActiveText: $subMenuActiveText; 20 | menuBg: $menuBg; 21 | menuHover: $menuHover; 22 | subMenuBg: $subMenuBg; 23 | subMenuHover: $subMenuHover; 24 | sideBarWidth: $sideBarWidth; 25 | } 26 | -------------------------------------------------------------------------------- /frontend/src/utils/auth.js: -------------------------------------------------------------------------------- 1 | import Cookies from 'js-cookie' 2 | 3 | const TokenKey = 'vue_admin_template_token' 4 | 5 | export function getToken() { 6 | return Cookies.get(TokenKey) 7 | } 8 | 9 | export function setToken(token) { 10 | return Cookies.set(TokenKey, token) 11 | } 12 | 13 | export function removeToken() { 14 | return Cookies.remove(TokenKey) 15 | } 16 | -------------------------------------------------------------------------------- /frontend/src/utils/get-page-title.js: -------------------------------------------------------------------------------- 1 | import defaultSettings from '@/settings' 2 | 3 | const title = defaultSettings.title || 'Vue Admin Template' 4 | 5 | export default function getPageTitle(pageTitle) { 6 | if (pageTitle) { 7 | return `${pageTitle} - ${title}` 8 | } 9 | return `${title}` 10 | } 11 | -------------------------------------------------------------------------------- /frontend/src/utils/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by PanJiaChen on 16/11/18. 3 | */ 4 | 5 | /** 6 | * Parse the time to string 7 | * @param {(Object|string|number)} time 8 | * @param {string} cFormat 9 | * @returns {string | null} 10 | */ 11 | export function parseTime(time, cFormat) { 12 | if (arguments.length === 0) { 13 | return null 14 | } 15 | const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}' 16 | let date 17 | if (typeof time === 'object') { 18 | date = time 19 | } else { 20 | if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) { 21 | time = parseInt(time) 22 | } 23 | if ((typeof time === 'number') && (time.toString().length === 10)) { 24 | time = time * 1000 25 | } 26 | date = new Date(time) 27 | } 28 | const formatObj = { 29 | y: date.getFullYear(), 30 | m: date.getMonth() + 1, 31 | d: date.getDate(), 32 | h: date.getHours(), 33 | i: date.getMinutes(), 34 | s: date.getSeconds(), 35 | a: date.getDay() 36 | } 37 | const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => { 38 | const value = formatObj[key] 39 | // Note: getDay() returns 0 on Sunday 40 | if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] } 41 | return value.toString().padStart(2, '0') 42 | }) 43 | return time_str 44 | } 45 | 46 | /** 47 | * @param {number} time 48 | * @param {string} option 49 | * @returns {string} 50 | */ 51 | export function formatTime(time, option) { 52 | if (('' + time).length === 10) { 53 | time = parseInt(time) * 1000 54 | } else { 55 | time = +time 56 | } 57 | const d = new Date(time) 58 | const now = Date.now() 59 | 60 | const diff = (now - d) / 1000 61 | 62 | if (diff < 30) { 63 | return '刚刚' 64 | } else if (diff < 3600) { 65 | // less 1 hour 66 | return Math.ceil(diff / 60) + '分钟前' 67 | } else if (diff < 3600 * 24) { 68 | return Math.ceil(diff / 3600) + '小时前' 69 | } else if (diff < 3600 * 24 * 2) { 70 | return '1天前' 71 | } 72 | if (option) { 73 | return parseTime(time, option) 74 | } else { 75 | return ( 76 | d.getMonth() + 77 | 1 + 78 | '月' + 79 | d.getDate() + 80 | '日' + 81 | d.getHours() + 82 | '时' + 83 | d.getMinutes() + 84 | '分' 85 | ) 86 | } 87 | } 88 | 89 | /** 90 | * @param {string} url 91 | * @returns {Object} 92 | */ 93 | export function param2Obj(url) { 94 | const search = url.split('?')[1] 95 | if (!search) { 96 | return {} 97 | } 98 | return JSON.parse( 99 | '{"' + 100 | decodeURIComponent(search) 101 | .replace(/"/g, '\\"') 102 | .replace(/&/g, '","') 103 | .replace(/=/g, '":"') 104 | .replace(/\+/g, ' ') + 105 | '"}' 106 | ) 107 | } 108 | -------------------------------------------------------------------------------- /frontend/src/utils/request.js: -------------------------------------------------------------------------------- 1 | import axios from 'axios' 2 | import { MessageBox, Message } from 'element-ui' 3 | import store from '@/store' 4 | import { getToken } from '@/utils/auth' 5 | 6 | // create an axios instance 7 | const service = axios.create({ 8 | baseURL: (window.env && window.env.apiUrl) || 'http://localhost:7001/', // url = base url + request url 9 | // withCredentials: true, // send cookies when cross-domain requests 10 | timeout: 30000 // request timeout 11 | }) 12 | 13 | // request interceptor 14 | service.interceptors.request.use( 15 | config => { 16 | // do something before request is sent 17 | 18 | if (store.getters.token) { 19 | // let each request carry token 20 | // ['Authorization'] is a custom headers key 21 | // please modify it according to the actual situation 22 | config.headers['Authorization'] = `Bearer ${getToken()}` 23 | } 24 | return config 25 | }, 26 | error => { 27 | // do something with request error 28 | console.log(error) // for debug 29 | return Promise.reject(error) 30 | } 31 | ) 32 | 33 | // response interceptor 34 | service.interceptors.response.use( 35 | /** 36 | * If you want to get http information such as headers or status 37 | * Please return response => response 38 | */ 39 | 40 | /** 41 | * Determine the request status by custom code 42 | * Here is just an example 43 | * You can also judge the status by HTTP Status Code 44 | */ 45 | response => { 46 | const res = response.data 47 | 48 | // if the custom code is not 20000, it is judged as an error. 49 | if (res.code !== 0) { 50 | Message({ 51 | message: res.message || 'Error', 52 | type: 'error', 53 | duration: 5 * 1000 54 | }) 55 | 56 | // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired; 57 | if (res.code === 50008 || res.code === 50012 || res.code === 50014) { 58 | // to re-login 59 | MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', { 60 | confirmButtonText: 'Re-Login', 61 | cancelButtonText: 'Cancel', 62 | type: 'warning' 63 | }).then(() => { 64 | store.dispatch('user/resetToken').then(() => { 65 | location.reload() 66 | }) 67 | }) 68 | } 69 | return Promise.reject(new Error(res.message || 'Error')) 70 | } else { 71 | return res 72 | } 73 | }, 74 | error => { 75 | console.log('err' + error) // for debug 76 | Message({ 77 | message: error.message, 78 | type: 'error', 79 | duration: 5 * 1000 80 | }) 81 | return Promise.reject(error) 82 | } 83 | ) 84 | 85 | export default service 86 | -------------------------------------------------------------------------------- /frontend/src/utils/validate.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by PanJiaChen on 16/11/18. 3 | */ 4 | 5 | /** 6 | * @param {string} path 7 | * @returns {Boolean} 8 | */ 9 | export function isExternal(path) { 10 | return /^(https?:|mailto:|tel:)/.test(path) 11 | } 12 | 13 | /** 14 | * @param {string} str 15 | * @returns {Boolean} 16 | */ 17 | export function validUsername(str) { 18 | const valid_map = ['admin', 'editor'] 19 | return valid_map.indexOf(str.trim()) >= 0 20 | } 21 | -------------------------------------------------------------------------------- /frontend/src/views/404.vue: -------------------------------------------------------------------------------- 1 | 22 | 23 | 34 | 35 | 229 | -------------------------------------------------------------------------------- /frontend/src/views/dashboard/index.vue: -------------------------------------------------------------------------------- 1 | 6 | 7 | 19 | 20 | 31 | -------------------------------------------------------------------------------- /frontend/src/views/login/index.vue: -------------------------------------------------------------------------------- 1 | 81 | 82 | 191 | 192 | 238 | 239 | 317 | -------------------------------------------------------------------------------- /frontend/src/views/nested/menu1/index.vue: -------------------------------------------------------------------------------- 1 | 8 | -------------------------------------------------------------------------------- /frontend/src/views/nested/menu1/menu1-1/index.vue: -------------------------------------------------------------------------------- 1 | 8 | -------------------------------------------------------------------------------- /frontend/src/views/nested/menu1/menu1-2/index.vue: -------------------------------------------------------------------------------- 1 | 8 | -------------------------------------------------------------------------------- /frontend/src/views/nested/menu1/menu1-2/menu1-2-1/index.vue: -------------------------------------------------------------------------------- 1 | 6 | -------------------------------------------------------------------------------- /frontend/src/views/nested/menu1/menu1-2/menu1-2-2/index.vue: -------------------------------------------------------------------------------- 1 | 6 | -------------------------------------------------------------------------------- /frontend/src/views/nested/menu1/menu1-3/index.vue: -------------------------------------------------------------------------------- 1 | 6 | -------------------------------------------------------------------------------- /frontend/src/views/nested/menu2/index.vue: -------------------------------------------------------------------------------- 1 | 6 | -------------------------------------------------------------------------------- /frontend/src/views/posts/create.vue: -------------------------------------------------------------------------------- 1 | 22 | 23 | 81 | 82 | 87 | 88 | -------------------------------------------------------------------------------- /frontend/src/views/posts/index.vue: -------------------------------------------------------------------------------- 1 | 43 | 44 | 88 | -------------------------------------------------------------------------------- /frontend/src/views/tree/index.vue: -------------------------------------------------------------------------------- 1 | 16 | 17 | 78 | 79 | -------------------------------------------------------------------------------- /frontend/tests/unit/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: { 3 | jest: true 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /frontend/tests/unit/components/Breadcrumb.spec.js: -------------------------------------------------------------------------------- 1 | import { mount, createLocalVue } from '@vue/test-utils' 2 | import VueRouter from 'vue-router' 3 | import ElementUI from 'element-ui' 4 | import Breadcrumb from '@/components/Breadcrumb/index.vue' 5 | 6 | const localVue = createLocalVue() 7 | localVue.use(VueRouter) 8 | localVue.use(ElementUI) 9 | 10 | const routes = [ 11 | { 12 | path: '/', 13 | name: 'home', 14 | children: [{ 15 | path: 'dashboard', 16 | name: 'dashboard' 17 | }] 18 | }, 19 | { 20 | path: '/menu', 21 | name: 'menu', 22 | children: [{ 23 | path: 'menu1', 24 | name: 'menu1', 25 | meta: { title: 'menu1' }, 26 | children: [{ 27 | path: 'menu1-1', 28 | name: 'menu1-1', 29 | meta: { title: 'menu1-1' } 30 | }, 31 | { 32 | path: 'menu1-2', 33 | name: 'menu1-2', 34 | redirect: 'noredirect', 35 | meta: { title: 'menu1-2' }, 36 | children: [{ 37 | path: 'menu1-2-1', 38 | name: 'menu1-2-1', 39 | meta: { title: 'menu1-2-1' } 40 | }, 41 | { 42 | path: 'menu1-2-2', 43 | name: 'menu1-2-2' 44 | }] 45 | }] 46 | }] 47 | }] 48 | 49 | const router = new VueRouter({ 50 | routes 51 | }) 52 | 53 | describe('Breadcrumb.vue', () => { 54 | const wrapper = mount(Breadcrumb, { 55 | localVue, 56 | router 57 | }) 58 | it('dashboard', () => { 59 | router.push('/dashboard') 60 | const len = wrapper.findAll('.el-breadcrumb__inner').length 61 | expect(len).toBe(1) 62 | }) 63 | it('normal route', () => { 64 | router.push('/menu/menu1') 65 | const len = wrapper.findAll('.el-breadcrumb__inner').length 66 | expect(len).toBe(2) 67 | }) 68 | it('nested route', () => { 69 | router.push('/menu/menu1/menu1-2/menu1-2-1') 70 | const len = wrapper.findAll('.el-breadcrumb__inner').length 71 | expect(len).toBe(4) 72 | }) 73 | it('no meta.title', () => { 74 | router.push('/menu/menu1/menu1-2/menu1-2-2') 75 | const len = wrapper.findAll('.el-breadcrumb__inner').length 76 | expect(len).toBe(3) 77 | }) 78 | // it('click link', () => { 79 | // router.push('/menu/menu1/menu1-2/menu1-2-2') 80 | // const breadcrumbArray = wrapper.findAll('.el-breadcrumb__inner') 81 | // const second = breadcrumbArray.at(1) 82 | // console.log(breadcrumbArray) 83 | // const href = second.find('a').attributes().href 84 | // expect(href).toBe('#/menu/menu1') 85 | // }) 86 | // it('noRedirect', () => { 87 | // router.push('/menu/menu1/menu1-2/menu1-2-1') 88 | // const breadcrumbArray = wrapper.findAll('.el-breadcrumb__inner') 89 | // const redirectBreadcrumb = breadcrumbArray.at(2) 90 | // expect(redirectBreadcrumb.contains('a')).toBe(false) 91 | // }) 92 | it('last breadcrumb', () => { 93 | router.push('/menu/menu1/menu1-2/menu1-2-1') 94 | const breadcrumbArray = wrapper.findAll('.el-breadcrumb__inner') 95 | const redirectBreadcrumb = breadcrumbArray.at(3) 96 | expect(redirectBreadcrumb.contains('a')).toBe(false) 97 | }) 98 | }) 99 | -------------------------------------------------------------------------------- /frontend/tests/unit/components/Hamburger.spec.js: -------------------------------------------------------------------------------- 1 | import { shallowMount } from '@vue/test-utils' 2 | import Hamburger from '@/components/Hamburger/index.vue' 3 | describe('Hamburger.vue', () => { 4 | it('toggle click', () => { 5 | const wrapper = shallowMount(Hamburger) 6 | const mockFn = jest.fn() 7 | wrapper.vm.$on('toggleClick', mockFn) 8 | wrapper.find('.hamburger').trigger('click') 9 | expect(mockFn).toBeCalled() 10 | }) 11 | it('prop isActive', () => { 12 | const wrapper = shallowMount(Hamburger) 13 | wrapper.setProps({ isActive: true }) 14 | expect(wrapper.contains('.is-active')).toBe(true) 15 | wrapper.setProps({ isActive: false }) 16 | expect(wrapper.contains('.is-active')).toBe(false) 17 | }) 18 | }) 19 | -------------------------------------------------------------------------------- /frontend/tests/unit/components/SvgIcon.spec.js: -------------------------------------------------------------------------------- 1 | import { shallowMount } from '@vue/test-utils' 2 | import SvgIcon from '@/components/SvgIcon/index.vue' 3 | describe('SvgIcon.vue', () => { 4 | it('iconClass', () => { 5 | const wrapper = shallowMount(SvgIcon, { 6 | propsData: { 7 | iconClass: 'test' 8 | } 9 | }) 10 | expect(wrapper.find('use').attributes().href).toBe('#icon-test') 11 | }) 12 | it('className', () => { 13 | const wrapper = shallowMount(SvgIcon, { 14 | propsData: { 15 | iconClass: 'test' 16 | } 17 | }) 18 | expect(wrapper.classes().length).toBe(1) 19 | wrapper.setProps({ className: 'test' }) 20 | expect(wrapper.classes().includes('test')).toBe(true) 21 | }) 22 | }) 23 | -------------------------------------------------------------------------------- /frontend/tests/unit/utils/formatTime.spec.js: -------------------------------------------------------------------------------- 1 | import { formatTime } from '@/utils/index.js' 2 | 3 | describe('Utils:formatTime', () => { 4 | const d = new Date('2018-07-13 17:54:01') // "2018-07-13 17:54:01" 5 | const retrofit = 5 * 1000 6 | 7 | it('ten digits timestamp', () => { 8 | expect(formatTime((d / 1000).toFixed(0))).toBe('7月13日17时54分') 9 | }) 10 | it('test now', () => { 11 | expect(formatTime(+new Date() - 1)).toBe('刚刚') 12 | }) 13 | it('less two minute', () => { 14 | expect(formatTime(+new Date() - 60 * 2 * 1000 + retrofit)).toBe('2分钟前') 15 | }) 16 | it('less two hour', () => { 17 | expect(formatTime(+new Date() - 60 * 60 * 2 * 1000 + retrofit)).toBe('2小时前') 18 | }) 19 | it('less one day', () => { 20 | expect(formatTime(+new Date() - 60 * 60 * 24 * 1 * 1000)).toBe('1天前') 21 | }) 22 | it('more than one day', () => { 23 | expect(formatTime(d)).toBe('7月13日17时54分') 24 | }) 25 | it('format', () => { 26 | expect(formatTime(d, '{y}-{m}-{d} {h}:{i}')).toBe('2018-07-13 17:54') 27 | expect(formatTime(d, '{y}-{m}-{d}')).toBe('2018-07-13') 28 | expect(formatTime(d, '{y}/{m}/{d} {h}-{i}')).toBe('2018/07/13 17-54') 29 | }) 30 | }) 31 | -------------------------------------------------------------------------------- /frontend/tests/unit/utils/parseTime.spec.js: -------------------------------------------------------------------------------- 1 | import { parseTime } from '@/utils/index.js' 2 | 3 | describe('Utils:parseTime', () => { 4 | const d = new Date('2018-07-13 17:54:01') // "2018-07-13 17:54:01" 5 | it('timestamp', () => { 6 | expect(parseTime(d)).toBe('2018-07-13 17:54:01') 7 | }) 8 | it('ten digits timestamp', () => { 9 | expect(parseTime((d / 1000).toFixed(0))).toBe('2018-07-13 17:54:01') 10 | }) 11 | it('new Date', () => { 12 | expect(parseTime(new Date(d))).toBe('2018-07-13 17:54:01') 13 | }) 14 | it('format', () => { 15 | expect(parseTime(d, '{y}-{m}-{d} {h}:{i}')).toBe('2018-07-13 17:54') 16 | expect(parseTime(d, '{y}-{m}-{d}')).toBe('2018-07-13') 17 | expect(parseTime(d, '{y}/{m}/{d} {h}-{i}')).toBe('2018/07/13 17-54') 18 | }) 19 | it('get the day of the week', () => { 20 | expect(parseTime(d, '{a}')).toBe('五') // 星期五 21 | }) 22 | it('get the day of the week', () => { 23 | expect(parseTime(+d + 1000 * 60 * 60 * 24 * 2, '{a}')).toBe('日') // 星期日 24 | }) 25 | it('empty argument', () => { 26 | expect(parseTime()).toBeNull() 27 | }) 28 | }) 29 | -------------------------------------------------------------------------------- /frontend/tests/unit/utils/validate.spec.js: -------------------------------------------------------------------------------- 1 | import { validUsername, isExternal } from '@/utils/validate.js' 2 | 3 | describe('Utils:validate', () => { 4 | it('validUsername', () => { 5 | expect(validUsername('admin')).toBe(true) 6 | expect(validUsername('editor')).toBe(true) 7 | expect(validUsername('xxxx')).toBe(false) 8 | }) 9 | it('isExternal', () => { 10 | expect(isExternal('https://github.com/PanJiaChen/vue-element-admin')).toBe(true) 11 | expect(isExternal('http://github.com/PanJiaChen/vue-element-admin')).toBe(true) 12 | expect(isExternal('github.com/PanJiaChen/vue-element-admin')).toBe(false) 13 | expect(isExternal('/dashboard')).toBe(false) 14 | expect(isExternal('./dashboard')).toBe(false) 15 | expect(isExternal('dashboard')).toBe(false) 16 | }) 17 | }) 18 | -------------------------------------------------------------------------------- /frontend/vue.config.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const path = require('path') 3 | const defaultSettings = require('./src/settings.js') 4 | 5 | function resolve(dir) { 6 | return path.join(__dirname, dir) 7 | } 8 | 9 | const name = defaultSettings.title || 'Serverless Admin System' // page title 10 | 11 | // If your port is set to 80, 12 | // use administrator privileges to execute the command line. 13 | // For example, Mac: sudo npm run 14 | // You can change the port by the following methods: 15 | // port = 9528 npm run dev OR npm run dev --port = 9528 16 | const port = process.env.port || process.env.npm_config_port || 9528 // dev port 17 | 18 | // All configuration item explanations can be find in https://cli.vuejs.org/config/ 19 | module.exports = { 20 | /** 21 | * You will need to set publicPath if you plan to deploy your site under a sub path, 22 | * for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/, 23 | * then publicPath should be set to "/bar/". 24 | * In most cases please use '/' !!! 25 | * Detail: https://cli.vuejs.org/config/#publicpath 26 | */ 27 | publicPath: '/', 28 | outputDir: 'dist', 29 | assetsDir: 'static', 30 | lintOnSave: process.env.NODE_ENV === 'development', 31 | productionSourceMap: false, 32 | devServer: { 33 | port: port, 34 | open: true, 35 | overlay: { 36 | warnings: false, 37 | errors: true 38 | } 39 | }, 40 | configureWebpack: { 41 | // provide the app's title in webpack's name field, so that 42 | // it can be accessed in index.html to inject the correct title. 43 | name: name, 44 | resolve: { 45 | alias: { 46 | '@': resolve('src') 47 | } 48 | } 49 | }, 50 | chainWebpack(config) { 51 | config.plugins.delete('preload') // TODO: need test 52 | config.plugins.delete('prefetch') // TODO: need test 53 | 54 | // set svg-sprite-loader 55 | config.module 56 | .rule('svg') 57 | .exclude.add(resolve('src/icons')) 58 | .end() 59 | config.module 60 | .rule('icons') 61 | .test(/\.svg$/) 62 | .include.add(resolve('src/icons')) 63 | .end() 64 | .use('svg-sprite-loader') 65 | .loader('svg-sprite-loader') 66 | .options({ 67 | symbolId: 'icon-[name]' 68 | }) 69 | .end() 70 | 71 | // set preserveWhitespace 72 | config.module 73 | .rule('vue') 74 | .use('vue-loader') 75 | .loader('vue-loader') 76 | .tap(options => { 77 | options.compilerOptions.preserveWhitespace = true 78 | return options 79 | }) 80 | .end() 81 | 82 | config 83 | // https://webpack.js.org/configuration/devtool/#development 84 | .when(process.env.NODE_ENV === 'development', config => 85 | config.devtool('cheap-source-map') 86 | ) 87 | 88 | config.when(process.env.NODE_ENV !== 'development', config => { 89 | config 90 | .plugin('ScriptExtHtmlWebpackPlugin') 91 | .after('html') 92 | .use('script-ext-html-webpack-plugin', [ 93 | { 94 | // `runtime` must same as runtimeChunk name. default is `runtime` 95 | inline: /runtime\..*\.js$/ 96 | } 97 | ]) 98 | .end() 99 | config.optimization.splitChunks({ 100 | chunks: 'all', 101 | cacheGroups: { 102 | libs: { 103 | name: 'chunk-libs', 104 | test: /[\\/]node_modules[\\/]/, 105 | priority: 10, 106 | chunks: 'initial' // only package third parties that are initially dependent 107 | }, 108 | elementUI: { 109 | name: 'chunk-elementUI', // split elementUI into a single package 110 | priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app 111 | test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm 112 | }, 113 | commons: { 114 | name: 'chunk-commons', 115 | test: resolve('src/components'), // can customize your rules 116 | minChunks: 3, // minimum common number 117 | priority: 5, 118 | reuseExistingChunk: true 119 | } 120 | } 121 | }) 122 | config.optimization.runtimeChunk('single') 123 | }) 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "serverless-admin-system", 3 | "version": "0.1.0", 4 | "scripts": { 5 | "bootstrap": "node scripts/bootstrap.js", 6 | "docker:up": "cd backend && npm run docker:up", 7 | "dev:be": "cd backend && npm run dev", 8 | "dev:fe": "cd frontend && npm run dev", 9 | "deploy": "serverless deploy --all", 10 | "deploy:fe": "serverless deploy --target=./frontend", 11 | "deploy:be": "serverless deploy --target=./backend", 12 | "deploy:be:layer": "serverless deploy --target=./backend/layer", 13 | "deploy:db": "serverless deploy --target=./db", 14 | "deploy:vpc": "serverless deploy --target=./vpc" 15 | }, 16 | "license": "MIT", 17 | "description": "Admin system developed by [Serverless Components](https://github.com/serverless/components)", 18 | "keywords": [ 19 | "admin-system", 20 | "serverless", 21 | "serverless-framework", 22 | "serverless-components" 23 | ], 24 | "author": "yugasun", 25 | "main": "index.js", 26 | "dependencies": {}, 27 | "devDependencies": {}, 28 | "repository": { 29 | "type": "git", 30 | "url": "git+https://github.com/serverless-plus/serverless-admin-system.git" 31 | }, 32 | "bugs": { 33 | "url": "https://github.com/serverless-plus/serverless-admin-system/issues" 34 | }, 35 | "homepage": "https://github.com/serverless-plus/serverless-admin-system#readme" 36 | } 37 | -------------------------------------------------------------------------------- /scripts/bootstrap.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const path = require('path') 4 | const util = require('util') 5 | const exec = util.promisify(require('child_process').exec) 6 | 7 | const rootDir = path.join(__dirname, '..') 8 | const apiDir = path.join(rootDir, 'backend') 9 | const frontendDir = path.join(rootDir, 'frontend') 10 | 11 | async function installDependencies(dir) { 12 | await exec('npm install', { 13 | cwd: dir 14 | }) 15 | } 16 | 17 | /* eslint-disable no-console*/ 18 | async function bootstrap() { 19 | console.log('Start install dependencies...\n') 20 | await installDependencies(rootDir) 21 | console.log('Root dependencies installed success.') 22 | await installDependencies(apiDir) 23 | console.log('Backend dependencies installed success.') 24 | await installDependencies(frontendDir) 25 | console.log('Frontend dependencies installed success.') 26 | console.log('All dependencies installed.') 27 | } 28 | 29 | bootstrap() 30 | 31 | process.on('unhandledRejection', (e) => { 32 | throw e 33 | }) 34 | -------------------------------------------------------------------------------- /serverless.template.yml: -------------------------------------------------------------------------------- 1 | name: admin-system 2 | author: Serverless Plus 3 | org: Serverless Plus 4 | description: Deploy an admin system application 5 | description-i18n: 6 | zh-cn: 快速部署一个基于后台管理系统, egg.js + postgres + vue.js 7 | keywords: tencent, serverless, egg.js, vue.js, postgresql 8 | repo: https://github.com/serverless-plus/serverless-admin-system/tree/master 9 | readme: https://github.com/serverless-plus/serverless-admin-system/tree/master/README.md 10 | license: MIT 11 | src: 12 | src: ./ 13 | exclude: 14 | - '.env' 15 | - '.git/**' 16 | - '**/node_modules' 17 | - '**/package-lock.json' 18 | - '**/yarn.lock' 19 | - '.DS_Store' 20 | include: 21 | - '.env.example' 22 | -------------------------------------------------------------------------------- /vpc/serverless.yml: -------------------------------------------------------------------------------- 1 | org: slsplus 2 | app: admin-system 3 | stage: dev 4 | 5 | component: vpc 6 | name: admin-system-vpc 7 | 8 | inputs: 9 | region: ${env:REGION} 10 | zone: ${env:ZONE} 11 | vpcName: ${name} 12 | subnetName: ${name} 13 | --------------------------------------------------------------------------------