@stanlemon/server-with-auth 0.1.5 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/jest.config.js ADDED
@@ -0,0 +1 @@
1
+ export { default } from "@stanlemon/webdev/jest.config.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stanlemon/server-with-auth",
3
- "version": "0.1.5",
3
+ "version": "0.1.8",
4
4
  "description": "A basic express web server setup with authentication baked in.",
5
5
  "author": "Stan Lemon <stanlemon@users.noreply.github.com>",
6
6
  "license": "MIT",
@@ -14,21 +14,24 @@
14
14
  "start": "NODE_ENV=development nodemon --ignore db.json ./app.js",
15
15
  "lint": "eslint --ext js,jsx,ts,tsx ./",
16
16
  "lint:format": "eslint --fix --ext js,jsx,ts,tsx ./",
17
- "test": "NODE_OPTIONS=--experimental-vm-modules jest --detectOpenHandles",
18
- "test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --detectOpenHandles --watch"
17
+ "test": "jest --detectOpenHandles",
18
+ "test:coverage": "jest --detectOpenHandles --coverage",
19
+ "test:watch": "jest --detectOpenHandles --watch"
19
20
  },
20
21
  "dependencies": {
21
22
  "@stanlemon/server": "*",
23
+ "@stanlemon/webdev": "*",
22
24
  "bcryptjs": "^2.4.3",
23
25
  "jsonwebtoken": "^8.5.1",
24
26
  "lowdb": "^3.0.0",
25
- "passport": "^0.5.2",
27
+ "passport": "^0.6.0",
26
28
  "passport-jwt": "^4.0.0",
27
29
  "shortid": "^2.2.16",
28
30
  "uuid": "^8.3.2"
29
31
  },
30
32
  "devDependencies": {
31
33
  "@stanlemon/eslint-config": "*",
34
+ "@types/supertest": "^2.0.12",
32
35
  "nodemon": "^2.0.16",
33
36
  "supertest": "^6.2.3"
34
37
  }
@@ -5,6 +5,7 @@ import {
5
5
  } from "@stanlemon/server";
6
6
  import passport from "passport";
7
7
  import { Strategy as JwtStrategy, ExtractJwt } from "passport-jwt";
8
+ import shortid from "shortid";
8
9
  import defaultUserSchema from "./schema/user.js";
9
10
  import checkAuth from "./checkAuth.js";
10
11
  import auth from "./routes/auth.js";
@@ -39,13 +40,17 @@ export default function createAppServer(options) {
39
40
  updateUser,
40
41
  } = { ...DEFAULTS, ...options };
41
42
 
43
+ const app = createBaseAppServer({ port, webpack, start });
44
+
45
+ if (process.env.NODE_ENV === "test") {
46
+ return app;
47
+ }
48
+
42
49
  if (!process.env.JWT_SECRET) {
43
50
  console.warn("You need to specify a secret.");
44
51
  }
45
52
 
46
- const secret = process.env.JWT_SECRET || "YouNeedASecret";
47
-
48
- const app = createBaseAppServer({ port, webpack, start });
53
+ const secret = process.env.JWT_SECRET || shortid.generate();
49
54
 
