I’m having a problem with image uploads with the Cloudinary API.
I have the app running on Heroku. I’m using Node for my backend. The app runs fine, until a user tries to post an image. I then get the following error message:
Invalid Signature ******************************. String to
sign - 'timestamp=.
I used the same setup in another app, and it works fine. I’ve followed some stack overflow threads on the problem, but I’m not getting a useful answer that I understand.
I’ve set up the environment variables in Heroku the same way I did on another app, and it works. I’ve also installed the Cloudinary and Multer packages in my package.json file.
Any ideas what I’m doing wrong here?
Below is my code:
var multer = require('multer');
var storage = multer.diskStorage({
filename: function(req, file, callback) {
callback(null, Date.now() + file.originalname);
}
});
var imageFilter = function (req, file, cb) {
// accept image files only
if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/i)) {
return cb(new Error('Only image files are allowed!'), false);
}
cb(null, true);
};
var upload = multer({ storage: storage, fileFilter: imageFilter});
var cloudinary = require('cloudinary');
cloudinary.config({
cloud_name: 'digi9mjbp',
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET
})
router.post("/", middleware.isLoggedIn, upload.single('image'),
function(req, res) {
cloudinary.v2.uploader.upload(req.file.path, function(err,result){
if(err){
req.flash("error", err.message);
return res.redirect("back");
}
// add cloudinary url for the image to the topic object under image
property
req.body.topic.image = result.secure_url;
//add image's public_id to topic object
req.body.topic.imageId = result.public_id;
// add author to topic
req.body.topic.author = {
id: req.user._id,
username: req.user.username
};
Topic.create(req.body.topic, function(err, topic){
if (err) {
req.flash('error', err.message);
return res.redirect('back');
}
res.redirect('/topics/' + topic.id);
});
});
});
Related
I am fairly new to coding and I'm in the learning phase for both React Native and Laravel. I was working on some practice project and I needed to upload an image from my React Native app to the Laravel server and from the server I could save it on a cloud or something. I can upload and display the image on the app using expo-image-picker but I just can't seem to get it to post it to the server using formData.
Also, why is that when I console.log formData why is it showing an empty object?
My code to loading the image and uploading it:
pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
console.log(result);
if(!result.cancelled)
{
this.setState({
image : result.uri
})
}
// ImagePicker saves the taken photo to disk and returns a local URI to it
let localUri = result.uri;
//console.log("localUri:", localUri)
let filename = localUri.split('/').pop();
console.log("filename:", filename)
// extract the filetype
//let fileType = localUri.substring(localUri.lastIndexOf(".") + 1);
//console.log(fileType)
let fileType = localUri.substring(localUri.lastIndexOf(":") + 1,localUri.lastIndexOf(";")).split("/").pop();
console.log("type:", fileType)
let formData = new FormData();
formData.append("photo", {
uri : localUri,
name: `photo.${fileType}`,
type: `image/${fileType}`
});
console.log("formdata", formData)
let options = {
method: "POST",
body: formData,
headers: {
Accept: "application/json",
"Content-Type": "multipart/form-data"
}
};
let response = await fetch(`${this.props.url}imagetest`, options)
result = await response.json()
console.log(result)
My simple code for api.php in Laravel is:
Route::post("/imagetest", function (Request $request) {
return ["uploaded" => $request->hasFile("photo")];
});
Found the solution at
send image using Expo
The problem I was having, I was testing it by running the code on web, when I ran it on the device I could see the formdata as well as the image was been uploaded too
How can I delete an image's file from the server using Parse Cloud Code. I am using back4app.com
After Deleting Image Row
I am getting the images urls, then calling a function to delete the image using its url
Parse.Cloud.afterDelete("Image", function(request) {
// get urls
var imageUrl = request.object.get("image").url();
var thumbUrl = request.object.get("thumb").url();
if(imageUrl!=null){
//delete
deleteFile(imageUrl);
}
if(thumbUrl!=null){
//delete
deleteFile(thumbUrl);
}
});
Delete the image file from the server
function deleteFile(url){
Parse.Cloud.httpRequest({
url: url.substring(url.lastIndexOf("/")+1),
method: 'DELETE',
headers: {
'X-Parse-Application-Id': 'xxx',
'X-Parse-Master-Key': 'xxx'
}
}).then(function(httpResponse) {
console.log(httpResponse.text);
}, function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
});
}
for security reasons, not is posible to delete directly the image from Back4App, using DELETE from SDK or REST API. I believe that you can follow the guide below:
https://help.back4app.com/hc/en-us/articles/360002327652-How-to-delete-files-completely-
After struggling with this for a while it seems to be possible through cloud function as mentioned here. One need to use MasterKey in the cloud code:
Parse.Cloud.define('deleteGalleryPicture', async (request) => {
const {image_id} = request.params;
const Gallery = Parse.Object.extend('Gallery');
const query = new Parse.Query(Gallery);
try {
const Image = await query.get(image_id);
const picture = Image.get('picture');
await picture.destroy({useMasterKey: true});
await Image.destroy();
return 'Image removed.';
} catch (error) {
console.log(error);
throw new Error('Error deleting image');
}
});
For me it was first confusing since I could open the link to that file even after I deleted the reference object in the dashboard, but then I found out that the dashboard is not calling Parse.Cloud.beforeDelete() trigger for some reason.
Trying to download the data from the url after deleting the file through the cloud code function returns 0kB data and therefore confirms that they were deleted.
I'm using parse on node. I have an express app, and a JS browser app, that is hosted off the express server.
At the moment the app has it's own login. It logs the user in on the client, and the client remains logged in.
I want to be able to log the client in via an express route /login. When they log in via this route, i want to log them in on the client side.
I have poured over documentation on this but I have struggled to find any real examples of how this is all done.
Here is some code i have found:
var cookieSession = require('cookie-session'),
// I added this require as it seems the code is using it;
session = require('express-session');
app.use(cookieSession({
name: COOKIE_NAME,
secret: "SECRET_SIGNING_KEY",
maxAge: 15724800000
}));
//
// This will add req.user if they are logged in;
//
app.use(function (req, res, next) {
Parse.Cloud.httpRequest({
url: 'http://localhost:1337/parse/users/me',
headers: {
'X-Parse-Application-Id': 'myAppId',
'X-Parse-REST-API-Key': 'myRestAPIKey',
'X-Parse-Session-Token': req.session.token
}
}).then(function (userData) {
req.user = Parse.Object.fromJSON(userData.data);
next();
}).then(null, function () {
return res.redirect('/login');
});
});
//
// login route;
//
app.post('/login', function(req, res) {
Parse.User.logIn(req.body.username, req.body.password).then(function(user) {
req.session.user = user;
req.session.token = user.getSessionToken();
res.redirect('/');
}, function(error) {
req.session = null;
res.render('login', { flash: error.message });
});
});
//
// and logout.
//
app.post('/logout', function(req, res) {
req.session = null;
res.redirect('/');
});
This looks pretty good, but this won't add a session on the client? How do parse the server login down to the client; Do i pass the session Token and use it on the client?
//
// If i call this code in the browser, i want the logged in user;
//
var current_user = Parse.User.current();
I have been unable to find any real code on-line that demonstrates all of this in the best-practice manner.
Is this the 'best practice' known solution or is there a better way of doing this?
I have this code included in my main.js:
var stripe = require("/cloud/stripe.js")("sk_test_*********");
//create customer
Parse.Cloud.define('createCustomer', function (req, res) {
stripe.customers.create({
description: req.params.fullName,
source: req.params.token
//email: req.params.email
}, function (err, customer) {
// asynchronously called
res.error("someting went wrong with creating a customer");
});
});
After pushing this code to my Heroku server the logs indicate that: Error: Cannot find module '/cloud/stripe.js'
I have also tried var stripe = require("stripe")("sk_test_*********"); but this returns the same error. Whenever I try add this new module to my server the whole server becomes dysfunctional. What workarounds are there to this? Thanks
Have you added Stripe to the requirements of your package.json file for your node project? If so, you should be able to reference it using the term require('stripe') as opposed to what you're doing.
I'll tell you what worked for me, I racked my brain on this for a day. Instead of using Cloud Code to make a charge, create a route on index.js. Something like this in index.js
var stripe = require('stripe')('sk_test_****');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: false
}));
app.post('/charge', function(req, res){
var token = req.body.token;
var amount = req.body.amount;
stripe.charges.create({
amount: amount,
currency: 'usd',
source: token,
}, function(err, charge){
if(err)
// Error check
else
res.send('Payment successful!');
}
});
I call this using jQuery post but you could also use a form.
When i use this function in Cloud Code Parse.User.current() return null.
I'm using parseExpressCookieSession for login.
Any advice?
var express = require('express');
var expressLayouts = require('cloud/express-layouts');
var parseExpressHttpsRedirect = require('parse-express-https-redirect');
var parseExpressCookieSession = require('parse-express-cookie-session');
// Required for initializing enter code hereExpress app in Cloud Code.
var app = express();
// Global app configuration section
app.set('views', 'cloud/views');
app.set('view engine', 'ejs'); // Switch to Jade by replacing ejs with jade here.
app.use(expressLayouts); // Use the layout engine for express
app.set('layout', 'layout');
app.use(parseExpressHttpsRedirect()); // Require user to be on HTTPS.
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('helloworld'));
app.use(parseExpressCookieSession({
fetchUser: true,
cookie: { maxAge: 3600000 * 24 }
}));
Parse.Cloud.beforeSave('Menu', function(request, response) {
var Business = Parse.Object.extend('Business');
var query = new Parse.Query(Business);
query.equalTo('profile', Parse.User.current().get('profile'));
query.find({
success: function(business) {
console.log(business);
response.success();
},
error: function(error) {
response.error(error.message);
}
});
});
app.listen();
This the code that i use to login/logout
app.post('/login', function(req, res) {
Parse.User.logIn(req.body.username, req.body.password).then(function(user) {
// Login succeeded, redirect to homepage.
// parseExpressCookieSession will automatically set cookie.
res.redirect('/');
},
function(error) {
// Login failed, redirect back to login form.
res.redirect('/');
});
});
// Logs out the user
app.post('/logout', function(req, res) {
Parse.User.logOut();
res.redirect('/');
});
It is an old question but answering for future reference.
Parse.User.current() works in Javascript SDK when used in clients ex. WebApp where users log in and the you can fetch the current user with that function.
To get the user calling a Cloud Code function or doing an operation on an object (beforeSave,afterSave,beforeDelete and so on) you use the request.user property it contains the user issuing the request to Parse.com.
More details about Parse.Cloud.FunctionRequest here: https://parse.com/docs/js/api/classes/Parse.Cloud.FunctionRequest.html
Example code:
Parse.Cloud.beforeSave('Menu', function(request, response) {
var requestUser = request.user;
// instance of Parse.User object of the user calling .save() on an object of class "Menu"
// code cut for brevity
});