[NEW] Add setting to configure default role for user on manual registration (#20650)

Co-authored-by: Diego Sampaio <chinello@gmail.com>
pull/22367/head
Lucas Sartor Chauvin 5 years ago committed by GitHub
parent aecc4d3656
commit 1b9dc26d66
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 13
      app/authentication/server/startup/index.js
  2. 3
      app/lib/server/functions/saveUser.js
  3. 3
      app/lib/server/startup/settings.js
  4. 3
      packages/rocketchat-i18n/i18n/en.i18n.json
  5. 5
      packages/rocketchat-i18n/i18n/pt-BR.i18n.json
  6. 12
      server/services/user/lib/getNewUserRoles.ts
  7. 61
      tests/end-to-end/api/01-users.js

@ -18,6 +18,7 @@ import {
} from '../lib/restrictLoginAttempts';
import './settings';
import { getClientAddress } from '../../../../server/lib/getClientAddress';
import { getNewUserRoles } from '../../../../server/services/user/lib/getNewUserRoles';
Accounts.config({
@ -209,10 +210,12 @@ Accounts.onCreateUser(function(options, user = {}) {
});
Accounts.insertUserDoc = _.wrap(Accounts.insertUserDoc, function(insertUserDoc, options, user) {
let roles = [];
const noRoles = !user?.hasOwnProperty('globalRoles');
const globalRoles = [];
if (Match.test(user.globalRoles, [String]) && user.globalRoles.length > 0) {
roles = roles.concat(user.globalRoles);
globalRoles.push(...user.globalRoles);
}
delete user.globalRoles;
@ -220,10 +223,12 @@ Accounts.insertUserDoc = _.wrap(Accounts.insertUserDoc, function(insertUserDoc,
if (user.services && !user.services.password) {
const defaultAuthServiceRoles = String(settings.get('Accounts_Registration_AuthenticationServices_Default_Roles')).split(',');
if (defaultAuthServiceRoles.length > 0) {
roles = roles.concat(defaultAuthServiceRoles.map((s) => s.trim()));
globalRoles.push(...defaultAuthServiceRoles.map((s) => s.trim()));
}
}
const roles = getNewUserRoles(globalRoles);
if (!user.type) {
user.type = 'user';
}
@ -270,7 +275,7 @@ Accounts.insertUserDoc = _.wrap(Accounts.insertUserDoc, function(insertUserDoc,
}
}
if (roles.length === 0) {
if (noRoles || roles.length === 0) {
const hasAdmin = Users.findOne({
roles: 'admin',
type: 'user',

@ -10,6 +10,7 @@ import { settings } from '../../../settings';
import { passwordPolicy } from '../lib/passwordPolicy';
import { validateEmailDomain } from '../lib';
import { validateUserRoles } from '../../../../ee/app/authorization/server/validateUserRoles';
import { getNewUserRoles } from '../../../../server/services/user/lib/getNewUserRoles';
import { saveUserIdentity } from './saveUserIdentity';
import { checkEmailAvailability, checkUsernameAvailability, setUserAvatar, setEmail, setStatusText } from '.';
@ -258,7 +259,7 @@ export const saveUser = function(userId, userData) {
const updateUser = {
$set: {
roles: userData.roles || ['user'],
roles: userData.roles || getNewUserRoles(),
...typeof userData.name !== 'undefined' && { name: userData.name },
settings: userData.settings || {},
},

@ -228,6 +228,9 @@ settings.addGroup('Accounts', function() {
value: true,
},
});
this.add('Accounts_Registration_Users_Default_Roles', 'user', {
type: 'string',
});
this.add('Accounts_PasswordReset', true, {
type: 'boolean',
public: true,

@ -203,6 +203,9 @@
"Accounts_Registration_AuthenticationServices_Default_Roles": "Default Roles for Authentication Services",
"Accounts_Registration_AuthenticationServices_Default_Roles_Description": "Default roles (comma-separated) users will be given when registering through authentication services",
"Accounts_Registration_AuthenticationServices_Enabled": "Registration with Authentication Services",
"Accounts_Registration_Users_Default_Roles": "Default Roles for Users",
"Accounts_Registration_Users_Default_Roles_Description": "Default roles (comma-separated) users will be given when registering through manual registration (including via API)",
"Accounts_Registration_Users_Default_Roles_Enabled": "Enable Default Roles for Manual Registration",
"Accounts_Registration_InviteUrlType": "Invite URL Type",
"Accounts_Registration_InviteUrlType_Direct": "Direct",
"Accounts_Registration_InviteUrlType_Proxy": "Proxy",

@ -185,9 +185,10 @@
"Accounts_Password_Policy_MinLength": "Tamanho mínimo",
"Accounts_Password_Policy_MinLength_Description": "Garante que as senhas tenham pelo menos esta quantidade de caracteres. Use `-1 para desativar.",
"Accounts_PasswordReset": "Redefinição de Senha",
"Accounts_Registration_AuthenticationServices_Enabled": "Registro com os Serviços de Autenticação",
"Accounts_Registration_AuthenticationServices_Default_Roles": "Funções padrão para serviços de autenticação",
"Accounts_Registration_AuthenticationServices_Default_Roles_Description": "Funções padrão (separadas por vírgulas) serão fornecidas ao registrar-se através de serviços de autenticação",
"Accounts_Registration_AuthenticationServices_Enabled": "Registro com os Serviços de Autenticação",
"Accounts_Registration_Users_Default_Roles_Enabled": "Ativar funções padrão para registro manual",
"Accounts_Registration_InviteUrlType": "Tipo de URL do Convite",
"Accounts_Registration_InviteUrlType_Direct": "Direta",
"Accounts_Registration_InviteUrlType_Proxy": "Proxy",
@ -198,6 +199,8 @@
"Accounts_RegistrationForm_Secret_URL": "URL Secreta",
"Accounts_RegistrationForm_SecretURL": "URL Secreta para o Formulário de Registro",
"Accounts_RegistrationForm_SecretURL_Description": "Você deve fornecer uma seqüência aleatória que será adicionada à sua URL de registro. Exemplo: https://open.rocket.chat/register/[secret_hash]",
"Accounts_Registration_Users_Default_Roles": "Funções padrão para usuários",
"Accounts_Registration_Users_Default_Roles_Description": "Funções padrão (separadas por vírgulas) que serão fornecidas ao registrar-se de forma manual (incluindo via API)",
"Accounts_RequireNameForSignUp": "Nome é obrigatório para cadastro",
"Accounts_RequirePasswordConfirmation": "Requer Confirmação de Senha",
"Accounts_SearchFields": "Campos a considerar na busca",

@ -0,0 +1,12 @@
import { settings } from '../../../../app/settings/server';
export function getNewUserRoles(previousRoles?: string[]): string[] {
const currentRoles = previousRoles ?? [];
const defaultUserRoles = String(settings.get('Accounts_Registration_Users_Default_Roles'))
.split(',')
.map((role) => role.trim())
.filter(Boolean);
return [...new Set([...currentRoles, ...defaultUserRoles])];
}

@ -226,6 +226,67 @@ describe('[Users]', function() {
reservedWords.forEach((name) => {
failCreateUser(name);
});
describe('users default roles configuration', () => {
before(async () => {
await updateSetting('Accounts_Registration_Users_Default_Roles', 'user,admin');
});
after(async () => {
await updateSetting('Accounts_Registration_Users_Default_Roles', 'user');
});
it('should create a new user with default roles', (done) => {
const username = `defaultUserRole_${ apiUsername }${ Date.now() }`;
const email = `defaultUserRole_${ apiEmail }${ Date.now() }`;
request.post(api('users.create'))
.set(credentials)
.send({
email,
name: username,
username,
password,
})
.expect('Content-Type', 'application/json')
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
expect(res.body).to.have.nested.property('user.username', username);
expect(res.body).to.have.nested.property('user.emails[0].address', email);
expect(res.body).to.have.nested.property('user.active', true);
expect(res.body).to.have.nested.property('user.name', username);
expect(res.body.user.roles).to.have.members(['user', 'admin']);
})
.end(done);
});
it('should create a new user with only the role provided', (done) => {
const username = `defaultUserRole_${ apiUsername }${ Date.now() }`;
const email = `defaultUserRole_${ apiEmail }${ Date.now() }`;
request.post(api('users.create'))
.set(credentials)
.send({
email,
name: username,
username,
password,
roles: ['guest'],
})
.expect('Content-Type', 'application/json')
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
expect(res.body).to.have.nested.property('user.username', username);
expect(res.body).to.have.nested.property('user.emails[0].address', email);
expect(res.body).to.have.nested.property('user.active', true);
expect(res.body).to.have.nested.property('user.name', username);
expect(res.body.user.roles).to.have.members(['guest']);
})
.end(done);
});
});
});
describe('[/users.register]', () => {

Loading…
Cancel
Save