Client_fetch_error session (next-auth v3) - next.js

i have big problem with next-auth credential-provider when i build my next.js project i get error [next-auth][error][client_fetch_error]
https://next-auth.js.org/errors#client_fetch_error session FetchError: request to http://localhost:3000/api/auth/session failed, reason: connect ECONNREFUSED 127.0.0.1:3000
**** i want to deploy my project local
that is my code
//env.local
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_URL_INTERNAL=http://localhost:3000
SECRET=SYoUMVkWrAVwv+qDJ+E43kmS7uMIJY3R7AS53tLNclk=
MONGODB_URI=mongodb://localhost:27017/healthycrm
//[...nextauth].js
import NextAuth from "next-auth";
import Providers from "next-auth/providers";
import User from "../../../models/mongoModels/user";
import connectDB from "../../../middleware/mondodb";
const handler = NextAuth({
providers: [
Providers.Credentials({
async authorize(credentials) {
const user = await User.findOne({
EmpUserName: credentials.userName,
}).exec();
if (!user) {
throw new Error("No user Found");
}
const cheakPassWord = user.EmpPassword === credentials.password;
if (!cheakPassWord) {
throw new Error("password is wrong");
}
return { name: user.EmpName, email: user.id, image: user.imgPath };
},
}),
],
secret: process.env.SECRET,
jwt: {
secret: process.env.SECRET,
encryption: true,
},
session: {
jwt: true,
maxAge: 1 * 24 * 60 * 60,
},
callbacks: {
async jwt({ token, user }) {
if (user) {
token.id = user.id;
}
return token;
},
async session({ session, token }) {
if (token) {
session.id = token.id;
}
return session;
},
session: async (session, user) => {
const data = await User.findById(user.email).exec();
const premissions = data.Premissions
? data.Premissions.map((x) => x.id)
: [];
const Emps = data.Premissions ? data.Emps.map((x) => x.id) : [];
session.user.jobID = data.EmpJobID;
session.user.MID = data._id;
session.user.List = data.EmpLists;
session.user.AreasQ = data.EmpAreasQ;
session.user.AreasG = data.EmpAreasG;
session.user.EmpJobName = data.EmpJobName;
session.user.EmpDepartID = data.EmpDepartID;
session.user.EmpDepartName = data.EmpDepartName;
session.user.EmpQtayID = data.EmpQtayID;
session.user.EmpGomla = data.EmpGomla;
session.user.directMangerId = data.directMangerId;
session.user.directMangerName = data.directMangerName;
session.user.EmpClassesQ = data.EmpClassesQ;
session.user.EmpClassesG = data.EmpClassesG;
session.user.Premissions = premissions;
session.user.Emps = Emps;
return Promise.resolve(session);
},
},
});
export default connectDB(handler);

I found the following solution: Run npm run dev during build

Related

Next-Auth who to deal with backend access token

I am using Django and Next.js (Version 13 with the app dir enabled). Now I have two questions:
What is the best practice to deal with the access token I receive after I do the authorize call to the django backend? Is it correct how I put it into the callbacks?
export const authOptions = {
secret: process.env.NEXTAUTH_SECRET,
providers: [
CredentialsProvider({
name: 'Django',
credentials: {
username: { label: "Username", type: "text", placeholder: "mail#domain.com" },
password: { label: "Password", type: "password" }
},
async authorize(credentials, req) {
// Do access call
const resToken = await fetch(process.env.AUTH_ENDPOINT, {
method: 'POST',
body: JSON.stringify(credentials),
headers: { "Content-Type": "application/json" }
})
const jwt_token = await resToken.json()
// fetching user data
const resUser = await fetch(`${process.env.BACKEND_URL}/auth/users/me/`, {
method: 'GET',
headers: { "Content-Type": "application/json",
"Authorization": `JWT ${jwt_token.access}` }
})
const user = await resUser.json()
if (resUser.ok && jwt_token.access) {
user.access_token = jwt_token.access
user.refresh_token = jwt_token.refresh
return user
}
// Return null if user data could not be retrieved
return null
}
})
],
session: {
strategy: "jwt",
},
jwt: { encryption: true, },
callbacks: {
async jwt({ token, user }) {
if (user) {
token.access_token = user.access_token
token.refresh_token = user.refresh_token
console.log("if executed")
}
return token
},
async session({ session, token, user }) {
if (!session) {
session.access_token = user.access_token
session.refresh_token = user.refresh_token
session.user = user
}return session;
},
}
}
export default NextAuth(authOptions)
I have the provider wrapped in the provider.js file as shown below. Now I was wondering if I need to passt the session as <SessionProvider session={session}> in the code below? And if yes - could you tell me how?
'use client'
import { SessionProvider } from 'next-auth/react'
export function Providers({ children }) {
return (
<SessionProvider>
{children}
</SessionProvider>
);
}
Thank you!

