Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/kblog');
mongoose.connection.on('error', console.error.bind(console, '连接数据库失败'));
// config static dir
app.use(staticServer(__dirname + '/public'));
// nunjucks config
app.use(nunjucks('app/views', {
noCache: process.env.NODE_ENV === 'production',
watch: ! process.env.NODE_ENV === 'production'
}));
// session
app.keys = ['some secret hurr'];
app.use(session(app));
// body parser
app.use(bodyParser());
// routes
routes(app);
// catch 404
app.use(function *(next) {
let self = this;
if (this.status === 404) {
yield this.render('page/404.html', {
user: self.session.user,
});
}
yield next;
import dotenv from 'dotenv';
import Koa from 'koa';
import session from 'koa-session';
import createShopifyAuth, {
createVerifyRequest,
} from '@shopify/koa-shopify-auth';
import renderReactApp from './render-react-app';
import webpack from 'koa-webpack';
import graphQLProxy from '@shopify/koa-shopify-graphql-proxy';
dotenv.config();
const {SHOPIFY_API_KEY, SHOPIFY_SECRET} = process.env;
const app = new Koa();
app.use(session(app));
app.use(
createShopifyAuth({
// your shopify app's api key
apiKey: SHOPIFY_API_KEY,
// your shopify app's api secret
secret: SHOPIFY_SECRET,
// our app's permissions
// we need to write products to the user's store
scopes: ['write_products'],
// our own custom logic after authentication has completed
afterAuth(ctx) {
const {shop, accessToken} = ctx.session;
console.log('We did it!', shop, accessToken);
import routes from './routes';
import { renderReact } from './render';
const app = new Koa();
// Use native promises
mongoose.Promise = global.Promise;
mongoose.connect(process.env.MONGODB_URI);
mongoose.connection.on('error', console.error.bind(console, '连接数据库失败'));
app.use(bodyParser());
// session
app.keys = ['forever'];
app.use(convert(session(app)));
app.use(views('../../views'));
app.use(async (ctx, next) => {
await send(ctx, ctx.path, { root: path.resolve(__dirname, '../../static') });
if (ctx.status === 404) {
await next();
}
});
routes(app);
app.use(renderReact);
app.listen(8080, () => console.log('Server is running on 8080'));
export const securityLayer = (app: Object) => {
app.keys = [process.env.SECRET_KEY];
const csrf = new CSRF();
app
.use(session({ maxAge: 86400000 }, app)) // https://github.com/koajs/session
.use((ctx, next) => {
// don't check csrf for request coming from the server
if (ctx.get("x-app-secret") === process.env.SECRET_KEY) {
return next();
}
return csrf(ctx, next);
}) // https://github.com/koajs/csrf
.use(helmet()); // https://github.com/venables/koa-helmet
};
// 3. respect transacted settings, create and handle transactions.
this.use(createTransaction())
// 4. session
if (app.session) {
const {
modelClass,
...options
} = isObject(app.session) ? app.session : {}
if (modelClass) {
// Create a ContextStore that resolved the specified model class,
// uses it to persist and retrieve the session, and automatically
// binds all db operations to `ctx.transaction`, if it is set.
// eslint-disable-next-line new-cap
options.ContextStore = SessionStore(modelClass)
}
this.use(session(options, this))
}
// 5. passport
if (app.passport) {
this.use(passport.initialize())
if (app.session) {
this.use(passport.session())
}
this.use(emitUserEvents())
}
// 6. finally handle the found route, or set status / allow accordingly.
this.use(handleRoute())
this.hasControllerMiddleware = true
}
}
// 生产环境启用https
let options = null;
if(IS_HTTPS == 'TRUE'){
// Force HTTPS on all page
app.use(enforceHttps())
options = {
key: fs.readFileSync(path.resolve(__dirname, './assets/cert/214545337340023.key')),
cert: fs.readFileSync(path.resolve(__dirname, './assets/cert/214545337340023.pem'))
}
}
app
.use(cookie())
.use(session(app))
.use(KoaBody({
multipart: true,
formidable: {
uploadDir: path.join(__dirname, '/upload')
}
}))
.use(serve(__dirname + "/assets",{
maxage: 365 * 24 * 60 * 60
}))
.use(koa2Common())
.use(cors({
origin: SYSTEM.ORIGIN,
headers: 'Origin, X-Requested-With, Content-Type, Accept',
methods: ['GET', 'PUT', 'POST'],
credentials: true,
}))
it('handles koa-session for GraphQL', async () => {
const app = new koa();
app.keys = [ 'my secret' ];
app.use(convert(session(app)));
app.use(async (ctx,next) => {
ctx.session.id = 'first';
await next();
});
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'sessionType',
fields: {
sessionId: {
type: GraphQLString,
resolve(parentValue, args, contextCtx) {
//here only session.id="first"
//console.log("contextCtx.session is------->",contextCtx.session)
return contextCtx.session.id;
}
}
import Koa = require('koa');
import session = require('koa-session');
import * as ContextSession from "koa-session/lib/context";
import {
encode,
decode,
hash,
} from "koa-session/lib/util";
encode({ a: "b" });
decode("123");
hash("abc");
const app = new Koa();
app.use(session({
valid: (ctx, sess) => {
const { session: s } = ctx;
if (s) {
s.sess = "validated";
s.save();
return true;
}
return false;
},
store: {
import Koa = require('koa');
import session = require('koa-session');
import * as ContextSession from "koa-session/lib/context";
import {
encode,
decode,
hash,
} from "koa-session/lib/util";
encode({ a: "b" });
decode("123");
hash("abc");
const app = new Koa();
app.use(session({
valid: (ctx, sess) => {
const { session: s } = ctx;
if (s) {
s.sess = "validated";
s.save();
return true;
}
return false;
},
store: {
get: async (key) => {
return "abc";
connectMongo().then(() => {
const app = new Koa()
app.use(logger())
app.use(bodyParser())
app.keys = ['davinci']
app.use(
session(
{
key: 'koa:sess',
maxAge: 86400000,
overwrite: true,
httpOnly: true,
signed: true,
rolling: false,
},
app
)
)
app.use(serve(resolve(__dirname, '../static')))
routes(app)
app.listen(8080, () => console.log('Server is running on 8080'))
})