How to enable 2FA for nextcloud?

Hi, if I enable 2FA to be mandatory in admin panel under security then the user is not able to login, because he has not set up 2fa yet. I there a way he gets presented a screen to conduct steps to register 2fa?

If you’ve enabled 2fa for all users, you also need to provide at least an initial token to them using the " Two-Factor Admin Support" app. This cannot be configured by the user on their own.
If 2fa is still disabled but you want the users to enable it, you can use the " Two factor reminder" app to remind them to enable/configure 2fa.

Ok, thanks. Good to know, but not pretty handy in case of many users existing with no 2fa enabled already.

You can create a script and use the occ command to loop over all users, setup an initial 2fa token for all users, write it to file, convert into an image using ImageMagick and send into to each user.

Thanks. I have written a quick and dirty script to mail all users an initial code to log into account after globally enabling and forcing 2fa to all users:

#! /usr/bin/env bash
#Author:todde
#Version:0.1
#This script search for users, who do not have 2fa enabled on their account.
#Then a one time code is generated and mailed to the user for initial login
##############################################################################

site="https://www.example.net"
mail_from="admin@example.net"


#Find all active users
user=`sudo -u www-data php /var/www/nextcloud/occ user:list | cut -c 5- | cut -d : -f 1`



for i in $user; do

#Extract email address from each user
   email=`sudo -u www-data php /var/www/nextcloud/occ user:info $i | egrep 'email:' | cut -c 5- | cut -d : -f 2`;
#Compare if totp is already in place
   status=`sudo -u www-data php /var/www/nextcloud/occ twofactorauth:state $i | egrep 'totp' | cut -c 3-`;

#Do nothing if totp is enabled    
     if [ "$status" = "totp" ]; then
        echo $i  >> /dev/null
#Generate code for initial login and mail code and instructions 2 user
     else
        code=`sudo -u www-data php /var/www/nextcloud/occ twofactorauth:admin:generate-code $i`
        printf "Dear $i, please enable 2fa on $site.\n\n Your inital code: \n $code \n\n\n For detailed instructions visit:\n https://docs.nextcloud.com/server/latest/user_manual/en/user_2fa.html \n\n You must complete the above steps from instructions, otherwise you will not be able to log into your account a second time!\n\n Regards - Your Site Administrator from $site" | mail -s "Urgent notice from $site" $email -r $mail_from



     fi

done

Note that you might need to adjust path of occ command.

1 Like

you are parsing occ output in a hard way. Maybe you don’t know but occ can provide JSON output, which is easier to parse (e.g. using jq)

As an example here an output of all users along with their email…

occ user:list --output=json --info| jq '.[] |{(.user_id): .email}'

You are right :+1: I will check out json. Thanks for pointing me there.