NextAuth session callback does not trigger

I deployed a Nextjs(v13) app with AWS Amplify and using NextAuth(v4.17.0). I'm using CredentialsProvider with a custom server. All works great in development environment, but in production the session callback doesn't fire and the session is empty, even if the token gets created in the database
/page/api/auth/[...nextauth].tsx disregard the console logs lol
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import jwt_decode from "jwt-decode";
import { TokenInfo } from "../../../components/types/auth_types";
async function refreshAccessToken(token) {
try {
console.log("BUT WHY?");
const res = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/api/token/refresh/`,
{
method: "POST",
body: JSON.stringify({refresh: token.refreshToken}),
headers: {"Content-Type": "application/json"},
}
);
if (!res.ok) throw "refreshError";
const responseJson = await res.json();
return {
...token,
accessToken: responseJson.access,
}
} catch(error) {
return {
...token,
error: "RefreshAccessTokenError",
}
}
}
export const authOptions = {
providers: [
CredentialsProvider({
id: "credentials",
name: "Credentials",
credentials: {
email: { label: "Username", type: "text", placeholder: "" },
password: { label: "Password", type: "password" }
},
async authorize(credentials, req) {
const userCredentials = {
email: credentials.email, password: credentials.password
};
try {
const res = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/api/token/`,
{
method: "POST",
body: JSON.stringify(userCredentials),
headers: {"Content-Type": "application/json"},
credentials: "include",
}
);
console.log("res", res);
if (res.ok) {
const responseJson = await res.json();
console.log("resJson", responseJson);
const tokenInfo: TokenInfo = jwt_decode(responseJson.access);
console.log("tokenInfo", tokenInfo);
return {
id: tokenInfo.user_id.toString(),
email: tokenInfo.email,
firstName: tokenInfo.first_name,
lastName: tokenInfo.last_name,
isStaff: tokenInfo.is_staff,
accessToken: responseJson.access,
refreshToken: responseJson.refresh,
};
}
return null;
} catch(e) {
return null;
}
}
})
],
callbacks: {
async jwt({ token, account, user }) {
if (account && user) {
console.log("got into token", user);
token.firstName = user.firstName;
token.lastName = user.lastName;
token.refreshToken = user.refreshToken;
token.accessToken = user.accessToken;
}
if (token.accessToken) {
console.log("got in this if instead")
const decodedToken: TokenInfo = jwt_decode(token.accessToken);
if (Date.now() < decodedToken.exp * 1000) {
console.log("got here, returned properly");
return token;
}
}
console.log("got here, not properly, why?");
return await refreshAccessToken(token);
},
async session({ session, token }) {
console.log("getting session");
session.user.firstName = token.firstName;
session.user.lastName = token.lastName;
session.accessToken = token.accessToken;
console.log("sess", session);
return session;
}
},
secret: process.env.NEXT_AUTH_SECRET,
session: {
maxAge: 2 * 24 * 60 * 60, // two days
}
};
export default NextAuth(authOptions);
I have searched as best as I could and couldn't find anything that I didn't do already.
My understanding is I don't need to set session: { strategy: "jwt"} since that's the default.
I have NEXT_AUTH_SECRET="mysecret", NEXT_PUBLIC_API_URL="https://www.backend_domain.com" and NEXTAUTH_URL="https://www.frontend_domain.com" set properly in .env.production and the API calls succeed, as well as the NextAuth calls return 200 status code, no errors in Amplify logs
Edit 1:
If I navigate to /api/auth/signin/credentials and use the default UI for login, the session gets created successfully

next auth oauth_callback_error

I am getting this error.
https://next-auth.js.org/errors#oauth_callback_error expected 200 OK, got: 400 Bad Request
Please help me solve it.
THis is my next auth config
const authHandler: NextApiHandler = (req, res) => NextAuth(req, res, options)
export default authHandler
const options: NextAuthOptions = {
providers: [
FacebookProvider({
clientId: process.env.FACEBOOK_CLIENT_ID,
clientSecret: process.env.FACEBOOK_CLIENT_SECRET,
}),
],
callbacks: {
async session({ session, token }) {
if (session?.user) {
session.user.id = token.id
session.user.createdAt = token.createdAt
session.user.role = token.role
}
return session
},
async jwt({ user, token }) {
if (user) {
token.id = user.id
// #ts-ignore
token.createdAt = user.createdAt
// #ts-ignore
token.role = user.role
}
return token
},
},
session: {
strategy: 'jwt',
},
adapter: PrismaAdapter(prisma),
secret: process.env.NEXTAUTH_SECRET,
}
]1

