diff --git a/src/guards.ts b/src/guards.ts index ed8c62a..554c45b 100644 --- a/src/guards.ts +++ b/src/guards.ts @@ -1,7 +1,7 @@ import { Router, Handler } from 'express' import * as jwt from 'jsonwebtoken' import * as jsonServer from 'json-server' -import { stringify } from 'querystring' +import { stringify, ParsedUrlQueryInput } from 'querystring' import { JWT_SECRET_KEY } from './constants' import { bodyParsingHandler, errorHandler, goNext } from './shared-middlewares' @@ -66,7 +66,7 @@ const privateOnly: Handler = (req, res, next) => { } // TODO: handle query params instead of removing them - const path = req.url.replace(`?${stringify(req.query)}`, '') + const path = req.url.replace(`?${stringify(req.query as ParsedUrlQueryInput)}`, '') const [, mod, resource, id] = path.split('/') // Creation and replacement diff --git a/src/users.ts b/src/users.ts index 0e9629d..8aff294 100644 --- a/src/users.ts +++ b/src/users.ts @@ -47,9 +47,13 @@ const validate: ValidateHandler = ({ required }) => (req, res, next) => { * Register / Create a user */ const create: Handler = (req, res, next) => { - const { email, password, ...rest } = req.body as User + const { email, password, authFields, ...rest } = req.body as User const { db } = req.app + const fields = {}; + if (authFields) + authFields.forEach(field => fields[field] = req.body[field]); + if (db == null) { // json-server CLI expose the router db to the app // (https://github.com/typicode/json-server/blob/master/src/cli/run.js#L74), @@ -71,7 +75,7 @@ const create: Handler = (req, res, next) => { try { return db .get('users') - .insert({ email, password: hash, ...rest }) + .insert({ email, password: hash, authFields, ...rest }) .write() } catch (error) { throw Error('You must add a "users" collection to your db') @@ -80,7 +84,7 @@ const create: Handler = (req, res, next) => { .then((user: User) => { return new Promise((resolve, reject) => { jwt.sign( - { email }, + { email, ...fields }, JWT_SECRET_KEY, { expiresIn: JWT_EXPIRES_IN, subject: String(user.id) }, (error, idToken) => { @@ -115,6 +119,10 @@ const login: Handler = (req, res, next) => { return } + const fields = {}; + if (user.authFields) + user.authFields.forEach(field => fields[field] = user[field]); + bcrypt .compare(password, user.password) .then((same) => { @@ -122,7 +130,7 @@ const login: Handler = (req, res, next) => { return new Promise((resolve, reject) => { jwt.sign( - { email }, + { email, ...fields }, JWT_SECRET_KEY, { expiresIn: JWT_EXPIRES_IN, subject: String(user.id) }, (error, idToken) => {