Getting 403 Forbidden laravel broadcasting/auth - javascript

Hey guys i been debugging for long but still can't fix the problem.
I get 403 Forbidden laravel broadcasting/auth using pusherjs for private channel. on pusher dashboard logs i can see the event but on browser not firing the event.
frontend code reactjs
const enablePusher = () => {
var pusher = new Pusher('XXXXXXXXXXXXXX', {
cluster: 'mt1',
authEndpoint: Setting.BASE_URL + '/broadcasting/auth',
auth: {
headers: {
Authorization: 'Bearer ' + localStorage.getItem('token'),
},
},
})
var channel = pusher.subscribe(`private-mc-chat-conversation.${conversation.id}`)
channel.bind('.Musonza\\Chat\\Eventing\\MessageWasSent', data => {
console.log(JSON.stringify(data))
})
}
BroadcastServiceProvider.php
Broadcast::routes(['middleware' => ['auth:api']]);
Channels.php
Broadcast::channel('presence-mc-chat-conversation.{conversationId}', function ($user) {
return ['id' => $user->id, 'name' => $user->name];
});

Related

How to improve sequential promises execution and force fulfillment

This code is being used in a Sveltekit web application.
In the first step I get a user jwt token from an api like : dashboard.example.com/auth/local
and in the second step I'm using the response of the first api call to get full information from an api endpoint like this : example.com/api/users/token
This is an endpoint in an Sveltekit application:
import { json as json$1, error } from '#sveltejs/kit';
import axios from 'axios';
import md5 from 'md5';
import { SITE_ADDRESS } from '$lib/Env';
let userToken;
/** #type {import('#sveltejs/kit').RequestHandler} */
export async function POST({ request }) {
const bodyData = await request.json();
let identifier = bodyData.data.identifier;
let password = bodyData.data.password;
let loginToken = bodyData.data.loginToken;
let newLoginToken = md5(identifier + password + process.env.SECURE_HASH_TOKEN);
let dataResult = await axios
.post(`${import.meta.env.VITE_SITE_API}/auth/local`, {
identifier: identifier,
password: password
})
.then((response) => {
return response.data;
})
.then((response) => {
let userSummaryData = response;
userToken = md5(
userSummaryData.user.username + userSummaryData.user.id + process.env.SECURE_HASH_TOKEN
);
let userCompleteData = axios
.post(`${SITE_ADDRESS}/api/users/${userToken}`, {
data: {
userID: userSummaryData.user.id,
username: userSummaryData.user.username
}
})
.then((response) => {
return {
userJWT: userSummaryData.jwt,
userSummary: userSummaryData.user,
userFullSummary: response.data.userFullSummary
};
});
return userCompleteData;
})
.catch((error) => {
// console.log(' ---- Err ----');
});
if (dataResult && newLoginToken == loginToken) {
return json$1(
{
userJWT: dataResult.userJWT,
userSummary: dataResult.userSummary,
userFullSummary: dataResult.userFullSummary
},
{
headers: {
'cache-control': 'private, max-age=0, no-store'
}
}
);
} else if (dataResult && newLoginToken != loginToken) {
throw error(400, 'Something wrong happened');
}
throw error(401, 'Something wrong happened');
}
This code is work perfectly in localhost. But when I test it on host I get error 401.
and the question is :
Why this works on localhost but doesn't work on the server?
How can I improve this kind of promises (I'd like to use the response of the first api call in the second api call and return both
as a result)

Axios giving unauthenticated error on post request while the get request works with the same user token tried logging out but it didn't work

