forked from zywcode/technode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
122 lines (101 loc) · 2.39 KB
/
server.js
File metadata and controls
122 lines (101 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
var koa = require('koa')
, app = koa()
// sessions
var session = require('koa-sess')
var redisStore = require('koa-redis')
app.keys = ['hive']
app.use(session({
store: redisStore()
}))
// body parser
var bodyParser = require('koa-bodyparser')
app.use(bodyParser())
// authentication
require('./auth')
var passport = require('koa-passport')
app.use(passport.initialize())
app.use(passport.session())
// append view renderer
var views = require('koa-render')
app.use(views('./views', {
map: { html: 'handlebars' },
cache: false
}))
var Router = require('koa-router')
// API
var APIRouter = new Router()
var API = require('./api')
var methodMap = {
'POST': 'create',
'PUT': 'update',
'PATCH': 'patch',
'DELETE': 'delete',
'GET': 'read'
}
APIRouter.register('/api/:resources', ['get', 'post'], function *(next) {
var resources = this.params.resources
try {
this.body = yield API[resources][methodMap[this.method]]()
} catch (e) {
this.throw(e)
}
})
APIRouter.register('/api/:resources/:id', ['get', 'put', 'delete'], function *(next) {
var resources = this.params.resources,
id = this.params.id
try {
this.body = yield API[resources][methodMap[this.method]](id)
} catch (e) {
this.throw(e)
}
})
app.use(APIRouter.middleware())
// public routes
var public = new Router()
public.get('/login', function*() {
this.body = yield this.render('login')
})
// POST /login
public.post('/login',
passport.authenticate('local', {
successRedirect: '/app',
failureRedirect: '/'
})
)
public.get('/logout', function*(next) {
this.logout()
this.redirect('/')
})
public.get('/auth/douban',
passport.authenticate('douban')
)
public.get('/auth/douban/callback',
passport.authenticate('douban', {
successRedirect: '/',
failureRedirect: '/login'
})
)
app.use(public.middleware())
// Require authentication for now
var send = require('koa-send')
app.use(function *(next) {
if (this.isAuthenticated()) {
yield next
if (this.body == null) {
yield send(this, __dirname + '/static/index.html')
}
} else {
this.redirect('/login')
}
})
// satatic
var serve = require('koa-static')
app.use(serve(__dirname + '/static'))
//sockjs
var sockjs = require('sockjs').createServer(),
server = require('http').createServer(app.callback())
sockjs.installHandlers(server, {
prefix: '/sockjs'
})
// start server
server.listen(process.env.PORT || 3000)