How to do axios.get when the url is password protected in react native? - react-native

I am trying to do axios.get. When I put the url on browser and hit enter browser assk me username and password. But I don't know how to set the password and username in axios header in a get method. The Swagger UI is http://api.myslambook.in/swagger/#
This is my code:
import axios from 'axios';
import base64 from 'react-native-base64'
export function FriendRequests ( ) {
state = {
serverData: [],
};
const tok = 'myusername:mypassword';
const hash = base64.encode(tok);
const Basic = 'Basic ' + hash;
axios.get('http://api.myslambook.in/users', {headers : { 'Authorization' : Basic }})
.then(res => {
const serverData = res.data;
this.setState({ serverData });
})
.catch(err => console.log(err));
}
I am getting this error in console:
Request failed with status code 401.
Can anyone help me? Thanks in advance.

For basic authentication the auth object can be used:
axios.get('http://api.myslambook.in/users', {
auth: {
username: 'janedoe',
password: 's00pers3cret'
}
}).then(res => {
const serverData = res.data;
this.setState({serverData});
}).catch(err => console.log(err));
to fix the Can't find variable: btoa error:
npm i -S base-64
and add the following to index.js:
import {decode, encode} from 'base-64'
if (!global.btoa) {
global.btoa = encode;
}
if (!global.atob) {
global.atob = decode;
}
Checkout the docs: https://github.com/axios/axios#request-config

Related

Jest / Vue Test Utils - Axios mock works only in test file itself