Axios giving unauthenticated error on post request while the get request works with the same user token tried logging out and in again but it's not working I think I am writing something wrong if anybody could help it would be very appriciable.
error:
POST http://localhost:8080/api/v1/projects 401 (Unauthorized)
Error: Request failed with status code 401
at e.exports (isAxiosError.js:10:1)
at e.exports (isAxiosError.js:10:1)
at l.onreadystatechange (isAxiosError.js:10:1)
const userToken =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2MzVmOGQzMzUzMTY3MzIyODBkNTJlNDQiLCJuYW1lIjoiUmFtIiwiaWF0IjoxNjY3ODQ3Nzg4LCJleHAiOjE2NzA0Mzk3ODh9.dHAdhvFphiN08hZKHyCEW5a5s3GHtaUtyOFlAnNkgSA"
const showProject = async () => {
loadingDOM.getElementsByClassName.visiblity = "visible"
try {
const {
data: { projects },
} = await axios.get("api/v1/projects", {
headers: {
Authorization: "Bearer " + userToken,
},
})
if (projects.length < 1) {
projectDOM.innerHTML =
'<h5 class="empty-list">No projects in your list</h5>'
loadingDOM.style.visibility = "hidden"
return
}
const allProjects = projects
.map((project) => {
const {
_id: projectId,
projectName,
discription,
} = project
return `<div class="single-project">
<h5><span><i class="far fa-check-circle"></i></span>${projectName}</h5>
<h5><span><i class="far fa-check-circle"></i></span>${discription}</h5>`
}).join("")
projectDOM.innerHTML = allProjects
} catch (error) {
console.log(error)
projectDOM.innerHTML =
'<h5 class="empty-list">There was an error, please try later....</h5>'
}
}
showProject()
// create project
formDOM.addEventListener("submit", async (e) => {
e.preventDefault()
const projectName = projectNameDOM.value
const projectDiscription = projectDiscriptionDOM.value
const projectAuthor = projectAuthorDOM.value
const projectCollaborator = projectCollaboratorDOM.value
const projectTechnologyUsed = projectTechnologyUsedDOM.value
try {
await axios.post('/api/v1/projects', {projectName, projectDiscription},{
headers: {
Authorization: "Bearer " + userToken,
},
})
showProject()
projectNameDOM.value = ''
projectDiscription.value = ''
formAlertDOM.style.display = 'block'
formAlertDOM.textContent = `success, project added`
formAlertDOM.classList.add('text-success')
} catch (error) {
console.log(error)
formAlertDOM.style.display = "block"
formAlertDOM.innerHTML = `error, please try again`
}
setTimeout(() => {
formAlertDOM.style.display = 'none'
formAlertDOM.classList.remove('text-success')
}, 3000)
})
I was expecting a 201 status code and a new project added in my database but didn't happened.

Vue.JS POST request pass null bearer token and failed with status code 401

