"syntax error, unexpected token \"(\", expecting \"{\"" when attempting to login to laravel from ionic using passport authentication - laravel-passport

I am attempting to create a login / registration process using an ionic 5 app and laravel 9. Registration works okay but when I attempt to login, laravel returns the error:
"syntax error, unexpected token \"(\", expecting \"{\""
login.page.ts
login(email: String, password: String) {
return this.http.post(this.env.API_URL + 'auth/login',
{email: email, password: password}
).pipe(
tap(token => {
this.global.storage.setItem('token', token)
.then(
() => {
//alert('Token Stored');
},
error => alert(error)
);
this.global.token = token;
this.global.isLoggedIn = true;
return token;
}),
);
}
Controller:
public function login(Request $request)
{
$data = [
'email' => $request['email'],
'password' => $request['password'],
];
try (auth()->attempt($data)) {
$tokenResult = auth()->user()->createToken('Pesacount-User-Access-Token');
$token = $tokenResult->accessToken;
if ($request->remember_me)
$token->expires_at = Carbon::now()->addWeeks(1);
$token->save();
return response()->json([
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'loginStatus' => 'Successful'
/***
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at
)->toDateTimeString()
*/
]);
return response()->json(['token' => $token], 200);
} catch (Exception $e) {
return response()->json(['error' => $e->getMessage()], 401);
}
}
According to the logs, the error is caused when running
try (auth()->attempt($data)) {
I was originally running laravel 5.6 and everything worked okay. Upgraded to laravel 9 and thats when the error started

Related

How to create a Plaid LinkToken using Node JS?

I believe Plaid updated its createLinkToken documentation, but I can't seem to figure out what I'm doing wrong here. I'm taking a course, and here is the old code that worked in using a FirebaseFunction to create a link token with Plaid:
exports.createPlaidLinkToken = functions.https.onCall(async (data, context) => {
const customerId = context.auth.id;
const plaidClient = new plaid.Client({
clientID: functions.config().plaid.client_id,
secret: functions.config().plaid.secret,
env: plaid.environments.sandbox,
options: {
version: '2019-05-29',
},
});
return plaidClient.createLinkToken({
user: {
client_user_id: customerId,
},
client_name: "Bon Voyage",
products: ["auth"],
country_codes: ["US"],
language: "en"
}).then((apiResponse) => {
const linkToken = apiResponse.link_token;
return linkToken;
}).catch((err) => {
console.log(err);
throw new functions.https.HttpsError("internal", "Unable to create plaid link token: " + err);
});
});
I've tried a number of things. I know plaid.Client is now new.Configuration but I can't seem to figure out the rest. Any helpers?
You can see in the comments below what I've tried. I've modified the code as follows, and now receive Error status code 400.
const plaid = require('plaid');
const { Configuration, PlaidEnvironments, PlaidApi } = require("plaid");
exports.createPlaidLinkToken = functions.https.onCall(async (data, context) => {
const customerId = context.auth.uid;
const configuration = new Configuration({
basePath: PlaidEnvironments.sandbox,
baseOptions: {
headers: {
plaid_client_id: functions.config().plaid.client_id,
plaid_secret: functions.config().plaid.secret,
plaid_version: '2021-05-20'
},
},
});
const plaidClient = new PlaidApi(configuration);
return plaidClient.linkTokenCreate({
user: {
client_user_id: customerId,
},
client_name: "Bon Voyage",
products: ["auth"],
country_codes: ["US"],
language: "en"
})
.then((apiResponse) => {
const linkToken = apiResponse.data.link_token;
// const linkToken = response.link_token
return linkToken;
})
.catch((err) => {
console.log(err);
throw new functions.https.HttpsError(
"internal",
" Unable to create plaid link token: " + err
);
});
});
It's difficult to answer this question as you haven't mentioned what you've tried or what error you are experiencing. Have you reviewed the sample implementations in the docs that show how to do this, including the sample code in the Quickstart and Tiny Quickstart?
Off the top of my head, I do see that this sample code specifies an API version of 2019-05-29, which is not compatible with the latest version of the Node client library that uses new.Configuration.

Why am I only getting Mailgun.js error in Cloud Run?

I'm trying to send an email using Mailgun's npm client - Mailgun.js.
When sending in development mode, everything works correctly. But when I upload the Node server to Cloud Run, something breaks.
Here is the code in the sendEmail helper file:
import formData from 'form-data';
import Mailgun from 'mailgun.js';
const sendEmail = async ({ to, subject, text, attachment, scheduledDate }) => {
const mailgun = new Mailgun(formData);
const mg = mailgun.client({
username: 'api',
key: process.env.MAILGUN_KEY,
url: 'https://api.eu.mailgun.net'
});
const data = {
from: `<myemail#mydomain.com>`,
to,
subject,
text
};
if (attachment) {
data.attachment = attachment;
}
if (scheduledDate) {
data['o:deliverytime'] = new Date(scheduledDate).toUTCString();
}
try {
const result = await mg.messages.create(process.env.MAILGUN_DOMAIN, data);
if (result.status && result.status !== 200) {
throw ({ code: result.status, message: result.message });
}
return true;
} catch(err) {
console.log(err);
return { error: err };
}
};
export default sendEmail;
And then in another file:
import { Router } from 'express';
import generateInvoicePDF from '../helpers/generateInvoicePDF.js';
import sendEmail from '../helpers/sendEmail.js';
const router = Router();
router.post('/email', async (req, res, next) => {
try {
const file = await generateInvoicePDF(invoice);
if (file?.error) {
throw ({ code: pdf.error.code, message: pdf.error.message });
}
const email = await sendEmail({
to: 'testemail#example.com',
subject: 'Invoice',
text: 'Test',
attachment: { filename: 'Invoice', data: file }
});
if (email?.error) {
throw ({ code: email.error.code, message: email.error.message });
}
res.status(200).json({ success: true });
} catch(err) {
next(err);
}
});
export default router;
The error I get when in production mode in Cloud Run's logs is:
TypeError: fetch failed
at Object.processResponse (node:internal/deps/undici/undici:5575:34)
at node:internal/deps/undici/undici:5901:42
at node:internal/process/task_queues:140:7
at AsyncResource.runInAsyncScope (node:async_hooks:202:9)
at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8) {
cause: TypeError: object2 is not iterable
at action (node:internal/deps/undici/undici:1661:39)
at action.next (<anonymous>)
at Object.pull (node:internal/deps/undici/undici:1709:52)
at ensureIsPromise (node:internal/webstreams/util:172:19)
at readableStreamDefaultControllerCallPullIfNeeded (node:internal/webstreams/readablestream:1884:5)
at node:internal/webstreams/readablestream:1974:7
}
Why the hell does it work in development mode on my local machine, but not when uploaded to Cloud Run?
For anyone struggling with something similar - I eventually figured out the problem.
On my local machine, where everything was working as expected, I'm using Node v16.15.0, whereas in the Dockerfile, I had specified
FROM node:latest
and therefore Cloud Run was using a newer version, which led to the problems...
I've now deployed using version 16.15.0 and everything works fine