I'm trying to create my first Vue.js 2.x tests and I could use some help:
For some reason, mocking only works on functions defined in the .spec file, but not on imported ones.
For example, the following code works:
// login.spec.js file - note "login" is defined here (which uses "axios" mock)
function login(email, password) {
// I'm defined inside the spec file!
let payload = { email, password };
return axios.post(loginApiUrl, payload);
}
jest.mock('axios');
beforeEach(() => {
jest.clearAllMocks()
})
describe('Login.vue', () => {
it('sample test', async () => {
const data = { a: 1 };
axios.post.mockResolvedValueOnce(data);
let res = await login('abcd#example.com', 'password')
expect(axios.post).toHaveBeenCalledTimes(1)
// The mock works!
While this doesn't:
// login.spec.js file
import auth from '#/api/auth.js'
jest.mock('axios');
beforeEach(() => {
jest.clearAllMocks()
})
describe('Login.vue', () => {
it('sample test', async () => {
const data = { a: 1 };
axios.post.mockResolvedValueOnce(data);
let res = await auth.login('abcd#example.com', 'password')
expect(axios.post).toHaveBeenCalledTimes(1)
// This doesn't work (fetching the original URL)
// auth.js
import axios from 'axios'
import { loginApiUrl } from '../helpers/constants'
const auth = {
login(email, password) {
// params are string payloads login request
// return: axios Promise
let payload = { email, password };
console.log('login')
return axios.post(loginApiUrl, payload);
}
}
export default auth;
Note that the second code makes a call to the actual URL (without the mock)
Anyone has an idea?
Thanks in advance.

IBM IAM IamAuthenticator getToken is not a function

I'm trying to get a token to use IBM Watson Speech-to-Text in my app. Here's my code:
const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const authenticator = new IamAuthenticator({
apikey: 'myApiKey',
});
authenticator.getToken(function (err, token) {
if (!token) {
console.log('error: ', err);
} else {
// use token
}
});
The error message is authenticator.getToken is not a function.
The documentation says:
string IBM.Cloud.SDK.Core.Authentication.Iam.IamAuthenticator.GetToken ( )
I've tried both getToken and GetToken. Same error message. The code isn't complicated, what am I doing wrong?
This is what worked for me with the latest ibm-watson node-sdk,
Install node-sdk with this command
npm install --save ibm-watson
Then, use this code snippet in your app.js or server.js node file to receive the IAM access token
const watson = require('ibm-watson/sdk');
const { IamAuthenticator } = require('ibm-watson/auth');
// to get an IAM Access Token
const authorization = new watson.AuthorizationV1({
authenticator: new IamAuthenticator({ apikey: '<apikey>' }),
url: ''
});
authorization.getToken(function (err, token) {
if (!token) {
console.log('error: ', err);
} else {
console.log('token: ', token);
}
});
You can also directly use the IamAuthenticator with Speech to Text
const fs = require('fs');
const SpeechToTextV1 = require('ibm-watson/speech-to-text/v1');
const { IamAuthenticator } = require('ibm-watson/auth');
const speechToText = new SpeechToTextV1({
authenticator: new IamAuthenticator({ apikey: '<apikey>' }),
url: 'https://stream.watsonplatform.net/speech-to-text/api/'
});
const params = {
// From file
audio: fs.createReadStream('./resources/speech.wav'),
contentType: 'audio/l16; rate=44100'
};
speechToText.recognize(params)
.then(response => {
console.log(JSON.stringify(response.result, null, 2));
})
.catch(err => {
console.log(err);
});
// or streaming
fs.createReadStream('./resources/speech.wav')
.pipe(speechToText.recognizeUsingWebSocket({ contentType: 'audio/l16; rate=44100' }))
.pipe(fs.createWriteStream('./transcription.txt'));
See my answer in your other post that might help. You use BearerTokenAuthenticator if you want to manage the token authentication process yourself.

How can I verify token google recaptcha 3 on adonis js?

I using vue as my front end. I send token from my front end like this :
let payload = {
token: tokenCaptcha
}
axios.post(`http://127.0.0.1:3333/api/v1/category`, payload)
.then(response => {
return response.data
}).catch(
error => {
console.log(error)
})
The token will used to verify on the backend. My backend using adonis.js
The script of controller like this :
'use strict'
class CategoryController {
async store ({ request, response }) {
return request.input('token')
}
}
module.exports = CategoryController
My routes like this :
Route.group(()=>{
Route.post('category', 'CategoryController.store')
}).prefix('api/v1')
How can I verify the token on adonis.js(backend)?
I had search reference. But I don't find it
You need to use axios. Something like:
const axios = use('axios')
const Env = use('Env')
const querystring = use('querystring')
async store({ request, response }) {
const data = request.only(['token'])
try {
const data_request = await axios.post('https://www.google.com/recaptcha/api/siteverify', querystring.stringify({ secret: Env.get('RECAPTCHA_PRIVATE_KEY'), response: data['token'], remoteip: '172.217.23.110' }))
if (!data_request.data.success) {
//If the recaptcha check fails
...
}
} catch (error) {
...
}
}
Google documentation - Verifying the user's response
This code is made for v2. But the verification is the same : https://developers.google.com/recaptcha/docs/v3#site_verify_response

NuxtJs - Cannot read property 'headers' of undefined

I'm a newbie in NuxtJs. I'm trying to implement an external API Call with axios which I get token and store it on cookie. Everything works well in development. But when I try to run npm run generate it gives me errors that I don't know what to do.
When I delete nuxtSeverInit, npm run generate runs smoothly. And after some research, i think that nuxtServerInit that I'm using shouldn't be used. Can anyone please tell me how to make it work.
This is the first project in a new company, so I'm trying to prove myself. Please help me with it. Will you.
Click here for image that shows the error that appears after npm run generate
This is store/index.js file
import Vuex from 'vuex'
var cookieparser = require('cookieparser')
const createStore = () => {
return new Vuex.Store({
state: {
auth: null,
},
mutations: {
update (state, data) {
state.auth = data
}
},
actions: {
nuxtServerInit ({ commit }, { req }) {
let accessToken = null
if (req.headers.cookie) {
var parsed = cookieparser.parse(req.headers.cookie)
if(parsed){
accessToken = parsed.auth
}
}
commit('update', accessToken)
},
}
})
}
export default createStore
middleware/authenticated.js file
export default function ({ store, redirect }) {
// If the user is not authenticated
if (!store.state.auth) {
return redirect('/login')
}
}
middleware/notAuthenticated.js file
export default function ({ store, redirect }) {
// If the user is authenticated redirect to home page
if (store.state.auth) {
return redirect('/app/dashboard')
}
}
login.vue file
validateBeforeSubmit() {
this.$validator.validateAll().then((result) => {
if (result) {
this.button_title = 'One moment ...';
let submitted_user_data = {
'username': this.emailAddress,
'client_id': this.user_uuid,
'password': this.password,
}
MerchantServices.do_user_login(submitted_user_data)
.then(response => {
let access_token = response.data.access_token;
this.postLogin(access_token);
})
.catch(error => {
this.$refs.invalid_credentials.open();
this.button_title = 'Sign in'
});
return;
}
});
},
postLogin: function(access_token_val) {
if(access_token_val != ''){
setTimeout(() => {
const auth = {
accessToken: access_token_val
}
this.$store.commit('update', auth)
Cookie.set('auth', auth)
this.$refs.invalid_credentials.open();
this.button_title = 'Sign in'
this.$router.push('/app/dashboard')
}, 1000)
}else{
alert('hello')
}
},
and the last user login api call which also returns the token.
do_user_login(user){
var user_details = 'username='+user.username+'&client_id='+ user.client_id +'&grant_type=password&password='+user.password+''
return axios.post('myapiurl', user_details )
.then(response => {
return response;
});
},
Acording to Nuxt Docs req is not available on nuxt generate.
You should use nuxt build and than nuxt start after that.

Token not being added to local storage after successful request

I'm having trouble with the aurelia-auth plugin. I can request a token from my back-end and get a successful response - however, my app doesn't appear to be authenticated and no token is saved to local storage.
auth-config.js
var config = {
baseUrl: 'http://localhost:64794',
signupUrl: 'users',
loginUrl: 'api/values/PostPassword',
tokenName: 'id_token',
loginRedirect: '#/welcome',
authHeader: 'Authorization',
authToken: 'Bearer',
storage: 'localStorage'
}
export default config;
login.js
import {AuthService} from 'aurelia-auth';
import {inject} from 'aurelia-framework';
#inject(AuthService)
export class Login {
heading = 'Login';
email = '';
password = '';
loginError = '';
constructor(auth) {
this.auth = auth;
};
login() {
return this.auth.login(this.email, this.password)
.then(response => {
console.log("Login response: " + response);
console.log("Auth: " + this.auth.isAuthenticated());
})
.catch(error => {
this.loginError = error.response;
});
};
}
Console output:
Login response: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImIiLCJuYmYiOjE1MDkyNzkxMzYsImV4cCI6MTUwOTI4MDMzNiwiaWF0IjoxNTA5Mjc5MTM2fQ.4QZu8pQI-K_71x_CKT9ANu1vQD7VvVUcyep51CvvCXg
login.js:27 Auth: false
Any advice would be appreciated.
token (or the object containing it) is expected to be the value of prop 'access_token' in the response by default in aurelia-auth
so you need to change the structure of your api response to
{ access_token: YOUR_TOKEN }
if you have no control over the server, you could still extract the token by overriding the default config. one in question here is responseTokenProp, more here
also, for a clearer picture as to how the token is extracted, have a look here