50
55
  passport.use(
51
56
  "jwt",
@@ -1,19 +1,36 @@
1
- import { Low, JSONFile } from "lowdb";
1
+ import { LowSync, JSONFileSync, MemorySync } from "lowdb";
2
2
  import { v4 as uuidv4 } from "uuid";
3
3
  import shortid from "shortid";
4
4
  import bcrypt from "bcryptjs";
5
5
 
6
+ const DEFAULT_ADAPTER =
7
+ process.env.NODE_ENV === "test"
8
+ ? new MemorySync()
9
+ : new JSONFileSync("./db.json");
10
+
6
11
  export default class SimpleUsersDao {
7
- constructor(seeds = [], adapter = new JSONFile("./db.json")) {
8
- this.db = new Low(adapter);
12
+ constructor(seeds = [], adapter = DEFAULT_ADAPTER) {
13
+ this.db = new LowSync(adapter);
9
14
 
10
- this.db.read().then(() => {
11
- this.db.data ||= { users: [] };
15
+ this.db.read();
12
16
 
13
- if (seeds.length > 0) {
14
- seeds.forEach((user) => this.createUser(user));
15
- }
16
- });
17
+ this.db.data ||= { users: [] };
18
+
19
+ if (seeds.length > 0) {
20
+ seeds.forEach((user) => this.createUser(user));
21
+ }
22
+ }
23
+
24
+ getDb() {
25
+ return this.db;
26
+ }
27
+
28
+ generateId() {
29
+ return uuidv4();
30
+ }
31
+
32
+ generateVerificationToken() {
33
+ return shortid.generate();
17
34
  }
18
35
 
19
36
  getUserById = (userId) => {
@@ -55,7 +72,7 @@ export default class SimpleUsersDao {
55
72
  .shift();
56
73
  };
57
74
 
58
- createUser = async (user) => {
75
+ createUser = (user) => {
59
76
  const existing = this.getUserByUsername(user.username);
60
77
 
61
78
  if (existing) {
@@ -66,17 +83,17 @@ export default class SimpleUsersDao {
66
83
  const data = {
67
84
  ...user,
68
85
  password: bcrypt.hashSync(user.password, 10),
69
- id: uuidv4(),
70
- verification_token: shortid.generate(),
86
+ id: this.generateId(),
87
+ verification_token: this.generateVerificationToken(),
71
88
  created_at: now,
72
89
  last_updated: now,
73
90
  };
74
91
  this.db.data.users.push(data);
75
- await this.db.write();
92
+ this.db.write();
76
93
  return data;
77
94
  };
78
95
 
79
- updateUser = async (userId, user) => {
96
+ updateUser = (userId, user) => {
80
97
  const now = new Date();
81
98
  this.db.data.users = this.db.data.users.map((u) => {
82
99
  if (u.id === userId) {
@@ -94,7 +111,7 @@ export default class SimpleUsersDao {
94
111
  }
95
112
  return u;
96
113
  });
97
- await this.db.write();
114
+ this.db.write();
98
115
  return this.getUserById(userId);
99
116
  };
100
117
  }
@@ -1,4 +1,7 @@
1
- import { Memory } from "lowdb";
1
+ /**
2
+ * @jest-environment node
3
+ */
4
+ import { MemorySync } from "lowdb";
2
5
  import SimpleUsersDao from "./simple-users-dao.js";
3
6
 
4
7
  describe("simple-users-dao", () => {
@@ -12,7 +15,7 @@ describe("simple-users-dao", () => {
12
15
 
13
16
  beforeEach(() => {
14
17
  // Before each test reset our users database
15
- users = new SimpleUsersDao([], new Memory());
18
+ users = new SimpleUsersDao([], new MemorySync());
16
19
  });
17
20
 
18
21
  it("creates a user", async () => {
@@ -21,40 +21,33 @@ export default function authRoutes({
21
21
  }) {
22
22
  const router = Router();
23
23
 
24
- router.get("/auth/session", (req, res, next) => {
25
- /* look at the 2nd parameter to the below call */
26
- passport.authenticate("jwt", { session: false }, (err, userId) => {
27
- if (err) {
28
- return next(err);
29
- }
24
+ router.get(
25
+ "/auth/session",
26
+ passport.authenticate("jwt", { session: false }),
27
+ async (req, res) => {
28
+ const userId = req.user;
29
+
30
30
  if (!userId) {
31
- return res.status(401).json({
31
+ res.status(401).json({
32
32
  token: false,
33
33
  user: false,
34
34
  });
35
+ return;
35
36
  }
36
37
 
37
- req.logIn(userId, async (err) => {
38
- if (err) {
39
- return next(err);
40
- }
41
-
42
- const user = await getUserById(userId);
43
-
44
- if (!user) {
45
- return res.status(401).json({
46
- token: false,
47
- user: false,
48
- });
49
- } else {
50
- const token = jwt.sign(user.id, secret);
51
- res
52
- .status(200)
53
- .json({ token, user: formatOutput(user, ["password"]) });
54
- }
55
- });
56
- })(req, res, next);
57
- });
38
+ const user = await getUserById(userId);
39
+
40
+ if (!user) {
41
+ res.status(401).json({
42
+ token: false,
43
+ user: false,
44
+ });
45
+ } else {
46
+ const token = jwt.sign(user.id, secret);
47
+ res.status(200).json({ token, user: formatOutput(user, ["password"]) });
48
+ }
49
+ }
50
+ );
58
51
 
59
52
  router.post("/auth/login", async (req, res) => {
60
53
  const user = await getUserByUsernameAndPassword(
@@ -1,14 +1,20 @@
1
+ /**
2
+ * @jest-environment node
3
+ */
1
4
  import request from "supertest";
2
- import { Memory } from "lowdb";
5
+ import { MemorySync } from "lowdb";
3
6
  import createAppServer from "../createAppServer";
4
7
  import SimpleUsersDao from "../data/simple-users-dao.js";
5
8
 
6
9
  // This suppresses a warning we don't need in tests
7
10
  process.env.JWT_SECRET = "SECRET";
8
11
 
9
- let users = new SimpleUsersDao([], new Memory());
12
+ let users = new SimpleUsersDao([], new MemorySync());
10
13
 
14
+ // We want to explicitly test functionality we disable during testing
15
+ process.env.NODE_ENV = "override";
11
16
  const app = createAppServer({ ...users, start: false });
17
+ process.env.NODE_ENV = "test";
12
18
 
13
19
  describe("/auth", () => {
14
20
  let userId;