27. Change group admin

Suppose, you do not want to manage the group but stay in the group as a member. Or simply want to leave the group and hand it over to someone else. You can do it by simply selecting any of the current members as a group admin. So in this article, we are going to add a feature that allows the admin to change the group admin.

To do that, first, create a form in the group-members-modal modal just like we created for deleting a member.

<!-- form to change group admin -->
<form v-on:submit.prevent="makeAdmin" style="margin-left: 10px;">
	<input type="hidden" name="_id" v-bind:value="member.user._id" required />
	<input type="hidden" name="groupId" v-bind:value="group._id" required />
	<input type="submit" value="Make Admin" v-bind:isMakingAdmin="disabled" class="btn btn-success" />
</form>

Since there are 2 buttons now in 1 table data <td> tag. So in order to show them side-by-side, you can give the following CSS property to the <td> tag:

style="display: flex;"

When the AJAX is called, it will take some time for the server to process that request. In the meantime, we will disable all the “Make admin” buttons so the admin cannot mistakenly click on any other.

isMakingAdmin: false,

It is also to show the admin that the request to change the admin is under process.

Then we need to create a method that will be called when the form is submitted. So, create the following function in your methods object:

makeAdmin: function () {
	const self = this

	// create form data object
	const form = event.target
	const _id = form._id.value
	const formData = new FormData(form)

	// ask for confirmation
	swal.fire({
		title: 'Make admin',
		text: "Are you sure you want to make this member an admin ? You will lose your privileges as an admin.",
		icon: 'warning',
		showCancelButton: true,
		confirmButtonColor: '#3085d6',
		cancelButtonColor: '#d33',
		confirmButtonText: 'Yes'
	}).then(async function (result) {
		if (result.isConfirmed) {
			
			// call an AJAX
			const response = await axios.post(
                self.$apiURL + "/groups/makeAdmin",
                formData,
                {
                    headers: self.$headers
                }
            )

            if (response.data.status == "success") {
            	// update local object
            	self.group = response.data.group
            	
            	swal.fire("Make admin", response.data.message, "success")
            } else {
                swal.fire("Error", response.data.message, "error")
            }
		}
	})
},

Here, we are first confirming with the admin if he wants to make this member an admin. Also, we are displaying a message that once he assigns someone else as admin, he will lose his privileges as an admin. This means that he will not be able to edit or remove this group. Nor he can invite any new member to the group. Nor he can remove any member of the group or re-assign himself as an admin.

If the user confirms it, then it will send an AJAX request to the server that will handle this request. The server will also send the updated group object in response to the request. So we will simply update that object with our local object.

Why we are updating the local object ?

The benefit of doing this is that, as soon as the response is received, Vue will remove the delete buttons because the group object has been updated. Now we need to create a Node JS API that will handle this request.

At this point, if you click the “Change admin” button, you will see something like this:

change group admin
change group admin

Create Node JS API to change admin

Open your api/modules/groups.js file and create the following API in it:

router.post("/makeAdmin", auth, async function (request, result) {
    // logged-in user
    const user = request.user;

    // user ID
    const _id = request.fields._id;

    // get group ID
    const groupId = request.fields.groupId;

    // check if group exists
    const group = await db.collection("groups").findOne({
        _id: ObjectId(groupId)
    });

    if (group == null) {
        result.json({
            status: "error",
            message: "Group does not exists."
        });
        return;
    }

    // check if users exists
    const memberUser = await db.collection("users").findOne({
        _id: ObjectId(_id)
    });

    if (memberUser == null) {
        result.json({
            status: "error",
            message: "User does not exists."
        });
        return;
    }

    // check if you are an admin of the group
    if (group.createdBy._id.toString() != user._id.toString()) {
        result.json({
            status: "error",
            message: "Sorry, you are not group admin."
        });
        return;
    }

    // check if user is a member
    let isMember = false;
    for (let a = 0; a < group.members.length; a++) {
        if (group.members[a].user._id.toString() == _id) {
            isMember = true;
            break;
        }
    }

    if (!isMember) {
        result.json({
            status: "error",
            message: "Sorry, the user is not a member of this group."
        });
        return;
    }

    // remove user as member from groups collection
    await db.collection("groups").findOneAndUpdate({
        _id: group._id
    }, {
        $pull: {
            members: {
                "user._id": memberUser._id
            }
        }
    });

    // set the member as admin
    await db.collection("groups").findOneAndUpdate({
        _id: group._id
    }, {
        $set: {
            createdBy: {
                _id: memberUser._id,
                name: memberUser.name,
                email: memberUser.email
            }
        }
    });

    // add admin in members list
    await db.collection("groups").findOneAndUpdate({
        _id: group._id
    }, {
        $push: {
            members: {
                _id: ObjectId(),
                status: "accepted",
                sentBy: {
                    _id: user._id,
                    name: user.name,
                    email: user.email
                },
                user: {
                    _id: user._id,
                    name: user.name,
                    email: user.email
                },
                createdAt: new Date().getTime()
            }
        }
    });

    // get updated group object
    const updatedGroup = await db.collection("groups").findOne({
        _id: ObjectId(groupId)
    });

    // send response back to client
    result.json({
        status: "success",
        message: "Admin has been changed.",
        group: updatedGroup
    });
});

Test the app now and try to make someone else the admin of the group. You will see that you will become a normal member just like the other members. But the other person is now an admin of the group.

So you are free to leave the group now. Because as long as you are the admin, you cannot leave the group. But now you have given this responsibility to someone else, you are free to leave the group.

So that’s how you can change the group admin.





Please disable your adblocker or whitelist this site!