[next-auth][error][client_fetch_error] NextAuthJS CredentialsProvider "providers SyntaxError: Unexpected token < in JSON at position 0"

As a beginner in Next.js I came across NextAuthJS. I wanted to use custom email and password authentication and thus I went with Credentials Provider and configured as below
import NextAuth from "next-auth";
import CredentialsProvider from `next-auth/providers/credentials`
import ConnectToDB from "../../../lib/db";
import auth from "../../../lib/auth";
export default NextAuth({
session: {
jwt: true,
maxAge: 30 * 24 * 60 * 60,
},
providers: [
CredentialsProvider({
async authorize(credentials) {
const client = await ConnectToDB();
const db = client.db();
const user = await db.collection("users").findOne({ email: credentials.email });
if (!user) {
client.close();
throw new Error("User not found");
}
const isValid = await auth.verifyPassword(credentials.password, user.password);
if (!isValid) {
client.close();
throw new Error("Invalid password");
}
client.close();
return { _id: user._id };
},
}),
],
});
And used the signIn method from next-auth/client to signin as below
import { signIn } from "next-auth/client";
const submitHandler = async (e) => {
e.preventDefault();
const email = emailRef.current.value;
const password = passwordRef.current.value;
const result = await signIn("credentials", { redirect: false, email, password });
}
I tried to debug this and found no solution to but and later I realised that some error is being logged in to browser console
This is the error I am receiving
[next-auth][error][client_fetch_error]
I think you already solved your problem since you asked a couple months ago.
if not i'm intending my answer for also those who has the same issue.
Your code looks almost exactly the same in my one project but mine is working fine.
Well, you need to define credemtials: {} object in the CredentialsProvider({ ... }) like the official doc example https://next-auth.js.org/configuration/providers/credentials.
The client_fetch_error error. I assume, you are getting this in production, i had this issue also. You need to add a environment variable:
and redeploy.
you should either return null or return user in the authorize, not throw error
In my case, I needed to add NEXTAUTH_SECRET variable to Vercel, and the error was fixed. You can generate it with openssl rand -base64 32
more about that here: https://next-auth.js.org/configuration/options#secret

