當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript express-session類代碼示例

本文整理匯總了TypeScript中express-session的典型用法代碼示例。如果您正苦於以下問題:TypeScript express-session類的具體用法?TypeScript express-session怎麽用?TypeScript express-session使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了express-session類的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: express

import { DKYSessionHandler } from "./session";
import * as session from "express-session";
import { logger, errorLogger } from "./logger";

var app: express.Application = express();

app.use(logger());

app.use(helmet());

//app.use(DKYSessionHandler());

app.use(session({
    name: 'app.sid',
    secret: "1234567890QWERTY",
    resave: true,
    store: new session.MemoryStore(),
    saveUninitialized: true
}));

app.use(bodyParser.urlencoded({ extended: true }));

app.use(bodyParser.json());

app.use(methodOverride());

app.use(express.static(__dirname + "/../public"));

app.use("/", router());

app.use(errorLogger());
開發者ID:nicholas-robson,項目名稱:dkydev_webapp,代碼行數:31,代碼來源:app.ts

示例2: express

import * as express from 'express';
import * as mongoose from 'mongoose';
import * as session from 'express-session';
import * as connectMongo from 'connect-mongo';
import * as mongodb from 'mongodb';

var app = express();

/// Create MongoStore
var MongoStore = connectMongo(session);

/// Use MongoStore

// MongoUrlOptions
app.use(session({
    secret: 'secret',
    store: new MongoStore({url: 'mongodb://localhost/test'})
}));


app.use(session({
    secret: 'secret',
    store: new MongoStore({
        url: 'mongodb://localhost/test',
        collection: "test-sessions",
        ttl: 30 * 24 * 60 * 60 // = 30 days
    })
}));

