Skip to content

Commit e70ddf6

Browse files
committed
添加服务端鉴权模拟
1 parent 076bc60 commit e70ddf6

File tree

12 files changed

+299
-15
lines changed

12 files changed

+299
-15
lines changed

app.js

+9-4
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,21 @@ const convert = require('koa-convert');
1010
const cors = require('koa-cors');
1111
const serve = require('koa-static-server');
1212
const bodyParser = require('koa-bodyparser');
13+
const authMiddleware = require('./middleware/auth.js');
1314

15+
let isDev = process.env.NODE_ENV === 'develop'; // 是否是开发环境
16+
17+
app.use(authMiddleware);
1418
app.use(bodyParser());
15-
// app.use(async (ctx, next) => {
16-
// console.log(ctx.request.body, ctx.path, 'ppp');
17-
// await next();
18-
// });
1919
app.use(convert(cors()));
2020
const router = require('./router')(app);
2121
app.use(serve({rootDir: path.join(__dirname, './static'), rootPath: '/static'}));
2222

23+
// 线上发布的
24+
if (!isDev) {
25+
app.use(serve({rootDir: path.join(__dirname, './dist'), rootPath: '/'})); // 在router之后要注意
26+
}
27+
2328
app.listen(port, () => {
2429
console.log(`earlyjoy已经启动,监听${port}端口`);
2530
});

client/container/login/login.jsx

+76-4
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,88 @@
11
import './login.scss';
2+
import 'weui';
3+
import ReactDOM from 'react-dom';
24
import React, { Component } from 'react';
5+
import { ajax } from '../../util/index.js';
36

4-
export default class extends Component {
7+
let Login = class extends Component {
58
constructor () {
69
super();
10+
this.state = {
11+
username: null,
12+
password: null
13+
}
14+
}
15+
16+
userNameHandler (e) {
17+
let username = e.target.value;
18+
this.setState({ username });
19+
}
20+
21+
passwordHandler (e) {
22+
let password = e.target.value;
23+
this.setState({ password });
24+
}
25+
26+
loginHandler () {
27+
let { username, password } = this.state;
28+
29+
if ( username && password ) {
30+
ajax({
31+
url: 'http://localhost:8333/login',
32+
method: 'post',
33+
data: { username, password }
34+
}).then((val) => {
35+
location.href = 'http://localhost:8333';
36+
}).catch((err) => {
37+
console.log(err);
38+
});
39+
} else {
40+
alert('请输入账号密码');
41+
}
742
}
843

944
render () {
1045
return (
11-
<div>
12-
login
46+
<div className="login-page">
47+
<div className="login-title">
48+
<h3>登陆早起打卡</h3>
49+
</div>
50+
<div className="weui-cells__title">账号</div>
51+
<div className="weui-cells">
52+
<div className="weui-cell">
53+
<div className="weui-cell__bd">
54+
<input type="text" className="weui-input"
55+
placeholder="请输入账号"
56+
onChange={this.userNameHandler.bind(this)}
57+
/>
58+
</div>
59+
</div>
60+
</div>
61+
62+
<div className="weui-cells__title">密码</div>
63+
<div className="weui-cells">
64+
<div className="weui-cell">
65+
<div className="weui-cell__bd">
66+
<input type="password" className="weui-input"
67+
placeholder="请输入账号"
68+
onChange={this.passwordHandler.bind(this)}
69+
/>
70+
</div>
71+
</div>
72+
</div>
73+
74+
<div className="weui-btn-area">
75+
<a className="weui-btn weui-btn_primary"
76+
onClick={this.loginHandler.bind(this)}
77+
>
78+
确定
79+
</a>
80+
</div>
1381
</div>
1482
)
1583
}
16-
}
84+
};
85+
86+
ReactDOM.render(<Login/>, document.querySelector('.doc'));
87+
88+

client/container/login/login.scss

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
* {
2+
margin: 0;
3+
padding: 0;
4+
}
5+
6+
body {
7+
background-color: #f8f8f8;
8+
}
9+
10+
.login-page {
11+
12+
}
13+
14+
.login-title {
15+
height: 50px;
16+
background-color: #fff;
17+
display: flex;
18+
align-items: center;
19+
justify-content: center;
20+
color: #666;
21+
}

