Firebase admin deleteUser function not working - javascript

I'm trying to delete all the users in my auth and database using firebase functions. Here's my code for that:
const admin = require("firebase-admin");
admin.initializeApp({
credential: admin.credential.applicationDefault(),
databaseURL: "----"
});
export const listenToAdminCommands = functions.firestore.document('collection/{docUid}')
.onWrite((change, context) =>
{
const pass: string = '--';
// const before = change.before.exists? change.before.data() : null;
const after = change.after.exists? change.after.data() : null;
if(after !== null && after !== undefined) {
const adminCommandType: string = after['type'];
const adminCommandPass: string = after['pass'];
if(adminCommandType === 'deleteAll' && adminCommandPass === pass) {
adminDeleteAllUsers();
}
}
});
//Admin control
function adminDeleteAllUsers() {
deleteAllUsers(' ');
return null;
}
function deleteAllUsers(nextPageToken: any) {
admin.auth().listUsers(1000, nextPageToken)
.then((listUsersResult: any) => {
//go through each one and check last time signed in
listUsersResult.users.forEach((userRecord: any) => {
const user: any = userRecord.toJSON();
const userUid = user['uid'];
console.log('Deleting user for data delete uid = ', userUid);
admin.auth().deleteUser(userUid)
.then(() => {
console.log('Successfully deleted user', userUid);
})
.catch((error: any) => {
console.log('Error deleting user:', error);
});
db.collection('users').doc(userUid).delete();
});
if (listUsersResult.pageToken) {
// List next batch of users.
listAllUsers(listUsersResult.pageToken);
}
})
.catch((error: any) => {
console.log('Error listing users:', error);
});
}
When the function get executed, no user is deleted. It's like the function never worked. Am I missing something?
Update:
I'm not sure if this is the way to do it, but it's still not working. I tried to handle promises correctly, but I'm not sure if what I'm doing is correct or not.
export const listenToAdminCommands = functions.firestore.document('collection/{docUid}')
.onWrite((change, context) =>
{
const pass: string = '---';
// const before = change.before.exists? change.before.data() : null;
const after = change.after.exists? change.after.data() : null;
if(after !== null && after !== undefined) {
const adminCommandType: string = after['type'];
const adminCommandPass: string = after['pass'];
if(adminCommandType === 'deleteAll' && adminCommandPass === pass) {
return adminDeleteAllUsers();
}
return;
}
return;
});
//Admin control
function adminDeleteAllUsers() {
return deleteAllUsers(' ');
}
function deleteAllUsers(nextPageToken: any) {
return admin.auth().listUsers(1000, nextPageToken)
.then((listUsersResult: any) => {
//go through each one and check last time signed in
listUsersResult.users.forEach((userRecord: any) => {
const user: any = userRecord.toJSON();
const userUid = user['uid'];
console.log('Deleting user for data delete uid = ', userUid);
return admin.auth().deleteUser(userUid)
.then(() => {
console.log('Successfully deleted user', userUid);
return db.collection('users').doc(userUid).delete();
})
.catch((error: any) => {
console.log('Error deleting user:', error);
return;
});
});
if (listUsersResult.pageToken) {
// List next batch of users.
listAllUsers(listUsersResult.pageToken);
}
return;
})
.catch((error: any) => {
console.log('Error listing users:', error);
return;
});
}

Related

http://localhost:9000/api/users net::ERR_CONNECTION_REFUSED and jwt must be provided

