Connecting Aurelia with backend API - rest

Context: I'm starting a new project for my company. It's been many years since I've done some web development and decided to build it using the latest platforms (so I'm a still new to all of this).
Current stack:
Aurelia frontend (running on localhost:9000)
Backend REST API using ExpressJS (running on localhost:8000)
PostGreSQL database running on AWS, providing data for the backend
Question: I can't seem to connect my frontend with my backend properly.
Here is my code:
import {inject} from "aurelia-framework";
import {HttpClient} from "aurelia-http-client";
#inject(HttpClient)
export class Login {
constructor(httpClient){
this.http = httpClient;
}
signIn() {
const url = 'http://localhost:8000/api/user/demo/test';
this.http
.get(url)
.then(data => {
console.log("data");
console.log(data);
})
.catch(error => {
console.log('Error getting ' + url);
console.log(error);
});
};
}
This always end up in the catch block, with a "response: ProgressEvent"
If I put the url in the browser I get a proper JSON:
{"status":"success","data":[],"message":"Retrieved ALL users"}
The code above only works for 'local' content, i.e. localhost:9000. As soon as I need content from somewhere else I get this error. What am I missing?

I think that CORS is not allowing you to access localhost:8000 from localhost:9000. To solve this, you should enable your ExpressJS server to accept CORS requests from localhost:9000 (or all hosts using a wildcard "*").
Look into these resources:
https://enable-cors.org/server_expressjs.html
https://github.com/expressjs/cors
Or search Google for 'expressJS cors'.

Related

How to Properly Set Permissions for a Custom Strapi Plugin

Strapi Version: 4.1.5
Operating System: Debian GNU/Linux 9
Database: PostgreSQL 13
Node Version: v14.16.0
NPM Version: 6.14.11
Yarn Version: v1.22.5
Hi everyone, I can’t seem to find consistent information on how to use permissions with a custom plugin in Strapi. I want to make an endpoint available to my front-end (Next.JS) application, but only when the front-end application has authenticated as a user and using the JWT that is returned from authenticating with Strapi. I keep getting a 401 returned.
Here’s what I’m doing:
I used this page to set up authentication in Strapi. I have a user created in Strapi, and from the front-end, I can authenticate and it returns a JWT token. When I set up collection types to only be accessible with the “authenticated” role, I can access those collection types in the api using this JWT token. So all of that works. The problem is that I can’t get this to work with my custom plugin, and I’m not sure why. I still get a 401 error instead.
Here’s how I set up the permissions:
Based on this page, I initially tried to leverage the isAuthenticated permission that the Users & Permissions plugin provides:
{
method: "GET",
path: "/progress",
handler: "memberProgress.getProgress",
config: {
policies: ['plugins::users-permissions.isAuthenticated']
},
},
Unfortunately, this did not work. The server raised an error, saying that this could not be found. So back on the document linked above, I decided to take the approach of creating my own gloabl permission. I created src/policies/is-authenticated.js with the following contents:
module.exports = (policyContext, config, { strapi }) => {
if (policyContext.state.user) { // if a session is open
// go to next policy or reach the controller's action
return true;
}
return false; // If you return nothing, Strapi considers you didn't want to block the request and will let it pass
};
Then, I modified my plugin’s route as follows:
{
method: "GET",
path: "/progress",
handler: "memberProgress.getProgress",
config: {
policies: ['global::is-authenticated']
},
},
This is all based on that document I linked to. Unfortunately, this still does not work. It seems to find the permission (server doesn’t raise an error about it), but when I try to access my plugin’s endpoint with the JWT token, I just get a 401 error.
Here is how I’m trying to access the endpoint on the front-end:
// VERIFIED, auth works and I get the expected jwt
const strapiAuth = await strapiApiAuth();
if ( strapiAuth && strapiAuth.hasOwnProperty("jwt") ) {
try {
const response = await axios.get(
`${process.env.STRAPI_BACKEND_URL}/member-progress/progress?year=2022&name=&pageSize=10&page=1`,
{
headers: {
Accept: "application/json",
Authorization: `Bearer ${strapiAuth.jwt}`
},
timeout: 500,
}
);
console.log(response);
} catch (error) {
// This is where I land with the 401 error
console.log(error);
}
}
Strapi check if you have a valid jwt by default with "authenticated" role, but you must mark the permission to your custom endpoint in "Settings→User & Permission Plugin→Roles" of admin panel also.

