0.0.7 • Published 9 months ago
@cruzeblade/express-authentication v0.0.7
Express.js Authentication
This package offers an Express.js middleware and router that makes it fast and easy to add user authentication to your Express.js server.
Usage
Authentication Server / Service:
import express from 'express';
import logger from './logger';
import cors from 'cors';
import 'dotenv/config';
import { createAuthRouter, SecretService } from '../dist';
const app = express();
const HOST = process.env.HOST ? (process.env.HOST as string) : 'localhost';
const PORT = process.env.PORT ? parseInt(process.env.PORT as string) : 4000;
const DB_URL = process.env.DB_URL as string;
const SECRET = process.env.SECRET as string;
app.use(express.json());
app.use(cors());
SecretService.setSecret(SECRET);
app.use(
createAuthRouter((mongoose) => {
mongoose
.connect(DB_URL)
.then(() => {
logger.info(`Connected to database on ${DB_URL}`);
})
.catch((err) => {
logger.error(`Could not connect to database on ${DB_URL}`);
});
}),
);
app.listen(PORT, HOST, () => {
logger.info(`Server listening on http://${HOST}:${PORT}`);
});
Other Servers / Services (authentication only):
import express from 'express';
import logger from './logger';
import cors from 'cors';
import 'dotenv/config';
import { authenticate, SecretService } from '../dist';
const app = express();
const HOST = process.env.HOST ? (process.env.HOST as string) : 'localhost';
const PORT = process.env.PORT ? parseInt(process.env.PORT as string) : 4000;
const DB_URL = process.env.DB_URL as string;
const SECRET = process.env.SECRET as string;
app.use(express.json());
app.use(cors());
SecretService.setSecret(SECRET);
app.get('/secure', authenticate, (req, res) => {
const user_id = req.session.user;
//...
});
app.listen(PORT, HOST, () => {
logger.info(`Server listening on http://${HOST}:${PORT}`);
});