Firebase react native loading issue

I'm new at react native and I try to build an mobile app. I'm using Firebase for applications. When I try to login, it stucks on the loading page. And getting this warning:
Setting a timer for a long period of time, i.e. multiple minutes, is a performance and correctness issue on Android as it keeps the timer module awake, and timers can only be called when the app is in the foreground. See https://github.com/facebook/react-native/issues/12981 for more info.
(Saw setTimeout with duration 3600000ms)
What should I do?
Also authentication code is here:
import { AsyncStorage } from 'react-native';
export const SIGNUP = 'SIGNUP';
export const LOGIN = 'LOGIN';
export const AUTHENTICATE = 'AUTHENTICATE';
export const LOGOUT = 'LOGOUT';
let timer;
export const authenticate = (userId, token, expiryTime) => {
return dispatch => {
dispatch(setLogoutTimer(expiryTime));
dispatch({ type: AUTHENTICATE, userId: userId, token: token });
};
};
export const signup = (email, password) => {
return async dispatch => {
const response = await fetch(
'https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=...',
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: email,
password: password,
returnSecureToken: true
})
}
);
if (!response.ok) {
const errorResData = await response.json();
const errorId = errorResData.error.message;
let message = 'Bir terslik var!';
if (errorId === 'EMAIL_EXISTS') {
message = 'Bu e-posta zaten kayıtlı!';
}
throw new Error(message);
}
const resData = await response.json();
console.log(resData);
dispatch(
authenticate(
resData.localId,
resData.idToken,
parseInt(resData.expiresIn) * 1000
)
);
const expirationDate = new Date(
new Date().getTime() + parseInt(resData.expiresIn) * 1000
);
saveDataToStorage(resData.idToken, resData.localId, expirationDate);
};
};
export const login = (email, password) => {
return async dispatch => {
const response = await fetch(
'https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=...',
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: email,
password: password,
returnSecureToken: true
})
}
);
if (!response.ok) {
const errorResData = await response.json();
const errorId = errorResData.error.message;
let message = 'Bir terslik var!';
if (errorId === 'EMAIL_NOT_FOUND') {
message = 'Böyle bir e-posta yok!';
} else if (errorId === 'INVALID_PASSWORD') {
message = 'Bu şifre geçersiz!';
}
throw new Error(message);
}
const resData = await response.json();
console.log(resData);
dispatch(
authenticate(
resData.localId,
resData.idToken,
parseInt(resData.expiresIn) * 1000
)
);
const expirationDate = new Date(
new Date().getTime() + parseInt(resData.expiresIn) * 1000
);
saveDataToStorage(resData.idToken, resData.localId, expirationDate);
};
};
export const logout = () => {
clearLogoutTimer();
AsyncStorage.removeItem('userData');
return { type: LOGOUT };
};
const clearLogoutTimer = () => {
if (timer) {
clearTimeout(timer);
}
};
const setLogoutTimer = expirationTime => {
return dispatch => {
timer = setTimeout(() => {
dispatch(logout());
}, expirationTime);
};
};
const saveDataToStorage = (token, userId, expirationDate) => {
AsyncStorage.setItem(
'userData',
JSON.stringify({
token: token,
userId: userId,
expiryDate: expirationDate.toISOString()
})
);
};

Is there a way to mock firebase modules in jest?

