firebase admin 11.5 not finding module - javascript

I have upgraded from Firebase Admin 10 to 11 and now I am finding an error
Error: Cannot find module 'firebase-admin/auth'
Require stack:
- C:\Users\Quarton Family\Desktop\TipBossProjects\TipBoss2023\server\firebase\index.js
my code is:
const { initializeApp, cert } = require('firebase-admin/app')
import { getAuth } from 'firebase-admin/auth'
import serviceAccountKey from './serviceAccountKey.json'
const app = initializeApp({
credential: cert(serviceAccountKey),
})
const auth = getAuth(app)
export default auth
When I try to import auth to a middleware.js document I get the above error. Any help would be much appreciated.
import auth from '../firebase'
export const findOrCreateUser = async (req, res, next) => {
try {
const firebaseUser = await auth.verifyIdToken(req.headers.token)
} catch (err) {
console.log(err)
res.status(401).json({
err: 'Invalid or expired token',
})
}
}

Related

Next.js | TypeError: Cannot read properties of undefined (reading 'secret')

I was trying to authenticate the API routes in next.js but getting the below error.
Page level Authentication is working fine. But wile trying to get the session in the API routes, getting error.
error - TypeError: Cannot read properties of undefined (reading 'secret')
at unstable_getServerSession (C:\Users\amond07\Workspace\Time_Management_App\time-management-matrix\time-management-matrix-web\node_modules\next-auth\next\index.js:78:48)
at __WEBPACK_DEFAULT_EXPORT__ (webpack-internal:///(api)/./pages/api/tasks/[user]/[date]/index.js:14:100)
at Object.apiResolver (C:\Users\amond07\Workspace\Time_Management_App\time-management-matrix\time-management-matrix-web\node_modules\next\dist\server\api-utils\node.js:179:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async DevServer.runApi (C:\Users\amond07\Workspace\Time_Management_App\time-management-matrix\time-management-matrix-web\node_modules\next\dist\server\next-server.js:381:9)
at async Object.fn (C:\Users\amond07\Workspace\Time_Management_App\time-management-matrix\time-management-matrix-web\node_modules\next\dist\server\base-server.js:500:37)
at async Router.execute (C:\Users\amond07\Workspace\Time_Management_App\time-management-matrix\time-management-matrix-web\node_modules\next\dist\server\router.js:213:36)
at async DevServer.run (C:\Users\amond07\Workspace\Time_Management_App\time-management-matrix\time-management-matrix-web\node_modules\next\dist\server\base-server.js:619:29)
at async DevServer.run (C:\Users\amond07\Workspace\Time_Management_App\time-management-matrix\time-management-matrix-web\node_modules\next\dist\server\dev\next-dev-server.js:536:20)
at async DevServer.handleRequest (C:\Users\amond07\Workspace\Time_Management_App\time-management-matrix\time-management-matrix-web\node_modules\next\dist\server\base-server.js:320:20)
Below is the code snippets
pages/api/[...nextauth].js
import GoogleProviders from "next-auth/providers/google";
export default NextAuth({
// Configure one or more authentication providers
providers: [
GoogleProviders({
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
}),
// ...add more providers here
],
secret: process.env.NEXTAUTH_SECRET,
});
pages\tasks\[user]\date
import clientPromise from "../../../../../lib/mongodb";
import { authOptions } from "../../../auth/[...nextauth]";
import { unstable_getServerSession } from "next-auth/next";
export default async (req, res) => {
const { user, date } = req.query;
const session = await unstable_getServerSession(req, res, authOptions);
try {
const client = await clientPromise;
const db = client.db();
const tasks = await db
.collection("tasks")
.find({ user: user, taskDate: date })
.sort({ startDate: -1 })
.toArray();
res.status(200).send({ tasks });
} catch (err) {
res.status(500).send({ error: "failed to fetch data" });
}
};
Is the "NEXTAUTH_SECRET" (properly) defined in your .env?
I have fixed the issue.
Issue was the way I was exporting it.
The unstable_getServerSession accepts a json object as authOptions but I was providing a function.
Edited the [...nextAuth].js as below:
import NextAuth from "next-auth";
import GoogleProviders from "next-auth/providers/google";
import { NextAuthOptions } from "next-auth";
export const authOptions = {
// Configure one or more authentication providers
providers: [
GoogleProviders({
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
}),
// ...add more providers here
],
secret: process.env.NEXTAUTH_SECRET,
};
export default NextAuth(authOptions);

JWT token does not expire

For whatever reason, the token generated by jsonwebtoken never expires.
Here is my code so far.
auth.ts Middleware.
// Libs
import { Express, Request, Response, NextFunction } from "express";
import { PassportStatic } from "passport";
import { Strategy as JWTStrategy, ExtractJwt } from "passport-jwt";
// Users
import { usersDB } from "../users";
const setupAuth = (api: Express, passport: PassportStatic) => {
const strategy = new JWTStrategy(
{
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: "123456qwerty",
algorithms: ["HS256"],
},
(payload, cb) => {
try {
const { sub } = payload;
const user = usersDB.find((u) => u.username === sub);
if (user) {
return cb(null, user);
} else {
return cb(null, false);
}
} catch (e) {
return cb(e);
}
}
);
api.use(passport.initialize());
passport.use(strategy);
};
export default setupAuth;
Login route
import { Request, Response } from "express";
import { usersDB, validatePassword } from "../../users";
import { genJWT } from "../../utils/auth";
const login = (req: Request, res: Response) => {
const { username, password } = req.body;
const user = usersDB.find((u) => u.username === username);
if (!user) {
return res
.status(401)
.json({ status: "fail", message: "Invalid username or password" });
}
if (!validatePassword(password, user.salt, user.hash)) {
return res
.status(401)
.json({ status: "fail", message: "Invalid username or password" });
}
const token = genJWT(user.username);
res.status(200).json({ status: "success", token });
};
export default login;
And the jwt token generator
import jwt from "jsonwebtoken";
export const genJWT = (username: string) => {
const token = jwt.sign({ sub: username, iat: Date.now() }, "123456qwerty", {
expiresIn: "1min",
algorithm: "HS256",
});
return token;
};
Then the secured routes
// Lib
import { Express } from "express";
import { PassportStatic } from "passport";
// GET
import root from "./GET/root";
import currentUser from "./GET/current-user";
import privateContent from "./GET/private-content";
// POST
import register from "./POST/register";
import login from "./POST/login";
import logout from "./POST/logout";
const setupRoutes = (api: Express, passport: PassportStatic) => {
api.get("/", root);
api.get(
"/current-user",
passport.authenticate("jwt", { session: false }),
currentUser
);
api.get(
"/private-content",
passport.authenticate("jwt", { session: false }),
privateContent
);
api.post("/register", register);
api.post("/login", login);
api.post("/logout", logout);
};
export default setupRoutes;
So the API is working, able to generate jwt token, able to authenticate with the token. It is able to validate too if I modify the token. But the problem is I can forever use the token. It never expires.
Is there something I missed?
Thanks in advance.
Ok when I removed
iat: Date.now()
from the jwt.sign, now the token does expire. So never put iat, let jsonwebtoken generate it.

jwt - vscode - postgresql DB connection/login project

i did so many things to solve this problem, i didn't.
so i am asking some questions related to some error
when i run code server and client side without no error.
but the screen is blank and console display error :
[App.js:24] POST http://localhost:5000/authentication/verify 401 (Unauthorized)
https://github.com/ousecTic/pern-jwt-tutorial << the link
anyway, i just type the code below, but it doens't work.
app.js (client side)
import React, { Fragment, useState, useEffect } from "react";
import "react-toastify/dist/ReactToastify.css";
import {
BrowserRouter as Router,
Route,
Switch,
Redirect
} from "react-router-dom";
import { toast } from "react-toastify";
//components
import Login from "./components/Login";
import Register from "./components/Register";
import Dashboard from "./components/Dashboard";
toast.configure();
function App() {
const checkAuthenticated = async () => {
try {
const res = await fetch("http://localhost:5000/authentication/verify", {
method: "POST",
headers: { jwt_token: localStorage.token }
});
const parseRes = await res.json();
parseRes === true ? setIsAuthenticated(true) : setIsAuthenticated(false);
} catch (err) {
console.error(err.message);
}
};
server.js (server side)
const express = require("express");
const app = express();
const cors = require("cors");
//middleware
app.use(cors());
app.use(express.json());
//routes
app.use("/authentication", require("./routes/jwtAuth"));
app.use("/dashboard", require("./routes/dashboard"));
app.listen(5000, () => {
console.log(`Server is starting on port 5000`);
});
jwtauth (server side)
router.post("/verify", authorize, (req, res) => {
try {
res.json(true);
} catch (err) {
console.error(err.message);
res.status(500).send("Server error");
}
});
module.exports = router;
and i checked already below some things.
i just changed react/react-dorm and others package version in package.json
in the server/client side. cause it has been changed a lot so many errors occured.
so i make the package the same version.
And i checked DB connection / but it seems to work.
and this is my entire code : https://github.com/Ryandongyou/jwt_project_dongyou
thank you :)

Can't reach server, React 404 error 'Post'

I can't reach server side I checked everything it should work
error is:
"POST http://localhost:3000/ 404 (Not Found)"
Here is my code
On client side here, I call createPost at jsx file and in actions/post.js file:
import * as api from "../api/index";
import * as types from "./types";
export const createPost = (post) => async (dispatch) =>{
try {
const {data} = await api.createPost(post);
dispatch({
type: types.CREATE_POST,
payload: data,
});
} catch (error) {
console.log(error);
}
};
from here it should call the api,
import axios from "axios";
const apiEndpoint = "/";
export const fetchPosts = async () => await axios.get(apiEndpoint);
export const createPost = async (post) => await axios.post(apiEndpoint, post);
and from there to server side but there is a error at createPost first.
btw in server,
import express from "express";
import {getPosts, createPost} from "../contollers/posts.js";
const router = express.Router();
//localhost/posts
// GET POST DELETE UPDATE
router.get("/", getPosts);
router.post("/", createPost);
export default router;
and in controller:
export const createPost = async(req,res) => {
const post = req.body;
const newPost = new Post(req.body);
try{
await newPost.save();
res.status(201).json(newPost);
}catch(error){
res.status(409).json({
message: error.message,
});
}
};
thanks for help
yeah its my stupidity that correcting some router&dom versions and url to 5000(which is the server) solved the issue

I keep getting http POST http://localhost:3000/api/authenticate 404 (Not Found)

am using angular 6 and express when am developing this api on authentcate uri it returning Http failure response for http://localhost:3000/api/authenticate: 404 Not Found
i have tried removing of the responses on my user.controller.js but the problem persisits it seems am missing out some point here and i dont know here it is at first i got an error saaying cant send headers after they are sent and the error was on my user.controller.js on this line else return res.status(404).json(info);
Here is my user.controller.js
const mongoose = require('mongoose');
const User = mongoose.model('User');
const passport = require('passport');
const _ = require('lodash');
module.exports.register = (req,res, next) => {
const user = new User();
user.fullname = req.body.fullname;
user.email = req.body.email;
user.College = req.body.College;
user.Department = req.body.Department;
user.password = req.body.password;
user.admintype = req.body.admintype;
user.save((err, doc) => {
if(!err) { res.send(doc)}
else
{
if(err.code == 11000)
res.status(422).send(['Duplicate email Address Found.'])
else
return next(err);
}
})
}
module.exports.authenticate = (req, res, next ) => {
//calll for passport authentication
passport.authenticate('local', (err, user, info) => {
//error form paasport middleware
if(err) return res.status(400).json(err);
//registered user
else if (user) return res.status(200).json({ "token":user.generateJwt() });
//unknown user or wrong password
else return res.status(404).json(info);
})(req, res);
}
module.exports.userProfile = (req, res, next) =>{
User.findOne({ _id:req._id},
(err,user) =>{
if(!user)
return res.status(404).json({ status: false, message : 'User Record not Found. '});
else
return res.status(200).json({ status:true , user : _.pick(user, ['fullname','email','university','College','Department','admintype'])});
} );
}
Here is my user.service.ts
```import { Injectable } from '#angular/core';
import { User } from './user.model';
import{ HttpClient, HttpHeaders } from '#angular/common/http';
import{ environment } from '../../environments/environment';
import { from } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class UserService {
selectedUser: User = {
fullname:'',
email:'',
university:'',
College:'',
Department:'',
password:'',
admintype:''
};
constructor(private http: HttpClient) { }
postUser(user:User)
{
return this.http.post(environment.apiBaseUrl+ '/register' ,user)
}
login(authCredentials)
{
return this.http.post(environment.apiBaseUrl+ '/authenticate',authCredentials);
}
setToken(token:string)
{
localStorage.setItem('token',token);
}
}```
Here is my sign-in.components.ts
```import { Component, OnInit } from '#angular/core';
import { NgForm } from '#angular/forms';
import { UserService } from 'src/app/shared/user.service';
import { Router } from '#angular/router';
#Component({
selector: 'app-sign-in',
templateUrl: './sign-in.component.html',
styleUrls: ['./sign-in.component.css']
})
export class SignInComponent implements OnInit {
constructor( private userService:UserService, private router:Router) { }
model = {
email:'',
password:''
};
emailRegex = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
serverErrorMessages : string;
ngOnInit() {
}
onSubmit(form :NgForm)
{
this.userService.login(form.value).subscribe(
res =>{
this.userService.setToken(res['token']);
this.router.navigateByUrl('/signup');
},
err =>{
this.serverErrorMessages = err.message;
});
}
}```
Here is my environment.ts
```/ This file can be replaced during build by using the `fileReplacements` array.
// `ng build --prod` replaces `environment.ts` with `environment.prod.ts`.
// The list of file replacements can be found in `angular.json`.
export const environment = {
production: false,
apiBaseUrl:'http://localhost:3000/api'
};
/*
* For easier debugging in development mode, you can import the following file
* to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
*
* This import should be commented out in production mode because it will have a negative impact
* on performance if an error is thrown.
*/
// import 'zone.js/dist/zone-error'; // Included with Angular CLI.```
Here is my auth.js
```const router = require('express').Router();
const User = require('../controller/model/User');
const ctrlUser = require('../controller/user.controller');
const jwthelper = require('../jwtHelper')
//validation
router.post('/register', ctrlUser.register);
router.post('/authenticate',ctrlUser.authenticate);
router.get('/userProfile',jwthelper.verifyJwtToken,ctrlUser.userProfile);
module.exports = router;```
Here is my index.js
```const express = require('express');
const app = express();
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const cors = require('cors')
const bodyParser = require('body-parser');
require('./passportConfig');
const passport = require('passport');
dotenv.config();
//connect to mongodb
mongoose.set('useFindAndModify', false); mongoose.set('useUnifiedTopology', true);
mongoose.connect(process.env.DB_CONNECT,{ useNewUrlParser:true} , () =>
console.log('connected to db!')
);
//import routes
const authRoute = require('./routes/auth');
//middleware
app.use(bodyParser.json());
app.use(cors());
app.use(passport.initialize());
//error handler
app.use((err, req, res, next) =>{
if(err.name =='ValidationError')
{
var valErrs = [];
Object.keys(err.errors).forEach(key => valErrs.push(err.errors[key].message));
res.status(422).send(valErrs);
next();
}
});
//route middleware
app.use('/api',authRoute);
app.listen(3000, () => console.log("server Up and Running"));```
Any Help please on this one please thank you all
The only thing which is remain is to attach the router which you have define in the auth.js file to your express app like this
const authRouter = require('./auth');
And to prefix all routes define in the auth.js file you attach it as a middleware which is trigger on route prifix with \api
const express = require('express');
const app = express();
// define all your middleware and all other route
// and here you attach the auth router
app.use('\api', authRouter);
This will make authentication available on url http://localhost:3000/api/authenticate
You may also get 404 because of this line in authenticate route (by the way I think this must be a 400 - bad request, not 404, which is making confusion.)
else return res.status(404).json(info);
So to understand this, can you replace your authenticate route like this, and see what logs in the api console:
module.exports.authenticate = (req, res, next ) => {
console.log("req.body: ", req.body)
//calll for passport authentication
passport.authenticate('local', (err, user, info) => {
//error form paasport middleware
if(err) return res.status(400).json(err);
//registered user
else if (user) return res.status(200).json({ "token":user.generateJwt() });
//unknown user or wrong password
else {
console.log("info: ", info)
return res.status(400).json(info);
}
})(req, res);
Also it the angular component, can you change your onSubmit like this for easy debug:
be sure your form.value is correct:
onSubmit(form :NgForm)
{
console.log("form.value: ", form.value);
this.userService.login(form.value).subscribe(
res =>{
this.userService.setToken(res['token']);
this.router.navigateByUrl('/signup');
},
err =>{
console.log("err: ", err.message)
this.serverErrorMessages = err.message;
});
}

Categories

Resources