2021-04-02 08:34:43 +13:00
|
|
|
const jwt = require("jsonwebtoken")
|
2021-04-08 02:15:05 +12:00
|
|
|
const { UserStatus } = require("../../constants")
|
|
|
|
const { compare } = require("../../hashing")
|
2021-04-15 01:13:48 +12:00
|
|
|
const env = require("../../environment")
|
2021-04-20 04:31:47 +12:00
|
|
|
const { getGlobalUserByEmail } = require("../../utils")
|
2021-07-07 05:10:04 +12:00
|
|
|
const { newid } = require("../../hashing")
|
|
|
|
const { createASession } = require("../../security/sessions")
|
2021-04-02 08:34:43 +13:00
|
|
|
|
|
|
|
const INVALID_ERR = "Invalid Credentials"
|
|
|
|
|
|
|
|
exports.options = {}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Passport Local Authentication Middleware.
|
2021-04-20 04:31:47 +12:00
|
|
|
* @param {*} email - username to login with
|
2021-04-02 08:34:43 +13:00
|
|
|
* @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
|
|
|
|
*/
|
2021-05-03 19:31:09 +12:00
|
|
|
exports.authenticate = async function (email, password, done) {
|
2021-04-20 04:31:47 +12:00
|
|
|
if (!email) return done(null, false, "Email Required.")
|
2021-04-02 08:34:43 +13:00
|
|
|
if (!password) return done(null, false, "Password Required.")
|
|
|
|
|
2021-04-21 04:17:44 +12:00
|
|
|
const dbUser = await getGlobalUserByEmail(email)
|
|
|
|
if (dbUser == null) {
|
2021-04-02 08:34:43 +13: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)) {
|
2021-07-07 05:10:04 +12:00
|
|
|
const sessionId = newid()
|
2021-07-16 04:57:02 +12:00
|
|
|
const tenantId = dbUser.tenantId
|
|
|
|
await createASession(dbUser._id, { sessionId, tenantId })
|
2021-07-08 10:29:19 +12:00
|
|
|
|
2021-07-08 10:30:14 +12:00
|
|
|
dbUser.token = jwt.sign(
|
|
|
|
{
|
|
|
|
userId: dbUser._id,
|
|
|
|
sessionId,
|
2021-07-16 04:57:02 +12:00
|
|
|
tenantId,
|
2021-07-08 10:30:14 +12:00
|
|
|
},
|
|
|
|
env.JWT_SECRET
|
|
|
|
)
|
2021-04-07 22:33:16 +12:00
|
|
|
// Remove users password in payload
|
2021-04-02 08:34:43 +13:00
|
|
|
delete dbUser.password
|
2021-04-07 22:33:16 +12:00
|
|
|
|
2021-04-02 08:34:43 +13:00
|
|
|
return done(null, dbUser)
|
|
|
|
} else {
|
|
|
|
done(new Error(INVALID_ERR), false)
|
|
|
|
}
|
|
|
|
}
|