Code.js
saveToFirebase = () => {
let statusMsg = ""
firebase
.firestore()
.collection("messages")
.doc(this.state.field.email)
.set(this.state.field)
.then((statusMsg = "Your Message have been submitted successfully."))
this.clearFields(statusMsg)
}
Code.test.js
it("should call mock firebase module", () => {
const docData = {
field: {
name: "Rob Bob",
email: "rob#bob.com",
phone: "9999999999",
subject: "Test subject",
message: "Test message",
},
}
const docResult = {
data: () => docData,
}
const get = jest.fn(() => Promise.resolve(docResult))
const set = jest.fn()
const doc = jest.fn(() => {
return {
set,
get,
}
})
const colllection = jest.fn((messages) => {
return { doc }
})
const firestore = () => {
return colllection
}
firebase.firestore = firestore
const mockData = { fake: "data" }
jest.clearAllMocks()
wrapper.instance().saveToFirebase()
})
While running the Code.test.js, it throws an error that firebase.firestore().collection() is not a function. Please suggest proper mocking of the firebase module for the above code and to add a case to check if firebase has successfully returned then, clearFields() is invoked.
You can use jest.spyOn(object, methodName) to mock firebase.firestore() function.
E.g.
index.jsx:
import React, { Component } from 'react';
import firebase from 'firebase';
export default class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
field: { email: 'mock#example.com' },
};
}
clearFields(statusMsg) {
console.log(statusMsg);
}
saveToFirebase = () => {
let statusMsg = '';
return firebase
.firestore()
.collection('messages')
.doc(this.state.field.email)
.set(this.state.field)
.then(() => {
statusMsg = 'Your Message have been submitted successfully.';
this.clearFields(statusMsg);
});
};
render() {
return <div>my component</div>;
}
}
index.test.jsx:
import MyComponent from '.';
import { shallow } from 'enzyme';
import React from 'react';
import firebase from 'firebase';
describe('61358076', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('should pass', async () => {
const firestoreMock = {
collection: jest.fn().mockReturnThis(),
doc: jest.fn().mockReturnThis(),
set: jest.fn().mockResolvedValueOnce(),
};
const clearFieldsSpy = jest.spyOn(MyComponent.prototype, 'clearFields');
jest.spyOn(firebase, 'firestore').mockImplementationOnce(() => firestoreMock);
const wrapper = shallow(<MyComponent></MyComponent>);
await wrapper.instance().saveToFirebase();
expect(firestoreMock.collection).toBeCalledWith('messages');
expect(firestoreMock.doc).toBeCalledWith('mock#example.com');
expect(firestoreMock.set).toBeCalledWith({ email: 'mock#example.com' });
expect(clearFieldsSpy).toBeCalledWith('Your Message have been submitted successfully.');
});
});
unit test results with 100% coverage:
PASS stackoverflow/61358076/index.test.jsx (17.824s)
61358076
✓ should pass (39ms)
console.log stackoverflow/61358076/index.jsx:1611
Your Message have been submitted successfully.
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.jsx | 100 | 100 | 100 | 100 |
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 19.945s
source code: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61358076
Hi recently I needed to mock jest module and this is my implementation,
note: I used eventEmitter3 to handle onAuthStateChange
import EventEmitter from 'eventemitter3';
const authEmitter = new EventEmitter();
let isSignIn = true;
const user = {
displayName: 'test name',
email: 'redirectTest#test.com',
emailVerified: true,
uid: 'id123',
providerData: [
{
email: 'redirectTest#test.com',
displayName: 'redirectResultTestDisplayName',
providerId: 'google',
},
],
};
const mockFirebase: any = {
initializeApp: jest.fn().mockReturnValue({
auth: jest.fn().mockReturnValue({
currentUser: isSignIn
? {
displayName: 'redirectResultTestDisplayName',
email: 'redirectTest#test.com',
emailVerified: true,
uid: 'id123',
providerData: [
{
email: 'redirectTest#test.com',
displayName: 'redirectResultTestDisplayName',
providerId: 'google',
},
],
sendEmailVerification: jest.fn(),
}
: null,
signInWithRedirect: jest.fn(),
getRedirectResult: jest.fn().mockReturnValue({
credential: {
providerId: 'Google',
},
user: {
getIdToken: jest.fn().mockResolvedValue('abc1234'),
},
additionalUserInfo: {
profile: {
email: '__tests__#__tests__.com',
name: 'John Doe',
},
},
}),
onAuthStateChanged: jest.fn(fn => {
// sign user on start
fn(user);
// sign-out user on start
authEmitter.on('sign-out', fn, undefined);
authEmitter.on('sign-in', fn, user);
}),
signOut: jest.fn(() => {
isSignIn = false;
authEmitter.emit('sign-out');
}),
signInWithEmailAndPassword: jest.fn(() => {
isSignIn = true;
authEmitter.emit('sign-in', user);
return Promise.resolve(true);
}),
sendPasswordResetEmail: jest.fn(() => Promise.resolve(true)),
sendEmailVerification: jest.fn(() => Promise.resolve(true)),
signInWithPopup: jest.fn(() => {
isSignIn = true;
authEmitter.emit('sign-in', user);
return Promise.resolve(true);
}),
}),
firestore: jest.fn().mockReturnValue({
collection: jest.fn().mockReturnValue({
doc: jest.fn().mockReturnValue({
add: jest.fn().mockResolvedValue({
id: 'abc123',
}),
set: jest.fn().mockResolvedValue({
uid: 'abc123',
}),
}),
}),
}),
}),
auth: {
GoogleAuthProvider: class {
addScope = jest.fn();
},
GithubAuthProvider: class {
addScope = jest.fn();
},
FacebookAuthProvider: class {
addScope = jest.fn();
},
},
};
jest.mock('firebase/app', () => mockFirebase);

Resources