client/template/login.html

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<!DOCTYPE html>
2+
<html lang="zh">
3+
<head>
4+
<meta charset="UTF-8">
5+
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
6+
<title>登陆</title>
7+
<link rel="icon" href="data:;base64,=">
8+
</head>
9+
<body>
10+
<div class="doc"></div>
11+
</body>
12+
</html>

client/webpack.config.js

+17-4
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,18 @@
44
const webpack = require('webpack');
55
const path = require('path');
66
const HtmlWebpackPlugin = require('html-webpack-plugin');
7+
let isDev = process.env.NODE_ENV === 'develop'; // 是否是开发环境
78

89
module.exports = {
910
entry: {
1011
vendor: ['babel-polyfill', 'react', 'react-dom', 'redux', 'react-redux', 'react-router-dom'],
11-
main: './index.js'
12+
main: './index.js',
13+
login: './container/login/login.jsx'
1214
},
1315
output: {
1416
path: path.resolve(__dirname, '../dist'),
15-
publicPath: '/',
17+
// publicPath: '/',
18+
publicPath: isDev ? 'http://localhost:9333/' : '/',
1619
filename: '[name].bundle.js'
1720
},
1821
module: {
@@ -34,11 +37,14 @@ module.exports = {
3437
},
3538
extensions: ['.js', '.jsx']
3639
},
37-
devtool: 'cheap-module-eval-source-map',
40+
devtool: isDev ? 'cheap-module-eval-source-map' : '',
3841
context: __dirname,
3942
devServer: {
4043
hot: true,
41-
port: 9333
44+
port: 9333,
45+
headers: {
46+
'Access-Control-Allow-Origin': '*'
47+
}
4248
},
4349
plugins: [
4450
new webpack.HotModuleReplacementPlugin(),
@@ -50,6 +56,13 @@ module.exports = {
5056
new HtmlWebpackPlugin({
5157
template: './template/index.html',
5258
filename: 'index.html',
59+
chunks: ['vendor', 'main'],
60+
inject: true
61+
}),
62+
new HtmlWebpackPlugin({
63+
template: './template/login.html',
64+
filename: 'login.html',
65+
chunks: ['vendor', 'login'],
5366
inject: true
5467
})
5568
]

ecosystem.config.js

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
module.exports = {
2+
/**
3+
* Application configuration section
4+
* http://pm2.keymetrics.io/docs/usage/application-declaration/
5+
*/
6+
apps : [
7+
8+
// First application
9+
{
10+
name : 'API',
11+
script : 'app.js',
12+
env: {
13+
COMMON_VARIABLE: 'true'
14+
},
15+
env_production : {
16+
NODE_ENV: 'production'
17+
}
18+
}
19+
20+
// Second application
21+
]
22+
23+
/**
24+
* Deployment section
25+
* http://pm2.keymetrics.io/docs/usage/deployment/
26+
*/
27+
// deploy : {
28+
// production : {
29+
// user : 'node',
30+
// host : '212.83.163.1',
31+
// ref : 'origin/master',
32+
// repo : '[email protected]:repo.git',
33+
// path : '/var/www/production',
34+
// 'post-deploy' : 'npm install && pm2 reload ecosystem.config.js --env production'
35+
// },
36+
// dev : {
37+
// user : 'node',
38+
// host : '212.83.163.1',
39+
// ref : 'origin/master',
40+
// repo : '[email protected]:repo.git',
41+
// path : '/var/www/development',
42+
// 'post-deploy' : 'npm install && pm2 reload ecosystem.config.js --env dev',
43+
// env : {
44+
// NODE_ENV: 'dev'
45+
// }
46+
// }
47+
// }
48+
};

middleware/auth.js

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
/**
2+
* Created by Weil on 2017/6/3.
3+
*/
4+
module.exports = async (ctx, next) => {
5+
let whiteList = ['/login', '/login.html'];
6+
7+
if (!whiteList.includes(ctx.path)) {
8+
let earlyToken = ctx.cookies.get('earlytoken');
9+
console.log(earlyToken, 'earlyToken');
10+
if ( !earlyToken ) {
11+
ctx.redirect('http://localhost:8333/login.html');
12+
}
13+
}
14+
15+
await next();
16+
};

package.json

+7-3
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,12 @@
44
"description": "",
55
"main": "index.js",
66
"scripts": {
7-
"test": "echo \"Error: no test specified\" && exit 1",
8-
"dev": "cd client && webpack-dev-server",
9-
"start": "nodemon app.js"
7+
"dev": "cd client && NODE_ENV=develop webpack-dev-server",
8+
"build": "cd client && NODE_ENV=production webpack -p",
9+
"node": "NODE_ENV=develop nodemon app.js",
10+
"start": "NODE_ENV=production node app.js",
11+
"publish": "pm2 startOrRestart pm2.prod.config.js",
12+
"p": "pm2 startOrRestart ecosystem.config.js"
1013
},
1114
"keywords": [],
1215
"author": "",
@@ -21,6 +24,7 @@
2124
"koa-router": "^7.1.1",
2225
"koa-static-server": "^1.2.1",
2326
"lodash.clonedeep": "^4.5.0",
27+
"node-fetch": "^1.7.0",
2428
"prop-types": "^15.5.10",
2529
"react": "^15.5.4",
2630
"react-dom": "^15.5.4",

pm2.prod.config.js

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
module.exports = {
2+
/**
3+
* Application configuration section
4+
* http://pm2.keymetrics.io/docs/usage/application-declaration/
5+
*/
6+
apps : [
7+
8+
// First application
9+
{
10+
name : 'earlyJoy',
11+
script : 'app.js',
12+
env: {
13+
COMMON_VARIABLE: 'true'
14+
},
15+
env_production : {
16+
NODE_ENV: 'production'
17+
}
18+
}
19+
20+
// Second application
21+
]
22+
23+
/**
24+
* Deployment section
25+
* http://pm2.keymetrics.io/docs/usage/deployment/
26+
*/
27+
// deploy : {
28+
// production : {
29+
// user : 'node',
30+
// host : '212.83.163.1',
31+
// ref : 'origin/master',
32+
// repo : '[email protected]:repo.git',
33+
// path : '/var/www/production',
34+
// 'post-deploy' : 'npm install && pm2 reload ecosystem.config.js --env production'
35+
// },
36+
// dev : {
37+
// user : 'node',
38+
// host : '212.83.163.1',
39+
// ref : 'origin/master',
40+
// repo : '[email protected]:repo.git',
41+
// path : '/var/www/development',
42+
// 'post-deploy' : 'npm install && pm2 reload ecosystem.config.js --env dev',
43+
// env : {
44+
// NODE_ENV: 'dev'
45+
// }
46+
// }
47+
// }
48+
};

router/index.js

+5
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
11
const Router = require('koa-router');
22
const router = new Router();
33
const api = require('./api.js');
4+
const page = require('./page.js');
5+
const login = require('./login.js');
6+
7+
page(router);
48
api(router);
9+
login(router);
510

611
module.exports = (app) => {
712
app.use(router.routes())

router/login.js

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
/**
2+
* Created by Weil on 2017/6/3.
3+
*/
4+
module.exports = (router) => {
5+
router.post('/login', (ctx, next) => {
6+
ctx.cookies.set('earlytoken', 'imnolyaearlyjoytoken', {
7+
maxAge: 1000*60*60*2
8+
});
9+
ctx.body = {
10+
status: true
11+
};
12+
})
13+
};

router/page.js

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
const fs = require('fs');
2+
const path = require('path');
3+
const fetch = require('node-fetch');
4+
let isDev = process.env.NODE_ENV === 'develop';
5+
6+
module.exports = (router) => {
7+
router.get('/', async (ctx, next) => {
8+
if ( isDev ) {
9+
let res = await fetch('http://localhost:9333');
10+
ctx.body = await res.text();
11+
} else {
12+
ctx.body = fs.readFileSync(path.join(__dirname, '../dist/index.html'), 'utf-8');
13+
}
14+
});
15+
16+
router.get('/login.html', async (ctx, next) => {
17+
if ( isDev ) {
18+
let res = await fetch('http://localhost:9333/login.html');
19+
ctx.body = await res.text();
20+
} else {
21+
ctx.body = fs.readFileSync(path.join(__dirname, '../dist/login.html'), 'utf-8');
22+
}
23+
});
24+
};
25+
26+
27+
// console.log(process.env.NODE_ENV);

0 commit comments

Comments
 (0)