User JsonWebToken in Angular -> Method Post - javascript

I built an website in node js on the web side I manage to log in to the website using axios.
export const logInFnc = async (email,password)=>{
try{
const login = await axios({
method:"POST",
url:"/api/v1/user/login",
data:{
email:email,
password:password
}
});
if(login.data.status = "success"){
showAlert('success','You have successfully logged in!!!');
window.setTimeout(()=>{
location.assign('/global-post')
},1500)
}
}catch(err){
showAlert('error',`There was a problem,you probably forgot your password or your email address is no longer valid.=>${err}`);
}
}
In the browser it works without problems as well as in the postman,
but in the angular it gives me an error of 400 and does not recognize anything

I think you have a problem with the URL, probably you are running a development server for angular in a port like 3000 and you have the API running in another port. Ensure this.
If the API is running in another port, you should change your URL param to add hostname + port, something like http://localhost:{API_PORT}/api/v1/user/login

I actually think that you are missing some words in the URL. Just copy the URL of the request (that you are using in postman) and use it in your angular project. Or create an enviroment file to save it there, and just grab it whenever you want.

Related

Next.js redirect from an API route

I am building a back-office app that requires users to sign in.
I have 2 external APIs:
API A : to manage user accounts and sessions
API B : to perform CRUD actions on another database (unrelated to users database)
The problem is that I don't want users to be able to perform calls to API B if their session is not valid. So I added some API endpoints in Next (under pages/api) that do the following actions:
verifying the validity of the session against API A
if session is valid: continue to step 3, if not: redirect to page /login
make the call to API B
Everything works fine if the session is valid but it fails if the session is not valid.
I have tried
res.redirect(307, '/login').end()
and
res.writeHead(307, { Location: '/login' }).end()
but it didn't work. It fails even by specifying the whole path (http://localhost:3000/login). What I don't understand is that I am successfully redirected to my /login page if I make the request directly from the browser (GET http://localhost:3000/api/data). It doesn't work when I make the request with Axios inside a React component.
Any idea how I can fix this?
As #juliomalves and #yqlim explained, I had to make the redirect manually based on the response of the API.
Faced same problem solve using below code:
Api
res.status(200).json({ success: "success" }) //add at last of the api to give response
page
import Router from 'next/router'
let res = await fetch('api', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
if (res.status == 200) {
Router.push('/location')
}
Answer is correct as #Jules Grenier sayes,but provided an example
You do not need .end(). Have you tried res.redirect(307, '/login')?
In Next.js v12 and v13, the following works for me.
// /api/example.js
const handler = async function (req, res) {
// custom logic
if (failed)
return res.redirect(307, '/login')
}
export default handler;
The API request must be initiated by a <form>.
redirect will not work with <fetch>

How to ping an IP address from a VueJS application?

Working on VueJS application, I want to create a function that pings a specific IP address and returns the time and status.
1- I used ping-lite but I got this error: Could not detect your ping binary..
I saw that in the node module they are checking the machine OS (running on Windows and WSL) and throwing that error if failing.
2- I then tried ping and I got this error:
(Promise/async): "TypeError: net.isIPv6 is not a function"
I was trying to executing the example code from their npm/github page:
var ping = require('ping');
var hosts = ['192.168.1.1', 'google.com', 'yahoo.com'];
for(let host of hosts){
let res = await ping.promise.probe(host);
console.log(res);
}
I wonder if the problems are related and if it's something with my environment/machine.
How to resolve this OR what's the best way to ping an IP address from a Vue app?
Ping is a node.js module not supported in the browser. This module would need to run server-side.
This could be accomplished us axios where you issue a GET call to the url and if you get a 200 back that indicates a successful call. This could also be accomplished using $ajax.
axios example
const response = await axios.get('https://api.github.com/users/mapbox');
if (response.status === 200) {
console.log('success'
}

TestCafe: How to test logout if user logged in from another machine

I have a scenario where I want to start running a test on chrome and at specific point I want my test to open different browser (firefox) and to do the same steps as in chrome then go back to chrome again and verify a change in ui. Is there anyway to do this using testcafe?
I am glad I asked.
In order to test if a login in another browser triggers a logout in the current browser, there is no need to run a different browser.
You can send the according login command from your test code.
node.js builtin standard http library is sufficient for that task. The official documentation has a specific section on http requests: https://nodejs.org/en/knowledge/HTTP/clients/how-to-create-a-HTTP-request/
I personally prefer the fetch API as available in the browser. node-fetch provides this API in node.
so your test code could look a little like this:
import 'node-fetch';
import { URLSearchParams } from 'url';
// we assume we get page state and interaction from this seperate module
import { loginAction, getIsLogged } from './page-actions';
fixture `login logut`
.page `http://your.app/`;
test('User is logged out if logged in somewhere else', async t => {
// perform the login actions to login as "username"
await loginAction(t, 'yourUsername', 'yourPassword');
await simulateLoginFromSomewhereElse('yourUsername', 'yourPassword');
await t.expect(getIsLoggedIn(t)).eql(false);
});
async function simulateLoginFromSomewhereElse(username, password) {
// build the (form) data to be sent to the server
const params = new URLSearchParams();
params.append('username', 'yourUsername');
params.append('password', 'yourPassword');
await fetch(`http://your.app/login`, { method: 'POST', body: params });
}

MarkLogic App Server Custom Login Page sessionID cookie with GET request

I am trying to develop a two-tier web application with MarkLogic-9 employing server side JavaScript and HTTP app servers. I have a simple page that prompts for username/password and sends a GET request via Ajax to the app server (application-level authentication).
My login.sjs script:
//generate object with field names from Request params
var params ={}; //JSON parsed URL parameters
var field_names = xdmp.getRequestFieldNames().toArray();
for(var fname_idx in field_names){
params[field_names[fname_idx]] = String(xdmp.quote(xdmp.getRequestField(String(field_names[fname_idx]))));
}
//get username and password from passed paramters
var username = params.username;
var password = params.password;
var ret = xdmp.login(username,password);
ret;
I have tested this and verified that it works by printing the xdmp.currentUser().
The login page then redirects to a home page that displays basic user info. My problem is that I cannot figure out how to preserve the current user's session after the client-side redirect to the homepage.
The app server has application-level authentication and a default user called Login-User, which is a custom user that has only the privileges necessary to log in (xdmp:login). The app server is hosted on localhost:8601. I have found that when I run login.sjs directly from the browser (i.e. typing localhost:8601/login.sjs?username=test_user&password=test_password), my browser gets a cookie with the sessionID. However, when I run the login.sjs via an Ajax GET request, my browser does not get any cookies. I don't know if this is the issue but I though it might be worth mentioning.
I am still a MarkLogic novice so I may be going about this the completely wrong way. Basically, how do I go about continuing a single user's session after redirecting to a new page? Do I use cookies to save the sessionID? Should I preserve the username and password in local storage and log in every time the website invokes a new .sjs file?
For completeness, here is the client side js I use to make the Ajax call to login. Pretty self-explanatory. The login.sjs file just returns true/false if the login was successful.
function createLoginEar(){
$("#login-button").click(function(event){
var un = $("#username").val();
var pw = $("#password").val();
if(un){
params.username = $("#username").val();
}
if(pw){
params.password = $("#password").val();
}
event.preventDefault(); //prevent form from clearing
console.log("input entered");
$.ajax({
type: "GET",
url: url,
data: params,
success: function(data){
if(data == "true"){
console.log("worked");
window.location.href = "homepage.html";
} else{
invalidLogin();
}
},
error: function(data){
invalidLogin();
}
})
})
}
The problem is that once the page redirects to homepage.html, there seems to be no memory of the user having logged in and when homepage.html calls any .sjs file, the user resets to the default which is "Login-User".
Thanks in advance.
I suggest you look at Chapter 15 of the security guide.
There is a sample of application level authentication using Custom Login Pages.
Lastly, the sample of IP-based login is not what you need, but shows you how to use xdmp.Login to switch users from the default application user.
I think that with all of that covered (not much to it really), you will be able to walk backthrough your setup and re-work it.
The issue was that my browser was not collecting cookies from the login because of issues that are over my head, but I found the answer in another post so this may be a duplicate.
Get and store cookie (from Set-Cookie) from an AJAX POST response.
I just had to include the following line in my ajax request:
xhrFields: { withCredentials: true },
Since this will throw an error if you have a wildcard in you Access-Control-Allow-Origin header, I also had to change this line:
xdmp.addResponseHeader('Access-Control-Allow-Origin', '*');
to this:
xdmp.addResponseHeader('Access-Control-Allow-Origin', 'http://localhost:8010');
And now my browser collects cookies.

How to connect to Asana's API using Asana's JS/Ruby library

I have a backend API written in Ruby and a client App that uses Angular. I'd like to authenticate the user to authenticate the user via the Angular app.
As such I've created my App on Asana. I'm having a few issues though:
First issue: I'm using the Authorisation Endpoint of Authorisation Code Grant. After reading the docs, I realised that I have to use Implicit Grant instead, which is more suitable for a browser-based app, however when I change it to Implicit Grant, save it and reload the page, it changes back to Authorisation Code Grant.
Then on my Angular App I have the following code:
var client = Asana.Client.create({
clientId: 133,
clientSecret: 'mysecretcode',
redirectUri: 'http://localhost:7699/profile'
});
client.useOauth({
flowType: Asana.auth.PopFlow
});
client.authorize().then(function () {
console.log('Auth completed');
}).catch(function (err) {
console.log(err);
});
client.users.me().then(function (result) {
console.log(result);
});
The above almost works. I do get redirected to Asana for the authorisation part, once I click on "Allow", I'm redirected back to my app, and I do get a code as part of the url. The code is something like:
http://localhost:7699/profile#access_token=very_long_string
If I understood the docs correctly, I could use the above access_token to make my first request. When I tried using Asana's JS library to make a request like so:
client.users.me().then(function (result) {
console.log(result);
});
Please note the client object I'm referring to is the same I've created earlier for authorisation. The above returns a 401, Unauthorised code.
Then I tried the following:
var params = {
grant_type: 'refresh_token',
client_id: 876787,
client_secret: 'some_secret',
redirect_uri: 'http://localhost:7699/profile',
code: my_access_code
};
$http.post('https://app.asana.com/-/oauth_token', params).then(function (result) {
console.log(result);
});
Which also gets me a 401 unauthorised code.
What am I doing wrong here?
I recommend you start by copy-pasting one of the examples from the node-asana examples directory into your app, and seeing if that works.
If you want to keep using the popup flow, the thing I suspect you are missing is the call to Asana.auth.PopupFlow.runReceiver(); in popup_receiver.html. This should be on the page pointed to by your redirect_uri, and tells the page that created the popup the auth data it needs to make subsequent requests. Also note how the page that originates the authentication request (popup.html) includes actions that happen after authentication in the callback passed to then: this ensures that these actions happen only after the user completes authentication through the popup.

Categories