// MongooseConnectionOptions
mongoose.connect('mongodb://localhost/test')
app.use(session({
開發者ID:AbraaoAlves,項目名稱:DefinitelyTyped,代碼行數:32,代碼來源:connect-mongo-tests.ts

示例3: Routes

var RDBStore = require('session-rethinkdb')(session);
var RDBStoreOptions = _.merge({}, dbConfig, { cleanupInterval: 5000 });
var sessionStore = { store: new RDBStore(RDBStoreOptions) };

process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var clientBaseUrl = require('config').get('clientBaseUrl');
var port = process.env.PORT || 3333;
var app = express();
var server = http.Server(app);
var io = require('socket.io')(server);

winstonConfiguration();
app.use(cookieParser());
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(session(_.merge({}, sessionConfig, sessionStore)));
app.use(cors());

app.use(express.static(path.join(__dirname, 'public')));

new Routes(app, express.Router());
new Sockets(io);

game.register();
category.register();

server.listen(port, function() {
  winston.info('listening on port:' + port + '; NODE_ENV='+ process.env.NODE_ENV);
});

function winstonConfiguration() {
開發者ID:radotzki,項目名稱:bullshit-server,代碼行數:31,代碼來源:app.ts

示例4: express

import * as routes from './routes/index';

const app = express();

// view engine setup

app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
  secret: 'somesecret',
  resave: true,
  saveUninitialized: true
}));
app.use(express.static(path.join(__dirname, '../public')));
app.use('/lib',express.static(path.join(__dirname, '../node_modules')));
app.use('/app',express.static(path.join(__dirname, '../app')));
app.use('/css',express.static(path.join(__dirname, '../public/assets/css')));
app.use('/js',express.static(path.join(__dirname, '../public/assets/js')));
app.use('/config',express.static(path.join(__dirname, '../config')));

app.use('/', routes);

let port: number = process.env.PORT || 3000;

let server = app.listen(port, function() {
    let host = server.address().address;
開發者ID:delpiero22,項目名稱:KM-RAOT,代碼行數:31,代碼來源:server.ts

示例5: join

// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();

// Config
const CONFIG_FOLDER = join(process.cwd(), 'config');
const config = require(join(CONFIG_FOLDER, 'amazon.json'));

// Express server
const app = express();

// Basic express session
app.use(
  session({
    secret: config.session.secret,
    saveUninitialized: false,
    resave: true
  })
);

// For jwt token errors
app.use((err, req, res, next) => {
  if (err.name === 'StatusError') {
    res.send(err.status, err.message);
  } else {
    next(err);
  }
});

const jwtCheck = jwtExpress({
  secret: config.jwt.secret
開發者ID:sumanbh,項目名稱:amazon-clone,代碼行數:30,代碼來源:server.ts

示例6: require

//custom module import
let index : express.Router  = require('./routes/indexRoute');

//server configuration
let app   : express.Express = express();
let port  : number          = process.env.PORT || 3000;
mongoose.connect('mongodb://localhost/quiz-app');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

//builtin middleware
app.use(express.static(path.join(__dirname, '../public')));

//third party middleware
app.use(morgan('dev'));
app.use(cookieParser('fulloffunwithcodingjsints'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(session({secret: 'fulloffunwithcodingjsints'}));
app.use(flash());

//custom mounted middleware for routing
app.use('/', index);

//start server
app.listen(port, () => {
  console.log('Express started on Port : ' + port);
});
開發者ID:asimbhai,項目名稱:quiz-app,代碼行數:30,代碼來源:server.ts

示例7: done

        .then((app) => {
            app.set('view options', {pretty: false});
            app.set("etag", false);
            app.disable("x-powered-by");

            app.engine("dust", cons.dust);

            app.set("views", __dirname + "/../views");
            app.set("view engine", "dust");

            app.use(express.static(__dirname + "/../public"));

            passport.use(new LocalStrategy(
                function(username, password, done) {
                    storageManager.getAccountByEmail(username)
                        .then((account:any) => {
                            if (account === null) {
                                return done(null, false, { message: 'Incorrect account.' });
                            }
                            if (compareSync(password, account.password)) {
                                return done(null, account);
                            }
                            return done(null, false, { message: 'Incorrect password.' });
                        })
                        .catch((err:any) => {
                            console.log(err);
                            return done(null, false, { message: 'Internal error.' });
                        });
                }
            ));

            passport.serializeUser(function(account, done) {
                done(null, account.id);
            });

            passport.deserializeUser(function(id, done) {
                storageManager.getAccountById(id)
                    .then((account:any) => {
                        if (account !== undefined) {
                            return done(null, account);
                        }
                        return done(new Error("Invalid account"), null)
                    })
                    .catch((err:any) => {
                        done(err, null);
                    });
            });

            app.use(methodOverride());
            app.use(bodyParser.json());
            app.use(bodyParser.urlencoded({extended: false}));

            app.use(cookieParser());
            app.use(session({ secret: 'keyboard cat' }));
            app.use(passport.initialize());
            app.use(passport.session());

            app.use(flash());

            app.use((req:express.Request, res:express.Response, next:express.NextFunction) => {
                logger.info({method: req.method, url: req.url, protocol: req.protocol, ip: req.ip, hostname: req.hostname}, req.method + " " + req.path);
                next();
            });

            return app;
        });
開發者ID:JesseDavid,項目名稱:express-typescript-sequelize,代碼行數:66,代碼來源:index.ts

示例8: start

export default function start(serverDataPath: string) {
  dataPath = serverDataPath;
  SupCore.log(`Using data from ${dataPath}.`);
  process.on("uncaughtException", onUncaughtException);

  loadConfig();

  const { version, superpowers: { appApiVersion: appApiVersion } } = JSON.parse(fs.readFileSync(`${__dirname}/../../package.json`, { encoding: "utf8" }));
  SupCore.log(`Server v${version} starting...`);
  fs.writeFileSync(`${__dirname}/../../public/superpowers.json`, JSON.stringify({ version, appApiVersion, hasPassword: config.server.password.length !== 0 }, null, 2));

  // SupCore
  (global as any).SupCore = SupCore;
  SupCore.systemsPath = path.join(dataPath, "systems");

  // List available languages
  languageIds = fs.readdirSync(`${__dirname}/../../public/locales`);
  languageIds.unshift("none");

  // Main HTTP server
  mainApp = express();

  if (typeof config.server.sessionSecret !== "string") throw new Error("serverConfig.sessionSecret is null");
  const sessionSettings = {
    name: "supSession",
    secret: config.server.sessionSecret,
    store: new expressSession.MemoryStore(),
    resave: false,
    saveUninitialized: false,
    cookie: { maxAge: 1000 * 60 * 60 * 24 * 30 }
  };

  mainApp.use(cookieParser());
  mainApp.use(bodyParser.urlencoded({ extended: false }));
  mainApp.use(handleLanguage);
  mainApp.use(expressSession(sessionSettings));
  mainApp.use(passportMiddleware.initialize());
  mainApp.use(passportMiddleware.session());

  mainApp.get("/", (req, res) => { res.redirect("/hub"); });

  mainApp.post("/login", ensurePasswordFieldIsntEmpty, passportMiddleware.authenticate("local", { successReturnToOrRedirect: "/", failureRedirect: "/login" }));
  mainApp.get("/login", serveLoginIndex);
  mainApp.get("/logout", (req, res) => { req.logout(); res.redirect("/"); });

  mainApp.get("/hub", enforceAuth, serveHubIndex);
  mainApp.get("/project", enforceAuth, serveProjectIndex);

  mainApp.use("/projects/:projectId/*", serveProjectWildcard);
  mainApp.use("/", express.static(`${__dirname}/../../public`));

  mainHttpServer = http.createServer(mainApp);
  mainHttpServer.on("error", onHttpServerError.bind(null, config.server.mainPort));

  io = socketio(mainHttpServer, { transports: [ "websocket" ] });
  io.use(passportSocketIo.authorize({
    cookieParser: cookieParser,
    key: sessionSettings.name,
    secret: sessionSettings.secret,
    store: sessionSettings.store
  }));

  // Build HTTP server
  buildApp = express();

  buildApp.get("/", redirectToHub);
  buildApp.get("/systems/:systemId/SupCore.js", serveSystemSupCore);

  buildApp.use("/", express.static(`${__dirname}/../../public`));

  buildApp.use((req, res, next) => {
    const originValue = req.get("origin");
    if (originValue == null) { next(); return; }

    const origin = url.parse(originValue);
    if (origin.hostname === req.hostname && origin.port === config.server.mainPort.toString()) {
      res.header("Access-Control-Allow-Origin", originValue);
    }
    next();
  });

  buildApp.get("/builds/:projectId/:buildId/*", (req, res) => {
    const projectServer = hub.serversById[req.params.projectId];
    if (projectServer == null) { res.status(404).end("No such project"); return; }
    let buildId = req.params.buildId as string;
    if (buildId === "latest") buildId = (projectServer.nextBuildId - 1).toString();
    res.sendFile(path.join(projectServer.buildsPath, buildId, req.params[0]));
  });

  buildHttpServer = http.createServer(buildApp);
  buildHttpServer.on("error", onHttpServerError.bind(null, config.server.buildPort));

  loadSystems(mainApp, buildApp, onSystemsLoaded);

  // Save on exit and handle crashes
  process.on("SIGTERM", onExit);
  process.on("SIGINT", onExit);
  process.on("message", (msg: string) => { if (msg === "stop") onExit(); });
}
開發者ID:defc0n1,項目名稱:superpowers-core,代碼行數:99,代碼來源:start.ts

示例9: cookieParser

app.middleware('parse', bodyParser.json());

// to support URL-encoded bodies
app.middleware('parse', bodyParser.urlencoded({
  extended: true,
}));

// The access token is only available after boot
app.middleware('auth', loopback.token({
  model: app.models.accessToken,
}));

app.middleware('session:before', cookieParser(app.get('cookieSecret')));
app.middleware('session', expressSession({
  secret: 'kitty',
  saveUninitialized: true,
  resave: true,
  store: new mongoStore({url: 'mongodb://localhost:27017/projecty'}),
}));

passportConfigurator.init();

// We need flash messages to see passport errors
app.use(expressFlash());

passportConfigurator.setupModels({
  userModel: app.models.user,
  userIdentityModel: app.models.userIdentity,
  userCredentialModel: app.models.userCredential,
});

for (var s in config) {
開發者ID:fastegg,項目名稱:projectY,代碼行數:32,代碼來源:server.ts

示例10: SequelizeStore

  TWITTER_CONSUMER_KEY,
  TWITTER_CONSUMER_SECRET,
} = process.env;

app.use(cors({
  origin: FRONTEND_URL,
  credentials: true
}));

const sessionStore = new SequelizeStore({db: sequelize})
sessionStore.sync()

app.use(session({
  secret: SESSION_SECRET,
  store: sessionStore,
  cookie: {
    maxAge: 7 * 24 * 60 * 60 * 1000 // 7 days
  }
}))

app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser((user, done) => {
  done(null, user.id)
});
passport.deserializeUser(async (id, done) => {
  try {
    done(null, await User.findById(id))
  } catch (e) {
    done(e, null);
開發者ID:sketchglass,項目名稱:respass,代碼行數:31,代碼來源:auth.ts


注:本文中的express-session類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。