This is my issue, I can access to MongoDB as an admin, but when I switch to “user” I can't, and it shows a message like this: msg: "You are not an admin!", even though I switched to 'user', this is and screenshot on MongoDB:
MongoDB, please click to see the image
This is a screenshot of the app message error:
Flutter app, please click to see the image
This is my code:
admin.js
const jwt = require("jsonwebtoken"); const User = require("../models/user");
const admin = async (req, res, next) => { try {
const token = req.header("x-auth-token");
if (!token)
return res.status(401).json({ msg: "No auth token, access denied" });
const verified = jwt.verify(token, "passwordKey");
if (!verified)
return res
.status(401)
.json({ msg: "Token verification failed, authorization denied." });
const user = await User.findById(verified.id);
if (user.type == "user" || user.type == "seller") {
return res.status(401).json({ msg: "You are not an admin!" });
}
req.user = verified.id;
req.token = token;
next(); } catch (err) {
res.status(500).json({ error: err.message }); } };
module.exports = admin;
admin_services.dart
class AdminServices {
void sellProduct({
required BuildContext context,
required String name,
required String description,
required double price,
required double quantity,
required String category,
required List<File> images,
}) async {
final userProvider = Provider.of<UserProvider>(context, listen: false);
try {
final cloudinary = CloudinaryPublic('blur', 'blur');
List<String> imageUrls = [];
for (int i = 0; i < images.length; i++) {
CloudinaryResponse res = await cloudinary
.uploadFile(CloudinaryFile.fromFile(images[i].path, folder: name));
imageUrls.add(res.secureUrl);
}
Product product = Product(
name: name,
description: description,
quantity: quantity,
images: imageUrls,
category: category,
price: price,
);
http.Response res = await http.post(
Uri.parse('$uri/admin/add-product'),
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'x-auth-token': userProvider.user.token,
},
body: product.toJson(),
);
httpErrorHandle(
response: res,
context: context,
onSuccess: () {
showSnackBar(context, 'Product added successfully');
Navigator.pop(context);
},
);
} catch (e) {
showSnackBar(context, e.toString());
}
}
Future<List<Product>> fetchAllProducts(BuildContext context) async {
final userProvider = Provider.of<UserProvider>(context, listen: false);
List<Product> productList = [];
try {
http.Response res = await http.get(
Uri.parse('$uri/admnin/get-products'),
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'x-auth-token': userProvider.user.token,
},
);
httpErrorHandle(
response: res,
context: context,
onSuccess: () {
for (int i = 0; i < jsonDecode(res.body).length; i++) {
productList.add(
Product.fromJson(
jsonEncode(
jsonDecode(res.body)[i],
),
),
);
}
});
} catch (e) {
showSnackBar(context, e.toString());
}
return productList;
}
void deleteProduct(
{required BuildContext context,
required Product product,
required VoidCallback onSuccess}) async {
final userProvider = Provider.of<UserProvider>(context, listen: false);
try {
http.Response res = await http.post(
Uri.parse('$uri/admnin/delete-product'),
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'x-auth-token': userProvider.user.token,
},
body: jsonEncode(
{
'id': product.id,
},
),
);
httpErrorHandle(
response: res,
context: context,
onSuccess: () {
onSuccess();
},
);
} catch (e) {
showSnackBar(context, e.toString());
}
}
}
Hope you can help me, thanks for your attention
Related
I'm trying to upload a file to an s3 bucket as per this guide. https://forge.autodesk.com/en/docs/model-derivative/v2/tutorials/translate-to-obj/about-this-tutorial/ and I'm stuck on step 4 - finalize upload. I'm getting failed with a status code of 400 when calling await finalizeUpload() in the handler.put method.
Here is the api route I am using
const upload = multer({
storage: multer.diskStorage({
destination: './public/uploads',
filename: (req, file, cb) => cb(null, file.originalname),
}),
})
handler.use(upload.single('model'))
handler.put(async (req, res) => {
const { _id: projectId } = req.query
const token = await getInternalToken()
const { access_token } = token
const file = req.file
const objectKey = file.originalname
try {
const projectsCollection = await getProject(projectId)
const bucketKey = projectsCollection.project.bucket.bucketKey
const signeds3upload = await obtainSignedUrl(bucketKey, objectKey, access_token)
const { uploadKey, urls } = signeds3upload
await uploadFile(urls, file.path)
await finalizeUpload(bucketKey, objectKey, uploadKey, access_token)
res.status(201).json({ bucketKey, objectKey, uploadKey })
} catch (error) {
console.log(error)
}
})
Here are the functions for steps 2 - 4
const obtainSignedUrl = async (bucketKey, objectKey, token) => {
const payload = {
ossbucketKey: bucketKey,
ossSourceFileObjectKey: objectKey,
access: 'full',
policyKey: 'transient',
}
const config = {
method: 'get',
url: `https://developer.api.autodesk.com/oss/v2/buckets/${bucketKey}/objects/${objectKey}/signeds3upload?minutesExpiration=30`,
headers: {
ContentType: 'application/json',
Authorization: `Bearer ${token}`,
},
}
try {
let res = await axios(config, payload)
return res.data
} catch (error) {
if (error.response) {
console.log('response Error obtainSignedUrl')
} else if (error.request) {
console.log('Request Error')
} else if (error.message) {
console.log('Message Error')
}
}
}
async function uploadFile(signed_upload_url, path_to_file) {
console.log(path_to_file)
const config = {
method: 'put',
url: signed_upload_url,
headers: {
ContentType: 'application/octet-stream',
},
}
try {
let res = await axios(config, path_to_file)
return res.data
} catch (error) {
if (error.response) {
console.log('response Error Upload File', error.message)
} else if (error.request) {
console.log('Request Error')
} else if (error.message) {
console.log('Message Error')
}
}
}
const finalizeUpload = async (bucketKey, objectKey, uploadKey, token) => {
const config = {
method: 'post',
url: `https://developer.api.autodesk.com/oss/v2/buckets/${bucketKey}/objects/${objectKey}/signeds3upload`,
headers: {
ContentType: 'application/json',
Authorization: `Bearer ${token}`,
},
}
try {
let res = await axios(config, uploadKey)
return res.data
} catch (error) {
if (error.response) {
console.log('response Error Finalize upload', error.message)
} else if (error.request) {
console.log('Request Error')
} else if (error.message) {
console.log('Message Error')
}
}
}
Here same error. Solved with
let res = await axios(config, JSON.stringify({uploadKey}))
I tried it in html and javascript it's working perfect in web (mobile's browser).I am using angular for frontend and node for backend but not getting any solution for redirect Playstore or Gpay for mobile browser. Basically I want to implement for mobile browser.
this is my node for backend code & for frontend I already paste static--
const canMakePaymentCache = 'canMakePaymentCache';
onBuyClicked();
function readSupportedInstruments() {
let formValue = {};
formValue['pa'] = keys.GPAY_MERCHANT_ID;//merchantId
formValue['pn'] = `Test_Gpay_Name`;//transactionId
formValue['tn'] = 'Testing Messages ';//message
formValue['mc'] = 'merchant Code';//
formValue['tr'] = 'Transaction Reference';
formValue['tid'] = 'Transaction id';
formValue['url'] = 'http://localhost.co/';
return formValue;
}
function readAmount() {
//const pay_amount = parseInt(req.body.amount) * 100;
return parseInt(req.body.amount) * 100;
}
function onBuyClicked() {
// if (!window.PaymentRequest) {
// console.log('Web payments are not supported in this browser.');
// return;
// }
let formValue = readSupportedInstruments();
const supportedInstruments = [
{
supportedMethods: ['https://pwp-server.appspot.com/pay-dev'],
data: formValue,
},
{
supportedMethods: ['https://tez.google.com/pay'],
data: formValue,
},
];
const details = {
total: {
label: 'Total',
amount: {
currency: 'INR',
value: readAmount(),
},
},
displayItems: [
{
label: 'Original amount',
amount: {
currency: 'INR',
value: readAmount(),
},
},
],
};
const options = {
requestShipping: false,
requestPayerName: false,
requestPayerPhone: false,
requestPayerEmail: false,
shippingType: 'shipping',
};
let request = null;
try {
//const PaymentRequest = {};
//request = PaymentRequest(supportedInstruments, details, options);
request ={supportedInstruments, details, options};
} catch (e) {
return;
}
if (!request) {
console.log('Web payments are not supported in this browser.');
return;
}
var canMakePaymentPromise = checkCanMakePayment(request);
canMakePaymentPromise
.then((result) => {
showPaymentUI(request, result);
})
.catch((err) => {
console.log('Error calling checkCanMakePayment: ' + err);
});
}
function checkCanMakePayment(request) {
//if (sessionStorage.hasOwnProperty(canMakePaymentCache)) {
//return Promise.resolve(JSON.parse(sessionStorage[canMakePaymentCache]));
//}
var canMakePaymentPromise = Promise.resolve(true);
if (request.canMakePayment) {
canMakePaymentPromise = request.canMakePayment();
}
return canMakePaymentPromise
.then((result) => {
canMakePaymentCache = result;
return result;
})
.catch((err) => {
console.log('Error calling canMakePayment: ' + err);
});
}
function showPaymentUI(request, canMakePayment) {
if (!canMakePayment) {
redirectToPlayStore();
return;
}
let paymentTimeout = window.setTimeout(function () {
window.clearTimeout(paymentTimeout);
request.abort()
.then(function () {
console.log('Payment timed out after 20 minutes.');
})
.catch(function () {
console.log('Unable to abort, user is in the process of paying.');
});
}, 20 * 60 * 1000); /* 20 minutes */
request.show()
.then(function (instrument) {
window.clearTimeout(paymentTimeout);
processResponse(instrument); // Handle response from browser.
})
.catch(function (err) {
console.log(err);
});
}
function processResponse(instrument) {
var instrumentString = instrumentToJsonString(instrument);
console.log(instrumentString);
fetch('/buy', {
method: 'POST',
headers: new Headers({ 'Content-Type': 'application/json' }),
body: instrumentString,
credentials: 'include',
})
.then(function (buyResult) {
if (buyResult.ok) {
return buyResult.json();
}
console.log('Error sending instrument to server.');
})
.then(function (buyResultJson) {
completePayment(
instrument, buyResultJson.status, buyResultJson.message);
})
.catch(function (err) {
console.log('Unable to process payment. ' + err);
});
}
function completePayment(instrument, result, msg) {
instrument.complete(result)
.then(function () {
console.log('Payment completes.');
console.log(msg);
document.getElementById('inputSection').style.display = 'none'
document.getElementById('outputSection').style.display = 'block'
document.getElementById('response').innerHTML =
JSON.stringify(instrument, undefined, 2);
})
.catch(function (err) {
console.log(err);
});
}
console.log(`in line 448....`);
function redirectToPlayStore() {
//if (confirm('Tez not installed, go to play store and install?')) {
//window.location.href = 'https://play.google.com/store/apps/details?id=com.google.android.apps.nbu.paisa.user.alpha'
//res.writeHead( "https://play.google.com/store/apps/details?id=com.google.android.apps.nbu.paisa.user.alpha" );
const response_data = axios
.post(
'https://play.google.com/store/apps/details?id=com.google.android.apps.nbu.paisa.user.alpha',
)
console.log(`in line no. 459... ${response_data}`);
return response_data;
//};
}
function instrumentToJsonString(instrument) {
var instrumentDictionary = {
methodName: instrument.methodName,
details: instrument.details,
shippingAddress: addressToJsonString(instrument.shippingAddress),
shippingOption: instrument.shippingOption,
payerName: instrument.payerName,
payerPhone: instrument.payerPhone,
payerEmail: instrument.payerEmail,
};
return JSON.stringify(instrumentDictionary, undefined, 2);
}
I'm working on the user registration functionality of an application using Typescript and Redux Toolkit. When I make the fetch request to the signup endpoint, a new user is saved to the database I've connected, but I keep entering the catch error block.
export const registerUser = createAsyncThunk(
"user/registerUser",
async (form: { username:string, password:string }, thunkAPI) => {
try {
const response = await fetch('/api/auth/signup', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userInfo: {
username: form.username,
password: form.password
}
}),
});
if (response.status === 200) return 200;
else return 400;
} catch (e) {
console.log('Error')
}
}
);
I've tried logging the response to the console a number of ways
const data = await response.json() console.log(data)
But have had no luck. I think this is an error with how I've done my fetch request using createAsyncThunk but haven't been able to figure out what I've missed.
This is the code for the initial state and slice:
interface UserState {
userProfile: {
id: number | null;
},
registration: {
status: 'loaded' | 'loading'
}
}
const initialState : UserState = {
userProfile: {
id: null,
},
registration: {
status: 'loaded'
}
};
export const userSlice = createSlice({
name: 'user',
initialState,
reducers: {
},
extraReducers: (builder) => {
builder.addCase(registerUser.fulfilled, (state) => { state.registration.status = 'loaded' }),
builder.addCase(registerUser.rejected, (state) => { state.registration.status = 'loaded' }),
builder.addCase(registerUser.pending, (state) => { state.registration.status = 'loading' })
}
})
And here is the code for the function where the action is dispatched on the UI
const handleRegister= async () => {
if (!username) return alert('Username field was left empty');
if (!password) return alert('Password field was left empty');
const {payload} : any = await dispatch(registerUser({ username: username, password: password}));
if (payload === 200) {
alert('Successfully registered. Redirecting to dashboard');
return navigate('/dashboard');
} else { return alert('User creation unsuccessful'); }
}
Appreciate any help as I've looked through many other posts but haven't been able to resolve my issue.
the code below is the first request for get list data
mounted() {
this.getList()
},
methods: {
handleClick(row) {
console.log(row.id)
console.log(row.url)
this.$router.push({ name: 'Main', query: { id: row.id } })
},
getList() {
axios
.get('/api/v1/requests/all', {
params: {
userId: this.$store.state.userInfo.id,
},
})
.then(response => {
let moment = require('moment')
for (var item of response.data.data) {
item.createdAt = moment(item.createdAt).format(
'YYYY-MM-DD HH:mm:ss',
)
}
this.items = response.data.data
})
.catch(error => {
console.log(error)
})
}
my interceptor
axios.interceptors.response.use(
function (response) {
return response
},
async function (error) {
const originalRequest = error.config
if (error.response.status === 401 && !originalRequest._retry) {
error.response.config._retry = true
sessionStorage.removeItem('access-token')
let headers = {
grant_type: 'refresh_token',
Authorization: sessionStorage.getItem('refresh-token'),
}
axios
.post('/api/v1/users/refresh_token', {}, { headers: headers })
.then(response => {
let token = response.data.data
sessionStorage.setItem('access-token', token)
originalRequest.headers['Authorization'] = token
originalRequest.headers['grant_type'] = 'grant_type'
return axios.request(originalRequest)
})
.catch(error => {
console.log(error)
alert('blablabla.')
})
}
return Promise.reject(error)
},
)
the flow is i understand
1.token expired
2.move to list page
3.mounted hook is request data
4.getList -> axios get('~~request/all')
5.interceptor->axios post('~~~refresh_token')
6.re request with new token(request/all)
7.re request is 200, but not update list page
i'd really appreciate your help :)
Seems like you need to return the second request (await for result and return). Right now the result of second request seems to be ignored
axios.interceptors.response.use(
function (response) {
return response;
},
async function (error) {
const originalRequest = error.config;
if (error.response.status === 401 && !originalRequest._retry) {
error.response.config._retry = true;
sessionStorage.removeItem("access-token");
let headers = {
grant_type: "refresh_token",
Authorization: sessionStorage.getItem("refresh-token"),
};
const [secondError, res] = await axios // await here
.post("/api/v1/users/refresh_token", {}, { headers: headers })
.then(async (response) => {
let token = response.data.data;
sessionStorage.setItem("access-token", token);
originalRequest.headers["Authorization"] = token;
originalRequest.headers["grant_type"] = "grant_type";
return [null, await axios.request(originalRequest)];
})
.catch((err) => {
console.log(err);
alert("blablabla.");
return [err, null];
});
// Handle here
if(secondError) {
return Promise.reject(secondError);
}
return Promise.resolve(res)
}
return Promise.reject(error);
}
);
The above solution worked for me perfectly. here's the modified code that I used for my requirement.
export default function axiosInterceptor() {
//Add a response interceptor
axios.interceptors.response.use(
(res) => {
// Add configurations here
return res;
},
async function (error) {
const originalRequest = error.config;
let secondError, res
if (error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
[secondError, res] = await axios({
method: "POST",
url: `${baseURL}/account/token/refreshtoken`,
withCredentials: true,
headers: { "Content-Type": "application/json" },
})
.then(async (response) => {
//handle success
return [null, await axios.request(originalRequest)];
}).catch(function (error) {
console.error(error)
});
}
if (secondError) {
return Promise.reject(secondError);
}
return Promise.resolve(res)
}
);
}
I'm New to unit test and trying to test my controller method.my project architecture design is as follow
Controller->Service->Model.
My test scenarios :
Pass correct parameters to controller method and test success response
Pass Invalid parameters to controller method and test error response
When i going to test scenario 1 ,according to my understanding i want to mock my programService and it return values.I have write test as follow and got errors.
I would really appreciate some one can fix this
ProgramsController.js
const ProgramService = require('../../services/program/programService');
class ProgramsController {
constructor() {
this.programService = new ProgramService();
}
async subscribe(req, res) {
try {
const { userId, uuid, msisdn, body: { programId } } = req;
const data = { userId, programId, msisdn, uuid }
const subscribe = await this.programService.subscribeUser(data);
res.json({
status: true,
message: 'Success',
friendly_message: constant.MSG.SUBSCRIPTION,
data: subscribe
})
} catch (error) {
res.status(500)
.json({
status: false,
message: 'Fail',
friendly_message: constant.MSG.SUBSCRIPTION_FAIL
})
}
}
}
ProgramService.js
class ProgramService {
constructor() {
this.subscriber = new Subscriber();
this.subsciberProgram = new SubsciberProgram()
}
async subscribeUser(data) {
try {
const { msisdn, userId, programId, uuid } = data;
...
return subscribedData;
} catch (error) {
throw error;
}
}
}
module.exports = ProgramService;
test.spec.js
const ProgramsService = require('../src/services/program/programService')
const ProgramsController = require('../src/controllers/programs/programsController')
const programController = new ProgramsController()
const programsService = new ProgramsService()
beforeAll(() => {
db.sequelize.sync({ force: true }).then(() => { });
});
const mockRequest = (userId, uuid, msisdn, body) => ({
userId,
uuid,
msisdn,
body,
});
const mockResponse = () => {
const res = {};
res.status = jest.fn().mockReturnValue(res);
res.json = jest.fn().mockReturnValue(res);
return res;
};
const serviceRecord = { userId: 1, programId: 1, msisdn: '56768382967', uuid: '46651a19-3ef1-4149-818e-9bd8a5f359ef' };
const fakeServiceReturn = { program_id: 1, amount: 5, no_of_questions: 10 }
describe('Subscribe', () => {
test('should return 200', async () => {
const req = mockRequest(
1,
'56768382967',
'46651a19-3ef1-4149-818e-9bd8a5f359ef',
{ 'programId': 1 }
);
const res = mockResponse();
const spy = jest.spyOn(programsService, 'subscribeUser').mockImplementation(() => serviceRecord);
await programController.subscribe(req, res);
expect(programsService.subscribeUser()).toHaveBeenCalledWith(fakeServiceReturn);
expect(res.status).toHaveBeenCalledWith(500);
expect(res.json).toHaveBeenCalledWith({
status: true,
message: 'Success',
friendly_message: 'successfull get data',
data : { program_id: 1, amount: 5, no_of_questions: 10 }
});
spy.mockRestore();
});
});
how can i mock programService.subscribeUser and test success response?
This mock should return a promise:
jest.spyOn(programsService, 'subscribeUser').mockImplementation(() => Promise.resolve(serviceRecord));