sub-manager-backend/auth/auth.mjs

78 lines
2.1 KiB
JavaScript

import passport from "passport";
import * as passportLocal from "passport-local";
import { db } from "../db.mjs";
import logger from "../logger.mjs";
import bcrypt from "bcrypt";
//This code saves the information provided by the user to the database, and then sends the user information to the next middleware if successful.
passport.use(
"signup",
new localStrategy(
{
usernameField: "email",
passwordField: "password",
},
async (email, password, done) => {
try {
const user = await db("users").insert({ email, password });
return done(null, user);
} catch (error) {
done(error);
}
},
),
);
async function isValidPwd(user, pwd) {
return bcrypt.compare(pwd, user.password);
}
passport.use(
"login",
new localStrategy(
{
usernameField: "email",
passwordField: "password",
},
async (email, password, done) => {
try {
const user = await db("users").select("*").where({ email });
if (user.length === 0) {
return done(null, false, { message: "User not found" });
}
user = user[0];
const validate = await isValidPwd(user, password);
if (!validate) {
return done(null, false, { message: "Wrong Password" });
}
return done(null, user, { message: "Logged in Successfully" });
} catch (error) {
return done(error);
}
},
),
);
// ...
const JWTstrategy = require("passport-jwt").Strategy;
const ExtractJWT = require("passport-jwt").ExtractJwt;
//This code uses passport-jwt to extract the JWT from the query parameter. It then verifies that this token has been signed with the secret or key set during logging in (TOP_SECRET). If the token is valid, the user details are passed to the next middleware.
passport.use(
new JWTstrategy(
{
secretOrKey: "TOP_SECRET",
jwtFromRequest: ExtractJWT.fromUrlQueryParameter("secret_token"),
},
async (token, done) => {
try {
return done(null, token.user);
} catch (error) {
done(error);
}
},
),
);