I am creating a blog application. In every parameterized route I get the details of that specific user.For eg: /profile/#randomuser get the details of #randomusers, /profile/#robert get the details of #robert. I get the details of parameterized toute users but not the user who log in to the blog application.
Everything is imported correctly.
<Route path="/profile/:profile" element={\<Profile /\>}
Profile.jsx
const [user, getUser] = useState([])
const [glbUser, setUser] = useContext(UserContext)
const match = useParams().profile
const match = useMatch('/profile/:profile')
const userMatch = match.params.profile
console.log(" usematchis ", userMatch)
const userParams = useParams().profile
useEffect(() => {
async function fetchGlbUser() {
const loggedInUser = window.localStorage.getItem('userToken')
if (loggedInUser) {
const user = JSON.parse(loggedInUser)
loginServices.setToken(user.token)
// loginServices.createToken()
const config = { headers: { Authorization: user.token } }
const glbUser = await axios.get("${postUrl}", config)
setUser(glbUser.data.glbUserToken)
return glbUser.data.glbUserToken
}
}
fetchGlbUser()
}, [])
// console.log("Match is", match)
// console.log("Type of Match is", typeof match.params.profile)
useEffect(() =\> {
axios.get("http://localhost:9000/api/users/${userMatch}", { params: { profile: userMatch } })
.then(res =\> {
console.log(res.data)
getUser(res.data)
// getUser(res.data.newUser)
})
.catch(err => console.log(err))
// const getUserData = async () => {
// const res = loginServices.getProfile(`http://localhost:9000/api/users/${userMatch}`, {params:{profile:userMatch}})
// return res.data
// }
// getUserData()
}, [])
Backend.js
router.get('/:profile', async (req, res) =\> {
console.log(req)
const username = req.params.profile
const decodedToken = jwt.verify(getToken(req), process.env.SECRET_KEY)
// console.log(username)
// console.log(typeof username)
try {
const newUser = await User.findOne({ username })
const glbUserToken = await User.findById(decodedToken.id)
// console.log(newUser)
res.status(200).json({ newUser, glbUserToken })
} catch (err) {
console.log(err)
}
})
const getToken = req =>
const auth = req.get('authorization')
if (auth && auth.startsWith(`bearer `))
return auth.replace('bearer ', '') }
return null
}

Method that causes infinite calls

I would just like to ask for suggestions and ideas about my current issue , I have a method which is getUserRoles which is fetching the logged-in user roles list.
The problem I have is that there are instances that the getUserGeneralDetails from the getUserRoles that is causing infinity , it is calling the getUserGeneralDetails infinitely and I dont understand why and what causes it.
Maybe somone can enlighten me with some problem with the code snippet I have below. Would be appreciatd, Thanks.
#method
//In this method, we are just fetching the logged-in user roles list.
public getUserRoles(): Promise<string[]> {
if (this.authUser === null) {
this.setAuthUser()
}
return new Promise((resolve, reject) => {
this.userService
.getUserGeneralDetails(this.authUser.nameid , this.accountId = 0)
.pipe(catchError((error: any, caught: any) => {
reject(error);
return caught;
}),
map((res: any) => res.data && res.data.userAccountDto
.filter(account => account.accountName === res.data.associatedAccount)
.map(account => account.userRoleDto.roleName)
)).subscribe((role: string[]) => {
resolve(role);
});
});
}
#code that calls the getUserRoles method
this.authService
.loginWithCredentials(username, password)
.then((r: any) => {
localStorage.removeItem("previousUrl");
if (r.isSuccess) {
this.authService.getUserRoles().then((userRoles: string[]) => {
localStorage.setItem("userRoles", JSON.stringify(userRoles));
})
this.route.navigateByUrl('/');
}else{
if(r.errors.length > 0){
if(r.errors[0].description.indexOf('not found') !== -1){
errMsg = ERR_FORM_MSG.INVALID_LOGIN;
}
}
this.apiErrMsg = errMsg;
}
})
.catch((e): any => {
this.apiErrMsg = e.message
? e.message
: errMsg;
})
.finally(() => {
this.hasSubmit = false;
this.closeLoader();
});
}
#user details
getUserGeneralDetails(id: number , accountId:number): Observable<any> {
const params = new HttpParams()
.set('id', id.toString())
.set('accountId', accountId.toString());
return this.httpRequestService.get<any>(`${apiBaseUrl}/detail` , params);
}

node.js send notification to specific user in controller

