2021-04-01 21:34:43 +02:00
|
|
|
const jwt = require("jsonwebtoken")
|
2021-04-07 16:15:05 +02:00
|
|
|
const { UserStatus } = require("../../constants")
|
2021-04-15 17:57:01 +02:00
|
|
|
const database = require("../../db")
|
2021-04-07 16:15:05 +02:00
|
|
|
const { StaticDatabases, generateUserID } = require("../../db/utils")
|
|
|
|
const { compare } = require("../../hashing")
|
2021-04-14 15:13:48 +02:00
|
|
|
const env = require("../../environment")
|
2021-04-01 21:34:43 +02:00
|
|
|
|
|
|
|
const INVALID_ERR = "Invalid Credentials"
|
|
|
|
|
|
|
|
exports.options = {}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Passport Local Authentication Middleware.
|
|
|
|
* @param {*} username - username to login with
|
|
|
|
* @param {*} password - plain text password to log in with
|
|
|
|
* @param {*} done - callback from passport to return user information and errors
|
|
|
|
* @returns The authenticated user, or errors if they occur
|
|
|
|
*/
|
|
|
|
exports.authenticate = async function(username, password, done) {
|
|
|
|
if (!username) return done(null, false, "Email Required.")
|
|
|
|
if (!password) return done(null, false, "Password Required.")
|
|
|
|
|
|
|
|
// Check the user exists in the instance DB by email
|
2021-04-15 17:57:01 +02:00
|
|
|
const db = new database.CouchDB(StaticDatabases.USER.name)
|
2021-04-01 21:34:43 +02:00
|
|
|
|
|
|
|
let dbUser
|
|
|
|
try {
|
|
|
|
dbUser = await db.get(generateUserID(username))
|
2021-04-07 12:33:16 +02:00
|
|
|
} catch (err) {
|
|
|
|
console.error("User not found", err)
|
2021-04-01 21:34:43 +02:00
|
|
|
return done(null, false, { message: "User not found" })
|
|
|
|
}
|
|
|
|
|
|
|
|
// check that the user is currently inactive, if this is the case throw invalid
|
|
|
|
if (dbUser.status === UserStatus.INACTIVE) {
|
|
|
|
return done(null, false, { message: INVALID_ERR })
|
|
|
|
}
|
|
|
|
|
|
|
|
// authenticate
|
|
|
|
if (await compare(password, dbUser.password)) {
|
|
|
|
const payload = {
|
2021-04-13 12:56:57 +02:00
|
|
|
userId: dbUser._id,
|
2021-04-14 14:22:57 +02:00
|
|
|
builder: dbUser.builder,
|
2021-04-14 15:13:48 +02:00
|
|
|
email: dbUser.email,
|
2021-04-01 21:34:43 +02:00
|
|
|
}
|
|
|
|
|
2021-04-14 15:13:48 +02:00
|
|
|
dbUser.token = jwt.sign(payload, env.JWT_SECRET, {
|
2021-04-01 21:34:43 +02:00
|
|
|
expiresIn: "1 day",
|
|
|
|
})
|
2021-04-07 12:33:16 +02:00
|
|
|
// Remove users password in payload
|
2021-04-01 21:34:43 +02:00
|
|
|
delete dbUser.password
|
2021-04-07 12:33:16 +02:00
|
|
|
|
2021-04-01 21:34:43 +02:00
|
|
|
return done(null, dbUser)
|
|
|
|
} else {
|
|
|
|
done(new Error(INVALID_ERR), false)
|
|
|
|
}
|
|
|
|
}
|