npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mygenericapiserver

v1.0.6

Published

A generic API server with pluggable authentication

Downloads

24

Readme

MyGenericAPIServer

MyGenericAPIServer is a generic API server template built with Node.js and Express. It features a pluggable authentication system that allows you to choose between basic authentication, token-based authentication, and OAuth2 authentication. This repository serves as a starting point for creating new API servers with different authentication mechanisms.

Introduction

MyGenericAPIServer is a Node.js library designed to provide a quick and easy way to set up an API server with pluggable authentication mechanisms. This library allows developers to choose between basic authentication, token-based authentication, and OAuth2 authentication with minimal configuration. By abstracting the complexity of setting up authentication, MyGenericAPIServer enables developers to focus on building their application logic and endpoints.

Table of Contents

Installation

  1. Create a new project:

    mkdir NewAPIServer
    cd NewAPIServer
    npm init -y
    npm install mygenericapiserver

Configuration

  1. Create a .env file:

    Create a .env file in the root directory to store environment variables.

    touch .env
  2. Add the following content to .env:

    AUTH_TYPE=basic  # or token, oauth2
    OAUTH2_AUTHORIZATION_URL=https://authorization-server.com/auth
    OAUTH2_TOKEN_URL=https://authorization-server.com/token
    OAUTH2_CLIENT_ID=your-client-id
    OAUTH2_CLIENT_SECRET=your-client-secret
    OAUTH2_CALLBACK_URL=http://localhost:3000/auth/oauth2/callback

Usage

Initialize the Server

To initialize the server, require the package and call initializeServer. Then use addPublicEndpoint and addPrivateEndpoint to define your endpoints, and finally call startServer to start the server.

Example server.js:

const { initializeServer, startServer, addPublicEndpoint, addPrivateEndpoint, getExpressInstance } = require('mygenericapiserver');

// Initialize the server
initializeServer();

// Add public and private endpoints
addPublicEndpoint('public', (req, res) => {
  res.json({ message: `This is the public endpoint: public` });
});

addPrivateEndpoint('private', (req, res) => {
  res.json({ message: `This is the private endpoint: private` });
});

// Add a new public endpoint that returns the HTML file
addPublicEndpoint('mytest', (req, res) => {
  res.sendFile(__dirname + '/public/test.html');
});

// Start the server
startServer();

Add Public Endpoint

To add a public endpoint, use the addPublicEndpoint function. This function takes an endpoint name and a handler function as parameters and defines a public route.

addPublicEndpoint('public', (req, res) => {
  res.json({ message: `This is the public endpoint: public` });
});

Add Private Endpoint

To add a private endpoint, use the addPrivateEndpoint function. This function takes an endpoint name and a handler function as parameters and defines a private route protected by the chosen authentication mechanism.

addPrivateEndpoint('private', (req, res) => {
  res.json({ message: `This is the private endpoint: private` });
});

Access Express Instance

If you need to access the Express instance for additional configuration, use the getExpressInstance function.

const app = getExpressInstance();
// Example: Adding a new middleware
app.use((req, res, next) => {
  console.log('Request URL:', req.url);
  next();
});

Authentication Types

Basic Authentication

Basic Authentication uses a username and password for authentication.

Set AUTH_TYPE=basic in your .env file. The default credentials are:

  • Username: admin
  • Password: secret

Token-based Authentication

Token-based Authentication uses a predefined list of valid tokens.

Set AUTH_TYPE=token in your .env file. The default valid tokens are:

  • token123
  • token456

OAuth2 Authentication

OAuth2 Authentication uses the OAuth2 protocol for authentication.

  1. Set AUTH_TYPE=oauth2 in your .env file.
  2. Configure the following OAuth2 environment variables in your .env file:
  • OAUTH2_AUTHORIZATION_URL: URL to the authorization server
  • OAUTH2_TOKEN_URL: URL to get the access token
  • OAUTH2_CLIENT_ID: Your OAuth2 client ID
  • OAUTH2_CLIENT_SECRET: Your OAuth2 client secret
  • OAUTH2_CALLBACK_URL: Callback URL for OAuth2 authentication
  1. OAuth2 Flow:
  • Navigate to /auth/oauth2 to initiate the OAuth2 authentication process.
  • After successful authentication, you will be redirected to /auth/oauth2/callback.

Example: Creating a New Project with MyGenericAPIServer

This example demonstrates how to create a new project, install MyGenericAPIServer, and add both a public endpoint and a private endpoint, each returning an HTML file.

Step 1: Create a New Project

Create a new project directory and initialize it:

mkdir NewAPIServer
cd NewAPIServer
npm init -y

Step 2: Install MyGenericAPIServer

Install the mygenericapiserver package:

npm install mygenericapiserver

Step 3: Create the .env File

Create a .env file in the root directory to specify the authentication type:

.env

AUTH_TYPE=basic  # or token, oauth2

Step 4: Create HTML Files

Create a directory named public and add HTML files for the endpoints:

Create the public directory:

mkdir public

Create public-endpoint.html:

echo "<!DOCTYPE html><html><body>Public Endpoint Content</body></html>" > public/public-endpoint.html

Create the private directory:

mkdir private

Create private-endpoint.html:

echo "<!DOCTYPE html><html><body>Private Endpoint Content</body></html>" > private/private-endpoint.html

Step 5: Create the Main Server File

Create the main server file server.js:

server.js

const { initializeServer, startServer, addPublicEndpoint, addPrivateEndpoint } = require('mygenericapiserver');

// Initialize the server
initializeServer();

// Add public and private endpoints
addPublicEndpoint('public-endpoint', (req, res) => {
  res.sendFile(__dirname + '/public/public-endpoint.html');
});

addPrivateEndpoint('private-endpoint', (req, res) => {
  res.sendFile(__dirname + '/private/private-endpoint.html');
});

// Start the server
startServer();

Step 6: Start the Server

Start the server:

node server.js

Step 7: Test the Endpoints

  • Navigate to http://localhost:3000/public-endpoint to see the public HTML content.
  • Navigate to http://localhost:3000/private-endpoint to see the private HTML content. Note that you will need to provide the correct credentials to access the private endpoint if basic authentication is used.

Example Directory Structure


NewAPIServer/
├── .env
├── node_modules/
├── package.json
├── public/
│   └── public-endpoint.html
├── private/
│   └── private-endpoint.html
└── server.js

Explanation

  1. Initialize Server: The initializeServer function sets up the Express application with session management and passport.
  2. Add Endpoints: The addPublicEndpoint and addPrivateEndpoint functions are used to define the public and private endpoints, respectively, serving the appropriate HTML files.
  3. Start Server: The startServer function starts the server on the specified port.