index.js file
var users = [];
let addUser = (userId, socketId) => {
!users.some((user) => user.userId === userId) &&
users.push({ userId, socketId });
};
let removeUser = (socketId) => {
users = users.filter((item) => item.socketId !== socketId);
};
const getUser = (userId) => {
console.log("inside function", users);
return users.find((item) => item.userId === userId);
};
io.on("connection", (socket) => {
socket.on("addUser", async (userId) => {
await addUser(userId, socket.id);
io.emit("getUsers", users);
console.log(users) // print array of users like this
// [{userId:'userId',socketId: 'socket id'}]
});
socket.on("disconnect", () => {
removeUser(socket.id);
io.emit("getUsers", users);
});
});
const socketIoObject = io;
const usersInObject = users;
module.exports.ioObject = { socketIoObject, usersInObject };
controller file
exports.createNotifications = async (req, res) => {
try {
const { userId, title, type = "default", isPublic } = req.body;
if (!title) {
return res.status(401).send("Data is required");
}
const notification = await notificationsModel.create({
userId,
title,
type,
isPublic: userId ? false : true,
});
console.log("socket", socket.ioObject.usersInObject); // return empty
// array [] !!!!
return res.status(200).send("sent");
} catch (err) {
return res.status(400).send(err.message);
}
};
why I can't get the users list in the controller, I got an empty array !!
I need to share the users list in all files to can get the user by function getUser to get the socketId of a specific user to can send a notification to him
Maybe, you import socket in controller file incorrect

discord bot that checks if the transfer is completed

I'm having an issue with my js code. I built a bot that makes a file to play in my server with the name of who joins, but it's too fast so I want to put something that stops the code until it finishes to make the file
client.on('voiceStateUpdate', async(oldState, newState) => {
if (!oldState || !newState) return;
const oldChannel = oldState.channel ? oldState.channel.id : null;
const newChannel = newState.channel ? newState.channel.id : null;
const user = await client.users.fetch(newState.id)
let nome = user.username;
let messaggio = 'E\' entrato '+nome;
say.export(messaggio , 'Cellos', 1, 'output.wav', (err) => {
if (err) {
return console.error(err)
}
})
online(newChannel, newState, nome);
});
function online(newChannel, newState, nome) {
if(newChannel === universoVoice && newState.id !== Botid){
console.log('entrata');
const voiceChannel = client.channels.cache.get(universoVoice);
if (!voiceChannel) return console.error("The channel does not exist!");
voiceChannel.join().then(connection => {
console.log("Connesso");
connection.play('out.mp3');
client.leaveVoiceChannel;
}).catch(e => {
console.error(e);
});
}else{
console.log('uscita');
}
}
Try using await online(newChannel, newState, nome); in order to wait until the say.export function is completed

Handle null return values in Promise in typescript

I am quite new to typescript and have following issue.
I have following code where I can't reach console.log('uid....' + uid); when the uid is null
deleteUser(email: string): Promise<User> {
let uid: string;
let p = new Promise<User>((resolve) => {
this.loginService.getUserIdByEmail(email).then((getUserResponse) => {
**********************************
******** do not reach here when getUserResponse is NULL**********************
************************
uid = getUserResponse;
console.log('uid....' + uid);
if (uid !== null) {
let actions = [
this.siteUserTableService.deleteByRowKey(uid),
this.userSiteTableService.deleteById(uid),
];
Promise.all(actions.map(this.reflect)).then(values => {
this.tableService.deleteById(uid).then((deleteResponse) => {
this.loginService.deleteUserByEmail(email);
});
});
}
}).catch((err) => {
// Something wrong
});
});
return p;
};
getUserIdByEmail(email: string): Promise<string> {
let searchParams = {
query: 'select UID from accounts where profile.email = "' + email + '"'
};
let p = new Promise<string>((resolve, reject) => {
login.accounts.search(searchParams).then((response) => {
if (response.errorCode === 0 && response.results.length > 0) {
resolve(response.results[0].UID);
} else {
console.log('No login user...');
reject('');
}
});
});
};
As I am not getting a return value from getUserIdByEmail function (return null) I cannot proceed with deleteUser function.
So how can I proceed even with null return value.
Thanks

Categories

Resources