pdf.getDocument does not throw a PasswordException - react-pdf

Using react web app
package.json
"react": "^16.10.2",
"react-pdf": "^5.7.2",
imports:
import {pdfjs} from "react-pdf";
pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist#${pdfjs.version}/build/pdf.worker.min.js`;
When loading encrypted (protected) pdf file, promise does not throw a PasswordException as it should
code
const data = convertDataURIToBinary(base64PdfData); //implementation not important
pdfjs.getDocument({data, password: ''}).promise.then(doc => {
console.warn('ends up here even with wrong password!')
}).catch(e => {
console.error('never executed, why?')
})
imported pdfjs dependency is version 2.12.313 so API should match

Related

How to use runtime config in composable?

I want to do this
composables/apiFetch.ts
import { $fetch } from 'ohmyfetch'
export const useApiFetch = $fetch.create({ baseURL: useRuntimeConfig().apiUrl })
And use it within Pinia so I don't repeat myself writing $fetch.create over and over again for every single API call.
somewhere_in_pinia.ts
...TRIM...
actions: {
async doSomething(payload: SomeNicePayload): Promise<void> {
const response = await useApiFetch('/something', { method: 'POST', body: payload })
}
}
...TRIM...
But Nuxt won't allow me
[nuxt] [request error] nuxt instance unavailable
at useNuxtApp (/D:/XXXX/frontend/prms-fe/.nuxt/dist/server/server.mjs:472:13)
at Module.useRuntimeConfig (/D:/XXXX/frontend/prms-fe/.nuxt/dist/server/server.mjs:480:10)
at $id_Yl353ZXbaH (/D:/XXXX/frontend/prms-fe/.nuxt/dist/server/server.mjs:38358:90)
at async __instantiateModule__ (/D:/XXXX/frontend/prms-fe/.nuxt/dist/server/server.mjs:40864:3)
I have been looking for solution online, followed instruction from the official discussion to no avail.
EDIT
I don't want to use Nitro, since my backend is already written on Laravel. I need to access the host without re-typing it all over the place so I thought I could use .env and runtimeConfig.
you are trying to access Nuxt instance while it's not ready yet. To make it work, write your composable as a function :
import { $fetch } from 'ohmyfetch'
export const useApiFetch = (url, params) => {
const instance = $fetch.create({ baseURL: useRuntimeConfig().apiUrl })
return instance(url, params)
}

How to resolve 'getUserByAccount is not a function' in next-auth?

