Skip to content

Commit

Permalink
Rewrite all code to use ESM instead of CJS (#110, #83)
Browse files Browse the repository at this point in the history
  • Loading branch information
stefandesu committed Sep 12, 2024
1 parent 1c1f015 commit a0448fb
Show file tree
Hide file tree
Showing 46 changed files with 276 additions and 263 deletions.
10 changes: 6 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ This repository offers a login server to be used with the [Cocoda Mapping Tool](
- [Clone and Install](#clone-and-install)
- [Docker](#docker)
- [Configuration](#configuration)
- [`.env`](#env)
- [`providers.json`](#providersjson)
- [`applications.json`](#applicationsjson)
- [Usage](#usage)
- [Test](#test)
- [Strategies](#strategies)
Expand Down Expand Up @@ -215,11 +218,10 @@ Because strategies use different parameters in their [verify callbacks](http://w
*/

// Import strategy here
const Strategy = require("passport-github").Strategy
import { Strategy } from "passport-github"

// Don't change this part!
module.exports =
(options, provider, callback) => new Strategy(options,
export default (options, provider, callback) => new Strategy(options,
// Strategies have different callback parameters.
// `req` is always the first and the `done` callback is always last.
(req, token, tokenSecret, profile, done) => {
Expand Down Expand Up @@ -370,7 +372,7 @@ Tokens get be received either through the [/token endpoint](#get-token) or by us
Example how to verify a token:

```javascript
const jwt = require("jsonwebtoken")
import jwt from "jsonwebtoken"

// token, e.g. from user request
let token = "..."
Expand Down
10 changes: 5 additions & 5 deletions bin/list-users.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* A small tool to query user data from the database.
*/

const meow = require("meow")
import meow from "meow"
const cli = meow(`
Usage
$ ./bin/list-users.js [IDs or URIs] [options]
Expand Down Expand Up @@ -48,10 +48,10 @@ if (cli.input.length && cli.flags.withProvider.length) {
}

process.env.VERBOSITY = "error"
const config = require("../config")
const utils = require("../utils")
const db = require("../utils/db")
const User = require("../models/user")
import config from "../config.js"
import * as utils from "../utils/index.js"
import * as db from "../utils/db.js"
import User from "../models/user.js"

// Copied from jskos-tools
const isValidUri = (uri) => {
Expand Down
9 changes: 5 additions & 4 deletions bin/manage-local.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@
* A small program to manage local providers and users.
*/

const inquirer = require("inquirer")
const bcrypt = require("bcryptjs")
const fs = require("fs")
import inquirer from "inquirer"
import bcrypt from "bcryptjs"
import fs from "node:fs"

console.log("Login Server local user management")
console.log("Important Note: Do not manually edit providers.json while this script is running. Any action here will override those changes!")

require("dotenv").config()
import dotenv from "dotenv"
dotenv.config()
let providersFile = process.env.PROVIDERS_PATH || "./providers.json"
let providers
// Try to read providers from file
Expand Down
38 changes: 27 additions & 11 deletions config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,27 @@
* Optional keys: MONGO_USER, MONGO_PASS, MONGO_HOST, MONGO_PORT, MONGO_DB, RATE_LIMIT_WINDOW, RATE_LIMIT_MAX
*
*/
require("dotenv").config()
const fs = require("fs")
const url = require("url")
const rsa = require("node-rsa")
const jwt = require("jsonwebtoken")
import * as dotenv from "dotenv"
dotenv.config()
import fs from "node:fs"
import path from "node:path"
import { fileURLToPath } from "node:url"
import rsa from "node-rsa"
import jwt from "jsonwebtoken"

export function getDirname(url) {
return path.dirname(fileURLToPath(url))
}
const __dirname = getDirname(import.meta.url)
/**
* Reads and parses a JSON file.
*
* @param {string} file JSON file relative to root folder of repository
* @returns parsed JSON
*/
export function readJSON(file) {
return JSON.parse(fs.readFileSync(path.resolve(__dirname, file)))
}

const
env = process.env.NODE_ENV || "development",
Expand All @@ -36,7 +52,7 @@ const
publicKeyPath = process.env.JWT_PUBLIC_KEY_PATH || "./public.key",
jwtAlgorithm = process.env.JWT_ALGORITHM || "RS256",
title = process.env.TITLE || "Login Server",
packageData = require("./package.json"),
packageData = readJSON("./package.json"),
urls = {
imprint: process.env.IMPRINT_URL,
privacy: process.env.PRIVACY_URL,
Expand All @@ -54,8 +70,8 @@ if (!baseUrl.endsWith("/")) {
baseUrl += "/"
}

let purl = url.parse(baseUrl)
if (!["http:", "https:"].includes(purl.protocol) || !purl.slashes || !purl.hostname) {
let purl = new URL(baseUrl)
if (!["http:", "https:"].includes(purl.protocol) || !purl.hostname) {
console.error("Please provide a full BASE_URL in .env.")
process.exit(1)
}
Expand Down Expand Up @@ -187,7 +203,7 @@ if (env != "test") {
fs.writeFileSync(providersFile, "[]")
}
try {
config.providers = require(providersFile)
config.providers = readJSON(providersFile)
if (!Array.isArray(config.providers)) {
throw new Error("providers.json has to contain an array.")
}
Expand Down Expand Up @@ -258,7 +274,7 @@ if (env != "test") {

// Add application names
try {
config.applications = require("./applications.json")
config.applications = readJSON("./applications.json")
} catch (error) {
config.applications = []
}
Expand All @@ -273,4 +289,4 @@ if (!urls.privacy) {
config.warn("Warning: PRIVACY_URL is not configured.")
}

module.exports = config
export default config
File renamed without changes.
8 changes: 4 additions & 4 deletions lib/events.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const utils = require("../utils")
const config = require("../config")
import * as utils from "../utils/index.js"
import config from "../config.js"

/**
* List of websockets of format
Expand Down Expand Up @@ -233,7 +233,7 @@ function sendTokenForUser(wsID, user) {
}

// Interval that checks sessions that are about to expire and notifies them.
const { connection } = require("../utils/db")
import { connection } from "../utils/db.js"
setInterval(() => {
// Only make request if the database is connected.
if (connection.readyState === 1) {
Expand All @@ -251,7 +251,7 @@ setInterval(() => {
}
}, 1000 * 60 * config.sessionExpirationMessageInterval)

module.exports = {
export {
websockets,
sendEvent,
userLoggedInWs,
Expand Down
13 changes: 3 additions & 10 deletions lib/test-strategy.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,8 @@
/**
* Module dependencies.
*/
const passport = require("passport-strategy")
, util = require("util")

import passport from "passport-strategy"
import util from "node:util"

/**
* `Strategy` constructor.
Expand All @@ -19,7 +18,7 @@ const passport = require("passport-strategy")
* @param {Function} callback
* @api public
*/
function Strategy({ users, passReqToCallback }, callback) {
export function Strategy({ users, passReqToCallback }, callback) {
if (!users || !users.length) {
throw new TypeError("Test strategy requires at least one user")
}
Expand Down Expand Up @@ -58,9 +57,3 @@ Strategy.prototype.authenticate = function(req) {
}])
this._cb(...args)
}


/**
* Expose `Strategy`.
*/
module.exports = { Strategy }
4 changes: 2 additions & 2 deletions models/usage.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* Mongoose Schema for a user's usage data.
*/

const mongoose = require("mongoose")
import mongoose from "mongoose"
const Schema = mongoose.Schema

const usageSchema = new Schema({
Expand All @@ -11,4 +11,4 @@ const usageSchema = new Schema({
lastUsed: String,
}, { versionKey: false })

module.exports = mongoose.model("Usage", usageSchema)
export default mongoose.model("Usage", usageSchema)
4 changes: 2 additions & 2 deletions models/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* It should contain key-value-pairs with the key being the provider/strategy and the value being a profile object with keys `id`, `uri`, `name`, and `username`.
*/

const mongoose = require("mongoose")
import mongoose from "mongoose"
const Schema = mongoose.Schema

const userSchema = new Schema({
Expand All @@ -16,4 +16,4 @@ const userSchema = new Schema({
merged: [String],
}, { versionKey: false })

module.exports = mongoose.model("User", userSchema)
export default mongoose.model("User", userSchema)
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"bugs": {
"url": "https://github.com/gbv/login-server/issues"
},
"type": "module",
"main": "server.js",
"scripts": {
"test": "NODE_ENV=test mocha --exit --timeout 10000 --slow 2000",
Expand Down
4 changes: 2 additions & 2 deletions routes/about.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
* /about route.
*/

const utils = require("../utils")
import * as utils from "../utils/index.js"

module.exports = app => {
export default app => {

app.get("/about", (req, res) => {
res.json(utils.prepareAbout())
Expand Down
2 changes: 1 addition & 1 deletion routes/account.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* Account route.
*/

module.exports = app => {
export default app => {

app.get("/account", (req, res) => {
if (!req.user) {
Expand Down
2 changes: 1 addition & 1 deletion routes/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* /api route.
*/

module.exports = app => {
export default app => {

app.get("/api", (req, res) => {
res.render("api")
Expand Down
2 changes: 1 addition & 1 deletion routes/base.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* Base (/) route.
*/

module.exports = app => {
export default app => {

app.get("/", (req, res) => {
if (req.user) {
Expand Down
6 changes: 3 additions & 3 deletions routes/delete.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
* /delete routes
*/

const events = require("../lib/events")
const User = require("../models/user")
import * as events from "../lib/events.js"
import User from "../models/user.js"

module.exports = app => {
export default app => {

app.get("/delete", (req, res) => {
res.render("delete")
Expand Down
6 changes: 3 additions & 3 deletions routes/disconnect.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
* /disconnect route
*/

const _ = require("lodash")
const events = require("../lib/events")
import _ from "lodash"
import * as events from "../lib/events.js"

module.exports = app => {
export default app => {

// Disconnect route
app.get("/disconnect/:provider", (req, res) => {
Expand Down
2 changes: 1 addition & 1 deletion routes/help.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* Help route.
*/

module.exports = app => {
export default app => {

app.get("/help", (req, res) => {
res.render("help")
Expand Down
4 changes: 2 additions & 2 deletions routes/login.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
* Login route.
*/

const utils = require("../utils")
import * as utils from "../utils/index.js"

module.exports = app => {
export default app => {

app.get("/login", (req, res) => {
utils.saveReferrerInSession(req)
Expand Down
4 changes: 2 additions & 2 deletions routes/logout.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
* /logout route
*/

const events = require("../lib/events")
import * as events from "../lib/events.js"

module.exports = app => {
export default app => {

app.get("/logout", async (req, res) => {
// Invalidate session
Expand Down
4 changes: 2 additions & 2 deletions routes/providers.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
* Providers route.
*/

const utils = require("../utils")
import * as utils from "../utils/index.js"

module.exports = app => {
export default app => {

app.get("/providers", (req, res) => {
res.json(utils.prepareProviders())
Expand Down
8 changes: 4 additions & 4 deletions routes/sessions.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
* /sessions route.
*/

const config = require("../config")
const { connection } = require("../utils/db")
const { websockets } = require("../lib/events")
import config from "../config.js"
import { connection } from "../utils/db.js"
import { websockets } from "../lib/events.js"

/**
* Returns a Promise with all sessions for a user.
Expand Down Expand Up @@ -37,7 +37,7 @@ function removeSession(sessionID) {
})
}

module.exports = app => {
export default app => {

app.get("/sessions", (req, res) => {
// Get all sessions from store (via mongoose)
Expand Down
Loading

0 comments on commit a0448fb

Please sign in to comment.