Why can't I access wix's My Collection from my backend code? - velo

Because I add them from the dashboard and fetch them into my flutter app with api
this is my api code:
export async function get_adminData(request) {
let options = {
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
}
};
try {
const results = await wixData.query("Admin")
.eq("url", "specificValue")
.eq("image", "specificValue")
.eq("text", "specificValue")
.eq("article", "specificValue")
.find();
if (results.items.length > 0) {
options.body = results.items;
return ok(options);
} else {
return notFound({});
}
} catch (error) {
options.body = {
"error": error
};
return serverError(options);
}
}
But I can only access collects that are under Wix App Collection.
I am new to wix and flutter so please help.

First and most obvious issue here is usually permissions issue
Try to check everything with this article
https://support.wix.com/en/article/velo-exposing-a-site-api-with-http-functions
Permissions HTTP functions, no matter how they are invoked, always run
with the permissions of an anonymous site visitor.

Related

Fitbit URL callback giving a response of NULL

I'm having trouble getting a response from a callback uri and I would really appreciate any help you could give me.
I am trying to use the Fitbit API which requires you to use a callback url to get an Auth Code.
Workflow:
1. Go to Fitbit url to get user to allow the app access to their personal data.
2. User agrees to the conditions
3. User gets redirected to my API
4. The API returns the code from (Code is located in URL and I can access it)
5. I console.log the code out to verify it
6. API returns the code
7. I work with code then exchanging it for an access token.
The problem is that I don't return the code (Or anything )when I return to the app even though I can console.log it on the API. The response I get is NULL
Here is the URL:
url = "https://www.fitbit.com/oauth2/authorize?response_type=code&client_id=CLIENT_ID&redirect_uri=https://REDIRECT_URL&scope=activity%20heartrate%20location%20nutrition%20profile%20settings%20sleep%20social%20weight&expires_in=604800";
I then open the URL in the InAPPBrowser successfully:
if (url !== "") {
const canOpen = await Linking.canOpenURL(url)
if (canOpen) {
try {
const isAvailable = await InAppBrowser.isAvailable()
if (isAvailable) {
const result =InAppBrowser.open(url, {
// iOS Properties
dismissButtonStyle: 'done',
preferredBarTintColor: 'gray',
preferredControlTintColor: 'white',
// Android Properties
showTitle: true,
toolbarColor: '#6200EE',
secondaryToolbarColor: 'black',
enableDefaultShare: true,
}).then((result) => {
console.log("Response:",JSON.stringify(result))
Linking.getInitialURL().then(url => {
console.log("Tests: ",url)
this._setTracker(url as string);
});
})
} else Linking.openURL(url)
} catch (error) {
console.log("Error: ",error)
}
}
}
From here the URL opens successfully.
Here is the API now which is done in Typescript on AWS serverless and Lambda
export const handler: APIGatewayProxyHandler = async (event, _context, callback) =>{
let provider = event.path
//prints code
let x = event.queryStringParameters
console.log("Code: ",x)
const response = {
statusCode: 200,
body: "Success"
};
return response;
}
Please let me know if further detail is required?
Thank you!
Right so it turns out what I was doing was correct apart from the response should have been 301 which is a redirect response.
const response= {
statusCode: 301,
headers: {
"location": `app://CALLBACK RESPONSE ADDRESS?type=${provider}`
},
body: "Boom"
}

WIX use Corvid API with 3rd party website

Is there a way to use the WIX Corvid API for external App, to retrieve the product Data.
I'm not able to find the SDK which we can use.
Our Client Wants to manage it product from a different platform.
we want a way to create/update/get product and order from the WIX store.
Make sure you do not get CORS error:
Change the below origin strings to your own origin.
This should resolve your CORS issue.
import {ok, badRequest, response} from 'wix-http-functions';
function validate(origin) {
if (origin == "http://localhost:4200" || origin == "http://localhost:4201") {
return true;
} else {
return false;
}
}
export function options_yourFunctionName(request) {
console.log(request);
let headers = {
"Access-Control-Allow-Methods": "POST, GET, OPTIONS",
"Access-Control-Max-Age": "86400"
}
if (validate(request.headers.origin)) {
headers["Access-Control-Allow-Origin"] = request.headers.origin;
}
return response({ "status": 204, "headers": headers });
}
export function post_yourFunctionName(request) {
console.log("post_duxLogin");
const _response = {
"headers": {
"Content-Type": "application/json",
}
};
if (validate(request.headers.origin)) {
_response.headers["Access-Control-Allow-Origin"] =
request.headers.origin;
_response.headers["Access-Control-Allow-Headers"] = "Content-Type";
}
// Perform other things here....
}
You need to use HTTP Functions to expose your sites API. Then you can send POST requests via the external app to your site's endpoint and based on the request parameters or body you can query your product data (provided its in a database collection) and return items to the external service.
As far as create/update/get goes, you can only do that as much as the Wix Stores Backend API allows you to: https://www.wix.com/corvid/reference/wix-stores-backend.html

custom authorizers in Amazon API Gateway 500 error