I've updated Nextjs to it's newest version and also updated next-auth and the prisma adapter as specified by the docs.
However, when I try to authenticate in the app with signIn I get the following error with the latest updates:
[next-auth][error][OAUTH_CALLBACK_HANDLER_ERROR]
https://next-auth.js.org/errors#oauth_callback_handler_error getUserByAccount is not a function {
message: 'getUserByAccount is not a function',
stack: 'TypeError: getUserByAccount is not a function\n' +
' at Object.callback (/home/.../node_modules/next-auth/core/routes/callback.js:81:39)\n' +
' at runMicrotasks (<anonymous>)\n' +
' at processTicksAndRejections (internal/process/task_queues.js:95:5)\n' +
' at async NextAuthHandler (/home/.../node_modules/next-auth/core/index.js:103:28)\n' +
' at async NextAuthNextHandler (/home/.../node_modules/next-auth/next/index.js:40:7)\n' +
' at async [...]/node_modules/next-auth/next/index.js:80:32\n' +
' at async Object.apiResolver (/home/.../node_modules/next/dist/server/api-utils.js:102:9)\n' +
' at async DevServer.handleApiRequest (/home/.../node_modules/next/dist/server/next-server.js:1014:9)\n' +
' at async Object.fn (/home/.../node_modules/next/dist/server/next-server.js:901:37)\n' +
' at async Router.execute (/home/.../node_modules/next/dist/server/router.js:210:32)',
name: 'TypeError'
}
Is there something I'm doing wrong, or is there an incompatibility I'm missing?
Relevant package.json:
...
"#next-auth/prisma-adapter": "^0.5.2-next.19",
"next": "^12.0.3",
"next-auth": "4.0.0-beta.6",
"prisma": "^3.4.1",
...
[...nextauth].ts:
import NextAuth from 'next-auth';
import CognitoProvider from 'next-auth/providers/cognito';
import { PrismaAdapter } from '#next-auth/prisma-adapter';
import { PrismaClient } from '#prisma/client';
const prisma = new PrismaClient();
export default NextAuth({
adapter: PrismaAdapter(prisma),
providers: [
CognitoProvider({
clientId: process.env.COGNITO_CLIENT_ID,
clientSecret: process.env.COGNITO_CLIENT_SECRET,
issuer: process.env.COGNITO_ISSUER,
}),
],
callbacks: {
async session({ session, user }) {
session.userId = user.id;
session.role = user.role;
return Promise.resolve(session);
},
},
});
Finally resolved the problem. Since next-auth has moved to monorepo, updating package was not enough, you need to uninstall it first then install it again.
Run:
npm uninstall next-auth #next-auth/prisma-adapter
then:
npm install #next-auth/prisma-adapter
This fixed it for me.
In the NextAuth.JS 4.0 the "Prisma schema" have slightly changed.
From the upgrade guide:
created_at/createdAt and updated_at/updatedAt fields are removed from all Models.
user_id/userId consistently named userId.
compound_id/compoundId is removed from Account.
access_token/accessToken is removed from Session.
email_verified/emailVerified on User is consistently named email_verified.
provider_id/providerId renamed to provider on Account
provider_type/providerType renamed to type on Account
provider_account_id/providerAccountId on Account is consistently named providerAccountId
access_token_expires/accessTokenExpires on Account renamed to expires_in
New fields on Account: expires_at, token_type, scope, id_token, session_state
verification_requests table has been renamed to verification_tokens
Complete new schema in:
https://next-auth.js.org/adapters/prisma

AngularFire#7.1.1: NullInjectorError: No provider for Firestore