Http request working on ionic serve but doesn't work on "ionic cordova run android --device"

I am using Ionic native http to make server requests. The server is hosted on aws and the apis are up and running (verified by postman).
When i do ionic serve the requests go through and work but when i try to run it on device it doesnt work. On inspection i get "net::ERR_CLEARTEXT_NOT_PERMITTED" and post is sent as OPTIONS
ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://18.220.143.133/api/login", ok: false, …}
already tried adding to config.xml
login(user: User): Observable<AuthResponse> {
return this.httpClient.post('http://18.220.143.133/api/login', user, {
headers: new HttpHeaders().set('Content-Type', 'application/json'),
}).pipe(
tap(async (res: AuthResponse) => {
if (res.success == true) {
await this.storage.set('user',res.user);
await this.storage.set('ACCESS_TOKEN', res.token);
this.authSubject.next(true);
}
})
);
}
I expect http requests to go through from mobile devices as well.
The same happened to me, until in the config.xml file I added:
<preference name = "android-targetSdkVersion" value = "27" />
It has to do with your CORS for the API call. This may help. Also, since you're using Angular HTTP requests, check here HTTP request from angular will send with method OPTIONS instead of POST.

Oauth + Laravel + Vuejs + MongoDB 500 Internal Server Error

everyone. I am currently developing a web app. I started to develop on a laptop. Then I mapped the code folder on the laptop to my pc. On my laptop, everything works correctly. But on the PC i cant get authenticated. I get 500 Internal server error. I am using Oauth, Laravel, laravel passport, vuejs and mongodb. i am currently accessing the mongodb server remotely if it matters.
Here is the login method
methods: {
login(){
var data = {
client_id:'58a08f3588053a6d947dc902',
client_secret:'E1STUJipgmCO2h9gtkN2Vl1fTpgJCuiW2SrktshM',
grant_type:'password',
username:this.userid,
password:this.password
}
this.$http.post("http://localhost:8000/oauth/token", data)
.then(response => {
console.log(response)
})
/*
.then(function(response){
console.log(response)
})*/
}
}
Thank you

LDAP authentication fails on ripple and actual device but not on browser

I'm trying to get an authorization token for an Ionic App from a LDAP service in a remote server.
I can get the auth token when I run the Ionic App in the browser with the command ionic serve and when I use Postman,
BUT it takes lot of time and eventually fails when I debug using ripple for the App or when I test on the phone or tablet.
The error says:
status: 503
statusText: Service Unavailable
data: html code from http://s3.amazonaws.com/heroku_pages/error.html
var deferred = $q.defer();
var req = {
method: 'GET',
url: 'http://host:port/adap?bind=token',
headers: {
Authorization: 'Basic <username>:<password>'
}
};
$http( req )
.then(function(data, status, headers, config) {
console.log(data);
deferred.resolve(data.data);
})
.catch(function(data) {
console.error(data.data);
deferred.reject(err);
});
return deferred.promise;
Does anybody have some hint about this issue?
Thanks in advance
For what you say the service is available, so the problem must be in the app side.
Check IP tables, and check ripple's proxy and set it to none.

How to use node.js Context.IO behind a department proxy?

Here is my node.js code to use Context.IO in a RESTful way rather than IMAP.
var ContextIO = require('contextio');
var ctxioClient = new ContextIO.Client({
key: 'MY_KEY',
secret: 'MY SECRET'
});
ctxioClient.accounts().get(function(err, res) {
if (err) throw err;
console.log(res);
});
When I executed the above code on my dormitory computer, everything worked fine. However, when I executed the code on my office computer, which is behind a departmental proxy, the code simply timed out. My department provides both http and socks proxies for internet access. The question is how to set it up in node.js?
By the way, I also tried
socksify node code.js
It did not time out. Instead, it just did not response.