I use Serverless-Authentication-boilerplate and want to map custom error response. But it always return 500 error.
authorize.js
// Authorize
function authorize(event, callback) {
let providerConfig = config(event);
try {
let data = utils.readToken(event.authorizationToken, providerConfig.token_secret);
console.log("Decrypted data: " + JSON.stringify(data));
let methodArn = event.methodArn.replace(/(GET|POST|PUT|DELETE)/g, '*').replace(/mgnt.+/g, 'mgnt/*');
console.log(`Change methodArn to: ${methodArn}`);
// TODO: handle expiration time validation
callback(null, utils.generatePolicy(
data.id, // which is $context.authorizer.principalId
'Allow',
methodArn));
} catch (err) {
console.log(err);
callback('401 Unauthenticated');
}
}
s-function.json
responses:{
"401 Unauthenticated.*": {
"statusCode": "401"
},
"default": {
"statusCode": "200",
"responseModels": {
"application/json;charset=UTF-8": "Empty"
},
"responseTemplates": {
"application/json;charset=UTF-8": ""
}
}
}
After ask to Amazon Web Services.
Unfortunately the mapping of the Authorizer is not currently configurable and every returned error from a lambda function will map to a 500 status code in API gateway. Moreover, the mapping is performed on an exact string match of the output, so, in order to return the intended 401 Error to the client, you should execute a call to 'context.fail('Unauthorized');.
Finally, I change
callback('401 Unauthenticated');
to
context.fail('Unauthorized');
and work fine.
Sharing to whom may encounter this.

How redirect to login page when got 401 error from ajax call in React-Router?

I am using React, React-Router and Superagent. I need authorization feature in my web application. Now, if the token is expired, I need the page redirect to login page.
I have put the ajax call functionality in a separated module and the token will be send on each request's header. In one of my component, I need fetch some data via ajax call, like below.
componentDidMount: function() {
api.getOne(this.props.params.id, function(err, data) {
if (err) {
this.setErrorMessage('System Error!');
} else if (this.isMounted()) {
this.setState({
user: data
});
}
}.bind(this));
},
If I got 401 (Unauthorized) error, maybe caused by token expired or no enough privilege, the page should be redirected to login page. Right now, in my api module, I have to use window.loication="#/login" I don't think this is a good idea.
var endCallback = function(cb, err, res) {
if (err && err.status == 401) {
return window.location('#/login');
}
if (res) {
cb(err, res.body);
} else {
cb(err);
}
};
get: function(cb) {
request
.get(BASE_URL + resources)
.end(endCallback.bind(null, cb));
},
But, I can't easily, call the react-router method in my api module. Is there an elegant way to implemented this easy feature? I don't want to add an error callback in every react components which need authorized.
I would try something like this:
Use the component's context to manipulate the router (this.context.router.transitionTo()).
Pass this method to the API callout as a param.
// component.js
,contextTypes: {
router: React.PropTypes.func
},
componentDidMount: function() {
api.getOne(this.props.params.id, this.context.router, function(err, data) {
if (err) {
this.setErrorMessage('System Error!');
} else if (this.isMounted()) {
this.setState({
user: data
});
}
}.bind(this));
},
// api.js
var endCallback = function(cb, router, err, res) {
if (err && err.status == 401) {
return router.transitionTo('login');
}
if (res) {
cb(err, res.body);
} else {
cb(err);
}
};
get: function(cb, router) {
request
.get(BASE_URL + resources)
.end(endCallback.bind(null, cb, router));
},
I know you didn't want a callback on each authenticated component, but I don't think there's any special react-router shortcuts to transition outside of the router.
The only other thing I could think of would be to spin up a brand new router on the error and manually send it to the login route. But I don't think that would necessarily work since it's outside of the initial render method.

Parse for javascript - "error 209 invalid session token" when signing up a new user

I wrote a simple function in an angularJS application for signing up new users:
$scope.registerUser = function(username, password) {
var user = new Parse.User();
user.set("username", username);
user.set("email", username);
user.set("password", password);
user.signUp(null, {
success: function(result) {
console.log(result);
$scope.registerUserSuccess = true;
$scope.registerUserError = false;
$scope.registerUserSuccessMessage = "You have successfully registered!";
$scope.$apply();
$timeout(function(){
$state.go("user");
}, 1000);
},
error: function(user, error) {
$scope.registerUserError = true;
$scope.registerUserSuccess = false;
$scope.registerUserErrorMessage = "Error: [" + error.code + "] " + error.message;
$scope.$apply();
}
});
Initially it worked fine, but when I deleted all the users directly through Parse.com, I can't sign up new users using this function anymore. Each time I get error 209 invalid session token. Here's a screenshot of my Parse database:
I've googled the error message and the solution is always to log out the current user. However, if no users exist this isn't an action I can possibly take.
So I would not only like to fix this problem, but also know how to prevent it in the future so my application can be used safely.
Edit: I created a user directly in Parse.com, wrote a function to log in that user, but got the same error. I am completely stuck until this session issue is resolved.
delete all your session tokens, and anything else Parse related really, from local storage:
if needed turn off legacy session tokens, and follow migration tutorial from scratch:
I encountered this same error when building apps with react native using back4app. to clear anything Parse related, from local storage:
add
import { AsyncStorage } from "react-native";
in to the page and Use
AsyncStorage.clear();
See Example Below:
import { AsyncStorage } from "react-native";
import Parse from "parse/react-native";
// Initialize Parse SDK
Parse.setAsyncStorage(AsyncStorage);
Parse.serverURL = "https://parseapi.back4app.com"; // This is your Server URL
Parse.initialize(
"APPLICATION_ID_HERE", // This is your Application ID
"JAVASCRIPT_KEY_HERE" // This is your Javascript key
);
.........
_handleSignup = () => {
// Pass the username, email and password to Signup function
const user = new Parse.User();
user.set("username", "username);
user.set("email", "email");
user.set("password", "password");
user.signUp().then(user => {
AsyncStorage.clear();
if (condition) {
Alert.alert(
"Successful!",
"Signin Successful! Log in to your account.",
[
{
text: "Proceed",
onPress: () => {
//in this example, i navigated back to my login screen
this.props.navigation.navigate("LoginScreen");
}
}
],
{ cancelable: false }
);
}
})
.catch(error => {
Alert.alert("" +error);
});
};

Resources