I'm getting the following error message with my Angular 12 app: NullInjectorError: No provider for Firestore!
Firestore is initialized both the old and the new way in my lazy loaded admin.module.ts
import { connectFirestoreEmulator, getFirestore, provideFirestore } from "#angular/fire/firestore";
import { AngularFirestoreModule } from "#angular/fire/compat/firestore";
...
imports: [
AngularFirestoreModule,
provideFirestore(() => {
const firestore = getFirestore();
if (!environment.production) {
connectFirestoreEmulator(firestore, "localhost", 8080);
}
return firestore;
}),
]
Also setting up Firebase both ways in my app.module.ts
import { provideFirebaseApp, initializeApp } from "#angular/fire/app";
import { AngularFireModule } from "#angular/fire/compat";
...
imports: [
AngularFireModule.initializeApp(environment.firebase),
provideFirebaseApp(() => initializeApp(environment.firebase)),
]
And finally, using Firestore in one of my services, (let's call it foo.service.ts) that is being provided by my admin.module.ts
import { Firestore } from "#angular/fire/firestore";
...
export class ScanRepositoryService {
constructor(private firestore: Firestore) {}
}
From what I can tell, I'm following the AngularFire documentation pretty strictly, still, getting this error message about my service can't resolve Firestore. Re-installing the whole node_modules and re-compiling the app with both dev and production flags did not help. Any other idea how to solve this issue?
Solved by removing all the "old" non-modular usage of Firestore, leaving only the version 9+ parts.

Ionic Sqlite not running on chrome

import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { SQLite, SQLiteObject } from '#ionic-native/sqlite';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
username='name';
items = [];
constructor(public navCtrl: NavController, private sqlite: SQLite) {
}
save()
{
alert();
this.sqlite.create({
name: 'data.db',
location: 'default'
})
.then((db: SQLiteObject) => {
//data insert section
db.executeSql('CREATE TABLE IF NOT EXISTS usernameList(id INTEGER PRIMARY KEY AUTOINCREMENT,name)', {})
.then(() => alert('Executed SQL'))
.catch(e => console.log(e));
//data insert section
db.executeSql('INSERT INTO usernameList(name) VALUES(?)', [this.username])
.then(() => alert('Executed SQL'))
.catch(e => console.log(e));
//data retrieve section
db.executeSql('select * from usernameList', {}).then((data) => {
alert(JSON.stringify(data));
//alert(data.rows.length);
//alert(data.rows.item(5).name);
this.items = [];
if(data.rows.length > 0) {
for(var i = 0; i < data.rows.length; i++) {
//alert(data.rows.item(i).name);�
this.items.push({name: data.rows.item(i).name});
}
}
}, (err) => {
alert('Unable to execute sql: '+JSON.stringify(err));
});
})
.catch(e => alert(JSON.stringify(e)));
}
}
Why I am not able to test my code on broswe
I even try using ionic cordova run browser
This is my console error
OPEN database:
data.db cordova.js:1003 Error: exec proxy not found for
:: SQLitePlugin :: close cordova.js:1003 Error: exec proxy not found
for :: SQLitePlugin :: open
plugins/cordova-sqlite-storage/www/SQLitePlugin.js:196 OPEN database:
data.db FAILED, aborting any pending transactions
plugins/cordova-sqlite-storage/www/SQLitePlugin.js:174 OPEN database:
data.db cordova.js:1003 Error: exec proxy not found for ::
SQLitePlugin :: close cordova.js:1003 Error: exec proxy not found for
:: SQLitePlugin :: open
plugins/cordova-sqlite-storage/www/SQLitePlugin.js:196 OPEN database:
data.db FAILED, aborting any pending transactions
Mysql doesnot support on ionic for testing on browser. Cordova doesnot support it. You need to test in native app
SQLite is not meant to be used on non-"native" builds of your Ionic app:
https://ionicframework.com/docs/native/sqlite/ - see the platforms listed there and there is no "browser" as supported platform.
To test it you should run your app on a device via something like:
ionic cordova run android
Depending on your use case & your requirements for local persistence sometimes it make sense to use Ionic Storage: https://ionicframework.com/docs/storage/ which can use sqlite and can "fallback" / use another type of persistence that is supported by a browser (websql, indexeddb). In this case you can develop and test your app in browser using "ionic serve" and then later on validate that it also works fine on a real device.

usage example for chokidar in Meteor to prevent Error: Meteor code must always run within a Fiber

The code below gives me the Error: 'Meteor code must always run within a Fiber. Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment.'
import chokidar from 'chokidar';
import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';
const Plates = new Mongo.Collection('plates');
var path = '~/Documents/dev/lpr/test';
var watcher = chokidar.watch(path, {
ignored: /(^|[\/\\])\../,
persistent: true
});
watcher.on('add', path => {
console.log(`DEBUG: File ${path} has been added`);
Plates.insert({
path,
})
});
The Meteor documentation (https://guide.meteor.com/using-npm-packages.html#wrap-async) suggests using Meteor.wrapAsync to solve this issue but I don't understand how to apply in this case?
e.g. below returns 'TypeError: watcherFiber.on is not a function'
var watcherFiber = Meteor.wrapAsync(chokidar.watch(path, {
ignored: /(^|[\/\\])\../,
persistent: true
}));
watcherFiber
.on('add', path => {
console.log(`DEBUG: File ${path} has been added`);
Plates.insert({
path,
})
});
The error text points you to the correct way to do that.
It should be like this:
watcher.on('add', Meteor.bindEnvironment(path => {
console.log(`DEBUG: File ${path} has been added`);
Plates.insert({
path,
});
}));

Resources