12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- const Koa = require('koa');
- const route = require('koa-route');
- const fs = require('fs')
- const app = new Koa();
- // sessions
- const session = require('koa-session')
- app.keys = ['your-session-secret']
- app.use(session({}, app))
- // body parser
- const bodyParser = require('koa-bodyparser')
- app.use(bodyParser())
- // authentication
- require('./auth')
- const passport = require('koa-passport')
- app.use(passport.initialize())
- app.use(passport.session())
- app.use(route.get("/default", (ctx) => {
- ctx.body = "default route";
- }))
- app.use(route.get("/", (ctx) => {
- ctx.body = "hello Koa default";
- }))
- app.use(route.get("/pleaselogin", (ctx) => {
- ctx.body = "please login"
- }))
- app.use(route.get("/login", (ctx) => {
- ctx.type = 'html'
- ctx.body = fs.createReadStream('views/login.html')
- }))
- app.use(route.get('/app', function (ctx) {
- if (ctx.isAuthenticated()) {
- ctx.type = 'html'
- ctx.body = fs.createReadStream('views/app.html')
- } else {
- ctx.redirect('/pleaselogin')
- }
- }))
- app.use(route.get("/whois", (ctx) => {
- if (ctx.isAuthenticated()) {
- var jsonFull = ctx.session.toJSON()
- var text = "User name " + jsonFull.passport.user + "\n"
- text = text + "json: \n" + JSON.stringify(jsonFull)
- ctx.body = text
- } else {
- ctx.redirect('/pleaselogin')
- }
- }))
- // app.use(route.get("/deser", passport.deserializeUser()))
- // POST /login
- // application/x-www-form-urlencoded
- app.use(route.post('/login',
- passport.authenticate('local', {
- successRedirect: '/app',
- failureRedirect: '/'
- })
- ))
- app.use(route.get('/hello', (ctx) => {
- ctx.type = 'application/json'
- ctx.body = { "info": "I am pusheen the cat." }
- }))
- app.use(route.get('/api/hello', (ctx) => {
- ctx.type = 'application/json'
- ctx.body = { "info": "This is api hello. I am pusheen the cat." }
- }))
- app.use(route.get('/logout'), (ctx) => {
- ctx.logout()
- ctx.redirect('/login')
- })
- app.listen(3000);
|