I get this in my flutter app, I send the token but still get this error message and everything is supposed to be alright
void changeFavourites(int productId) {
DioHelper.postData(
url: favourite,
data: {"product_id": productId},
lang: "en",
token: token,
).then((value) {
changeFavouritesmodel = ChangeFavouritesmodel.fromJson(value.data);
print(value.data);
print(token);
emit(ShopChangeFavouritesSuccessState());
}).catchError((error) {
emit(ShopChangeFavouritesErrorState());
});
}
Related
I am using the Credentials provider and next-auth 4.3.1
I go to page /protected
This page does useSession({ required: true, onUnauthenticated: () => router.push('/login?redirect=/protected') })
I login on the login page I got redirected too with this code:
const { data: { csrfToken } } = await axios.get('/api/auth/csrf');
const res = await axios
.post(
'/api/auth/callback/credentials',
{
json: true,
csrfToken,
redirect: false,
email: form.email,
password: form.password
},
{
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}
);
router.push(router.query.redirect || '/');
After succesfully logging in, notice it pushes back router.push(router.query.redirect), so it takes me back to /protected
However useSession returns { data: undefined, status: loading } and triggers onUnauthenticated, taking me back to the login page
Now, I don't login again, I just type in URL bar https://localhost:3000/protected it will load the protected page and useSession properly finds the logged-in session.
Is there something I have to do to make useSession see signIn was just called?
Here is my [...nextauth].ts:
const handler = NextAuth({
secret: process.env.NEXTAUTH_SECRET,
session: {
strategy: 'jwt'
},
debug: process.env.NODE_ENV === 'development',
providers: [
CredentialsProvider({
credentials: {
email: { label: 'Email', type: 'text' },
password: { label: 'Password', type: 'password' }
},
async authorize(credentials, req) {
////// removed
}
})
],
pages: {
signIn: '/login'
},
callbacks: {
async jwt({ token, user }) {
if (user) {
token.user = { id: user.id };
}
return token;
},
async session({ session, token }) {
if (session?.user) {
session.user.id = token.user.id;
}
return session;
}
}
});
I have a problem with my authentication via Coinbase (using Nextauth) on NextJS app.
I made this code below, and it saves the profile well in my Mongodb database. But when I re-login, accesstoken and refreshtoken are not changed...
So I can’t use the APIs afterwards.
import NextAuth from 'next-auth';
import Providers from 'next-auth/providers';
async function refreshAccessToken(token) {
try {
const url =
"https://api.coinbase.com/oauth/token?" +
new URLSearchParams({
client_id: process.env.COINBASE_CLIENT_ID,
client_secret: process.env.COINBASE_SECRET_ID,
grant_type: "refresh_token",
refresh_token: token.refreshToken,
})
const response = await fetch(url, {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
method: "POST",
})
const refreshedTokens = await response.json()
if (!response.ok) {
throw refreshedTokens
}
return {
...token,
accessToken: refreshedTokens.access_token,
accessTokenExpires: Date.now() + refreshedTokens.expires_in * 1000,
refreshToken: refreshedTokens.refresh_token ?? token.refreshToken, // Fall back to old refresh token
}
} catch (error) {
console.log(error)
return {
...token,
error: "RefreshAccessTokenError",
}
}
}
export default NextAuth({
// Configure one or more authentication providers
providers: [
Providers.Coinbase({
clientId: process.env.COINBASE_CLIENT_ID,
clientSecret: process.env.COINBASE_SECRET_ID,
callbackUrl: process.env.COINBASE_CALLBACKURL,
scope: "wallet:accounts:read",
}),
],
callbacks: {
async jwt({ token, user, account, profile, isNewUser }) {
// Initial sign in
if (account && user) {
return {
accessToken: user.data.access_token,
accessTokenExpires: Date.now() + user.data.expires_in * 1000,
refreshToken: user.data.refresh_token,
user,
}
}
// Return previous token if the access token has not expired yet
if (Date.now() < token.accessTokenExpires) {
return token
}
// Access token has expired, try to update it
return refreshAccessToken(token)
},
async session(session, token) {
session.accessToken = token.accessToken
return session
}
},
events: {
async signIn(message) { console.log('success signin') },
async signOut(message) { console.log('success signout') },
async createUser(message) { console.log('success user create') },
async updateUser(message) { console.log('success update user') },
async session(message) { console.log('success session') },
async error(message) { console.log('error') }
},
// A database is optional, but required to persist accounts in a database
database: `mongodb+srv://${process.env.NOSQL_USER}:${process.env.NOSQL_PWD}#${process.env.NOSQL_HOST}/${process.env.NOSQL_TABLE}`,
});
I’m still a beginner on NextJS and React in particular:) Thanks for your help
I have a MERN mobile app thats using passportjs to authenticate and login users (with mongodb database and axios), however, when i eventually get to the the screen to enter in data (a "log"), i cant associate that data/log with the signed in user. How can i grab the user id several screens later after they have already signed in to associate it with the entry? My mongodb database has a number of users, so i only want a specific user's data (eg calories), ie the one that is currently logged in:
// Mongoose schemas
// log.model.js
const Schema = mongoose.Schema;
const logSchema = new Schema(
{
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
calories: {
type: Number,
required: true,
},
},
{
timestamps: true,
}
);
const Log = mongoose.model("Log", logSchema);
// user.model.js
const userSchema = new Schema(
{
_id: Schema.Types.ObjectId, // user id
email: {
type: String,
required: true,
unique: true,
trim: true,
},
password: {
type: String,
required: true,
trim: true,
minlength: 6,
},
},
{
timestamps: true,
}
);
const User = mongoose.model("User", userSchema);
They are first prompted to signin in the app, where they will then navigate to Home. Not all features are added in yet, just in development stage now:
// ./frontend/screens/signin.js
function onLoginPress() {
axios({
method: "POST",
data: {
email: email,
password: password,
},
withCredentials: true,
url: 'http:localhost:5000/users/signin',
})
.then((res) => console.log(res.data))
.catch((error) =>
console.log("ERROR: Promise rejected (sign in): " + error)
);
navigation.navigate("Home");
}
// ./backend/routes/users.js
router.route("/signin").post((req, res, next) => {
passport.authenticate("local", (error, user, info) => {
if (error) {
res.json({
status: "FAILED",
message: error,
});
}
if (!user) {
res.json({
status: "FAILED",
message: "No user exists",
});
} else {
req.logIn(user, (error) => {
if (error) console.log("ERROR: " + error);
res.json({
status: "SUCCESS",
message: "Successfully authenticated",
});
console.log(req.user);
});
}
})(req, res, next);
});
After they sign in, and they wish to enter in calories, i attempt to associate that log (and any future logs they might add) with the signed in user when they hit a button:
// ./frontend/screens/log.js
const [calories, setCalories] = React.useState("");
function onSaveLog() {
axios({
method: "post",
url: "http://localhost:5000/log/add",
data: {
calories: calories,
// CANT GET USER ID HERE?
},
})
.then((res) => {
console.log(res.data);
})
.catch(function () {
console.log("LOG ERROR: promise rejected");
});
}
// ./backend/routes/log.js
router.route("/add").post((req, res) => {
const calories = Number(req.body.calories);
// const user = req.body.user; // CANT GET THE USER ID HERE
const newLog = new Log({
calories,
// user,
});
// saves Log data to mongodb
newLog
.save()
.then(() => res.json("Log added"))
.catch((err) => res.status(400).json("Error: " + err));
});
so, what you doubt is, correct me if I'm wrong is that you want an ID that can be accessed somewhere later in the app to retrieve the users' data.
There are many ways to achieve that,
after you get the id, you can pass it as Navparams. check this for more info RN- params
Next you can store the id in async storage and retrieve it anywhere, I would suggest this cause is the easiest rn--async storage
import AsyncStorage from '#react-native-async-storage/async-storage';
const storeData = async (value) => {
try {
await AsyncStorage.setItem('#storage_Key', value)
} catch (e) {
// saving error
}
}
// read
const getData = async () => {
try {
const value = await AsyncStorage.getItem('#storage_Key')
if(value !== null) {
// value previously stored
}
} catch(e) {
// error reading value
}
}
you can do it this way, do tell me if you're stuck
I am using stripe sdk for payment and trying to create customer in that ,
static Future<Map<String, dynamic>> createcustomer() async {
try {
var body = {
'name': 'Jenny Rosen',
'address': {
'line1': '510 Townsend St',
'postal_code': '98140',
'city': 'San Francisco',
'state': 'CA',
'country': 'US',
}
};
var response = await http.post(
'https://api.stripe.com/v1/customers',
body: json.encode(body),
headers: StripeService.headers
);
print('resvfdg: ${jsonDecode(response.body)}');
return jsonDecode(response.body);
} catch (err) {
print('err charging user: ${err.toString()}');
}
return null;
}
i am getting the error code: parameter_unknown,message: Received unknown parameter ,
how to create customer in stripe ?? or what i am missing in this ?
i don't know how to apply this and i need to create customer for doing international payment outside india , if i done payment in "INR" it will working properly , but for any other currency they asked for name and address.
I'm using Dio, this code is working for me:
static Future<Map<String, dynamic>> createcustomer() async {
try {
var data = {
'name': 'Jenny Rosen',
'address': {
'line1': '510 Townsend St',
'postal_code': '98140',
'city': 'San Francisco',
'state': 'CA',
'country': 'US',
}
};
Response response = await Dio().post('https://api.stripe.com/v1/customers',
data: data,
options: Options(contentType:Headers.formUrlEncodedContentType,
headers: {
'Authorization': 'Bearer ${secret}', // your secret key
}
),
);
print('response: ${jsonDecode(response.data)}');
return jsonDecode(response.data);
} catch (err) {
print('err charging user: ${err.toString()}');
}
return null;
}
I have used this api is working fine but response is paramter unknown
{error: {code: parameter_unknown, doc_url: https://stripe.com/docs/error-codes/parameter-unknown, message: Received unknown parameter: {"address":"sss","email":"aryan#gmail.com","name":"aryan","phone":"953667"}, param: {"address":"sss","email":"aryan#gmail.com","name":"aryan","phone":"953667"}, type: invalid_request_error}}
Flutter Code
Future createcustomer() async {
try {
var body = {
"address": "sss",
"email": "aryan#gmail.com",
"name": "aryan",
"phone": "95366710",
};
//final response = await http.post(Uri.parse("https://api.stripe.com/v1/customers"),
final response = await http.post(Uri.parse("https://api.stripe.com/v1/customers"),
headers: {
"Content-Type": "application/x-www-form-urlencoded","Authorization": "Bearer ${sKey}",
},
body: json.encode(body),
);
print('resvfdg: ${jsonDecode(response.body)}');
return jsonDecode(response.body);
} catch (err) {
print('err charging user: ${err.toString()}');
}
}
As I mentioned above my Axios on Nuxt.js is not catch error properly
I need to know the error, so I can prompt to let the user know their input is not correct but it only console.log the error code status not the message from my API
this is my code
await axios
.post(
"API LINK",
{
email: user.email,
password: "123456",
name: user.name,
dob: user.dob ?? null,
gender: user.gender ?? null,
profileImage: imageUrl ?? user.profileImage,
userType: user.userType
}
)
.then(res => {
console.log("success");
console.log(res);
})
.catch(err => {
console.log('fail');
console.log(err)
})
This is what log on a chrome console
error
add.vue?104b:181 Error: Request failed with status code 400
at createError (createError.js?2d83:16)
at settle (settle.js?467f:17)
at XMLHttpRequest.handleLoad (xhr.js?b50d:61)
But what I expect from the console.log(err) is
(This is response from postman)
{
"message": "Error creating new user.",
"error": {
"code": "auth/invalid-password",
"message": "The password must be a string with at least 6 characters."
}
}
I have no idea what is happening.
Try this
console.log(err.response)
To make the code cleaner you can destructure the argument:
.catch(({ response }) => {
console.log('fail');
console.log(response)
})
If you want to use some other property name instead of response you can do it like this:
.catch(({ response: err }) => {
console.log('fail');
console.log(err)
})
The problem is when the console.log tries to output the error, the string representation is printed, not the object structure, so you do not see the .response property.
Here you can read about https://github.com/axios/axios/issues/960
This is working with a try / catch structure, which is the preferred way
try {
await axios.post("API LINK", {
email: user.email,
password: "123456",
name: user.name,
dob: user.dob ?? null,
gender: user.gender ?? null,
profileImage: imageUrl ?? user.profileImage,
userType: user.userType,
})
console.log("success", res)
} catch ({ response }) {
console.log("fail", response)
}