How can i get many details as possible about error using React Error boundry get error details?

Im tring to catch more details when error accuring.
when the error is accuring im using node api server to catch the error and save in log file.
i simulated a Network Error and tring to get many details as possible.
when i console.log the error in frontend im getting this:
withFormHandler.js:28 Uncaught Error: Error: Network Error
at Object.componentDidUpdate (withFormHandler.js:28)
...
but i cant send this information using my api.
all im getting in the server side is an empty object.
so how can i catch and send many details as possible about the error and write it to the log file?
this is my ErrorBoundry component:
class ErrorBoundary extends React.Component {
state = {
hasError: false,
error: { message: "", stack: "" },
info: { componentStack: "" },
};
static getDerivedStateFromError = (error) => {
return { hasError: true };
};
componentDidCatch = (error, info) => {
this.setState({ error, info });
axios
.get(`http://localhost:5001/api/logs/error`, {
params: {
error: error.message,
details: info,
// details:error ---> this is also not give me information i need
},
})
.catch(() => {});
};
render() {
const { hasError, error, info } = this.state;
const { children } = this.props;
return hasError ? <ErrorComponent message={error.message} /> : children;
}
}
this is the server side handle:
router.get("/error", (req, res) => {
const errorMessage = req.query.error;
const details = req.query.details; -----> return an empty object :(
const logFile = "./logs/debug.log";
if (errorMessage) {
let error = errorMessage + "\r\n" + details;
fs.appendFile(logFile, error, function (err) {
// callback or something
});
}
});

Why Hook is called in all update services methods

I'm create a hook file with the following information, which is Hooks.js
Hooks.js is working to authenticate an actions with JWT when need it, I dont need it in all servies calls.
As my understanding the syntax to call a hook was app/use route/hooks and those hooks were only applied to and specific route and not globally.
module.exports = {
errorHandler: (context) => {
if (context.error) {
context.error.stack = null;
return context;
}
},
isValidToken: (context) => {
const token = context.params.headers.authorization;
const payload = Auth.validateToken(token);
console.log(payload);
if(payload !== "Invalid" && payload !== "No Token Provided"){
context.data = payload._id;
}
else {
throw new errors.NotAuthenticated('Authentication Error Token');
}
},
isValidDomain: (context) => {
if (
config.DOMAINS_WHITE_LIST.includes(
context.params.headers.origin || context.params.headers.host
)
) {
return context;
}
throw new errors.NotAuthenticated("Not Authenticated Domain");
},
normalizedId: (context) => {
context.id = context.id || context.params.route.id;
},
normalizedCode: (context) => {
context.id = context.params.route.code;
},
};
Then I create a file for services and routes, like the following:
const Hooks = require("../../Hooks/Hooks");
const userServices = require("./user.services");
module.exports = (app) => {
app
.use("/users", {
find: userServices.find,
create: userServices.createUser,
})
.hooks({
before: {
find: [Hooks.isValidDomain],
create: [Hooks.isValidDomain],
},
});
app
.use("/users/:code/validate", {
update: userServices.validateCode,
})
.hooks({
before: {
update: [Hooks.isValidDomain, Hooks.normalizedCode],
},
});
app
.use("/users/personal", {
update: userServices.personalInfo,
})
.hooks({
before: {
update: [Hooks.isValidDomain, Hooks.isValidToken],
},
});
};
Why Hooks.isValidToken applies to all my update methods? Even if I'm not calling it?
Please help.
app.hooks registers an application level hook which runs for all services. If you only want it for a specific service and method it needs to be app.service('users').hooks().

Resources