I'm backend guy who wants to gain some Vue.js skills. In my app I've got Ruby on Rails as backend and Vue.js as front-end with a standard JWT token flow. I'm trying to send a POST request (fetchAllProductsRequest) to the backend that will trigger some background job using below code:
index.js
const fetchAllProductsRequest = (self) => {
const jwtToken = self.$store.state.idToken;
return axios
.post(`/api/v1/imports/products/fetch_all`,{
headers: {
Authorization: `Bearer ${jwtToken}`,
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(response => response.data)
};
Quite surprisingly I get an error: Request failed with status code 401. When I debugging it on the backend side I see that I send an empty token inside the header:
[1] pry(#<Api::V1::Imports::ProductsController>)> params[:headers]
=> #<ActionController::Parameters {"Authorization"=>"Bearer null", "Content-Type"=>"application/json", "Accept"=>"application/json"} permitted: false>
Here is a function that triggers fetchAllProductsRequest which is responsible for POST request:
fetch_all.vue
<script>
import {
fetchAllProductsRequest,
} from '../../api/imports'
import ModalController from '../general/modal_controller'
export default {
name: 'BackboneFetchAll',
data() {
return { }
},
components: {
MoonLoader
},
computed: {
databaseSyncInProgress() {
return this.$store.getters.getDatabaseSyncStatus;
},
},
methods: {
async syncAll() {
let confirmationText = `Do you want to sync all Backbone products?`
if (await ModalController.showConfirmation('Confirmation', confirmationText)) {
try {
ModalController.showLoader()
await fetchAllProductsRequest(this)
this.$store.commit('setSyncingProductsInProgress', value)
const successMessage = `Database synchronization has been queued`
await ModalController.showToast('', successMessage)
} catch (data) {
const errorMessage = `Error occurred during queueing products to sync - `
ModalController.showToast('', errorMessage + data?.message, 'error')
} finally {
ModalController.hideLoader()
}
}
},
}
}
</script>
What did I missed?

Cannot set headers after they are sent to the client axios next.js

Same question on GitHub - https://github.com/axios/axios/issues/2743
I have Axios in my Next.js project and sometimes I get an error due to interceptor when return the Promise.reject.
Error: Cannot set headers after they are sent to the client.
I encounter this problem when I make a request in getInitialProps. This happens very rarely when I restart the PC and open the page again.
Axios instance:
const instance = axios.create({
baseURL: 'https://my-api.com',
withCredentials: true,
headers: {
'X-Requested-With': 'XMLHttpRequest',
},
})
instance.interceptors.response.use(undefined, error => {
if (error.response.status === 401) {
console.log("UNAUTHORIZED")
}
return Promise.reject(error) // <-- this cause the problem
})
Next.js Page example:
const Index = ({myData}) => {
return data.map(...)
}
Index.getInitialProps = async ({req}) => {
let myData
try {
const res = await API.get('/my-request', {
headers: req ? { cookie: req.headers.cookie } : undefined, //setting cookie
})
myData = res.data
} catch (e) {}
return {myData}
}
This problem disappeared when I upgraded Axios 0.19.0 to 0.19.2 ¯_(ツ)_/¯

Unable to get fetch response on react native app

I am stuck on one of the mysterious issue. The problem goes like this:
What I Do??
Simply do login api call and if login success then I have to fetch amount of data from 5-6 api calls and store them in local database (Realm). Here is my code.
login(email, password) {
this.toggleLoadingFunction(true);
fetch(LoginURL, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: email,
password: password,
request_from: 'mobile'
}),
})
.then(async res => {
if (res.ok) {
let data = await res.json();
global.user = data['user']
global.token = data['token']
getAllMasterDataAndSaveInRealm().then(() => {
this.toggleLoadingFunction(false);
global.storage.save({ key: 'LoggedInData', data: data });
this.props.navigation.navigate('Project', data);
}).catch(() => {
this.toggleLoadingFunction(false);
Alert.alert("Master Data Failed !!!");
})
} else {
this.toggleLoadingFunction(false);
let data = await res.json();
Alert.alert("Login Failed!!!", data.message)
}
})
.catch(error => {
this.toggleLoadingFunction(false);
Alert.alert("Network Error. Please try again.")
})
Here getAllMasterDataAndSaveInRealm() is lies on helper function which calls 5-6 apis and response back if all work is done. Here is how it looks like:
export const getAllMasterDataAndSaveInRealm = () => {
const token = global.token;
return new Promise.all([
getMaterials(token),
getEquipments(token),
getObjective(token),
getCategories(token),
getNcData(token),
getPlans(token)]
);
}
Each function inside getAllMasterDataAndSaveInRealm() returns Promise after successfully stored data in local realm db. Here is one of the above function.
export const getActivityPlan = (token) => {
return new Promise((resolve, reject) => {
return fetch(FetchActivityPlanDataURL, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'access_token': `${token}`
}
}).then((response) => {
console.log("Activity Plans Api response", response);
return response.json()
})
.then((responseJson) => {
const { data } = responseJson
console.warn("Activity Plans Api", data);
global.realm.write(() => {
for (var item of data) {
item.id = item.id ? item.id : 0;
item.activity_id = item.activity_id ? item.activity_id.toString() : "";
item.activity_name = item.activity_name ? item.activity_name.toString() : "";
item.activity_cost = item.activity_cost ? item.activity_cost.toString() : "";
item.project_id = item.project_id ? item.project_id : 0;
global.realm.create("ActivityPlan", item, true);
}
})
resolve(data);
})
.catch((error) => {
reject(`Activity Plan Failed ${error}`)
});
})
}
All remaining functions are same as above ( what they do is simply fetch data from api and store it in realm and resolve or reject)
What I Expect:
getAllMasterDataAndSaveInRealm() function Just store all the required data in db and let me know all done and then navigate to the another screen, as Login and fetching data is done.
Problem:
When I do run the app and process for login, Sometimes it works fine but most of the time App stuck on showing loader since some of the api call among 6 api from above do not get response from the request ( I do log the response) on wifi. But when I use mobile data and VPN it always works.
When I log request on server console, response is sent with code 200, but app is unable to get response for the request.
I am new on react native. I do lots of searches over internet but unable to find the solution. I don't have any idea whats going wrong with the code. Please help me out.
Project Configurations:
"react": "16.8.6",
"react-native": "0.60.4",
"realm": "^2.29.2",
Node version: v9.0.0

Categories

Resources