1
0
mirror of https://github.com/1C-Company/v8-code-style.git synced 2024-11-28 09:33:06 +02:00

#427 Добавлена проверка использования метода РольДоступна

This commit is contained in:
Artem Iliukhin 2021-12-18 00:53:31 +03:00
parent 4bc051bd6f
commit 54a20871ef
10 changed files with 239 additions and 0 deletions

View File

@ -17,6 +17,8 @@
#### Код модулей
- Использован метод "РольДоступна()"
#### Запросы
#### Права ролей

View File

@ -0,0 +1,22 @@
# The "IsInRole" method was used
To check access rights in the code, use the AccessRight method.
## Noncompliant Code Example
```bsl
If IsInRole("AddClient") Then ...
```
## Compliant Solution
```bsl
If AccessRight("Add", Metadata.Catalogs.Client) Then ...
```
This approach allows you to increase the code robustness when configuration roles are revised.
## See
- [Configuring roles and access rights](https://support.1ci.com/hc/en-us/articles/360011122599-Configuring-roles-and-access-rights)
- [Checking access rights](https://support.1ci.com/hc/en-us/articles/360011003180-Checking-access-rights)

View File

@ -0,0 +1,25 @@
# Использован метод "РольДоступна"
Для проверки прав доступа в коде следует использовать метод ПравоДоступа.
## Неправильно
```bsl
Если РольДоступна("ДобавлениеИзменениеСтранМира") Тогда ...
```
## Правильно
```bsl
Если ПравоДоступа("Редактирование", Метаданные.Справочники.СтраныМира) Тогда ...
```
Такой подход позволяет повысить устойчивость кода к пересмотру состава
ролей в конфигурации, а также обеспечить работоспособность конфигурации
в особых режимах работы, когда реальный состав ролей отличается от
спроектированного
## См.
- [Настройка ролей и прав доступа](https://its.1c.ru/db/v8std#content:689:hdoc)
- [Проверка прав доступа](https://its.1c.ru/db/v8std#content:737:hdoc:3)

View File

@ -152,6 +152,10 @@
category="com.e1c.v8codestyle.bsl"
class="com.e1c.v8codestyle.internal.bsl.ExecutableExtensionFactory:com.e1c.v8codestyle.bsl.check.ModuleUnusedMethodCheck">
</check>
<check
category="com.e1c.v8codestyle.bsl"
class="com.e1c.v8codestyle.bsl.check.IsInRoleCheck">
</check>
</extension>
<extension

View File

@ -0,0 +1,100 @@
/*******************************************************************************
* Copyright (C) 2021, 1C-Soft LLC and others.
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* 1C-Soft LLC - initial API and implementation
*******************************************************************************/
package com.e1c.v8codestyle.bsl.check;
import static com._1c.g5.v8.dt.bsl.model.BslPackage.Literals.STATIC_FEATURE_ACCESS;
import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
import com._1c.g5.v8.dt.bsl.model.Expression;
import com._1c.g5.v8.dt.bsl.model.FeatureAccess;
import com._1c.g5.v8.dt.bsl.model.Invocation;
import com._1c.g5.v8.dt.bsl.model.StaticFeatureAccess;
import com._1c.g5.v8.dt.bsl.model.StringLiteral;
import com._1c.g5.v8.dt.bsl.model.util.BslUtil;
import com.e1c.g5.v8.dt.check.CheckComplexity;
import com.e1c.g5.v8.dt.check.ICheckParameters;
import com.e1c.g5.v8.dt.check.settings.IssueSeverity;
import com.e1c.g5.v8.dt.check.settings.IssueType;
/**
* Checking the use of the IsInRole method that is not recommended.
*
* @author Artem Iliukhin
*/
public class IsInRoleCheck
extends AbstractModuleStructureCheck
{
private static final String EXCEPTION_ROLES_PARAM = "exceptionRoles"; //$NON-NLS-1$
private static final String NAME = "IsInRole"; //$NON-NLS-1$
private static final String NAME_RU = "РольДоступна"; //$NON-NLS-1$
private static final String CHECK_ID = "using-isinrole"; //$NON-NLS-1$
private static final String DEFAULT_EXCEPTION_ROLES_PARAM = ""; //$NON-NLS-1$
public IsInRoleCheck()
{
super();
}
@Override
public String getCheckId()
{
return CHECK_ID;
}
@Override
protected void configureCheck(CheckConfigurer builder)
{
builder.title(Messages.IsInRoleCheck_Using_IsInRole)
.description(Messages.IsInRoleCheck_Use_AccessRight)
.complexity(CheckComplexity.NORMAL)
.severity(IssueSeverity.MINOR)
.issueType(IssueType.WARNING)
.module()
.checkedObjectType(STATIC_FEATURE_ACCESS)
.parameter(EXCEPTION_ROLES_PARAM, String.class, DEFAULT_EXCEPTION_ROLES_PARAM,
Messages.IsInRoleCheck_Exception_Roles);
}
@Override
protected void check(Object object, ResultAcceptor resultAceptor, ICheckParameters parameters,
IProgressMonitor monitor)
{
Invocation invocation = BslUtil.getInvocation((FeatureAccess)object);
if (invocation == null)
{
return;
}
String name = ((StaticFeatureAccess)object).getName();
if (name.equalsIgnoreCase(NAME_RU) || name.equalsIgnoreCase(NAME))
{
final String exRoles = parameters.getString(EXCEPTION_ROLES_PARAM).trim();
List<String> roles = List.of(exRoles.split("[\\s,]+")); //$NON-NLS-1$
List<Expression> params = invocation.getParams();
if (!params.isEmpty() && params.get(0) instanceof StringLiteral)
{
StringLiteral param = (StringLiteral)params.get(0);
if (!param.getLines().isEmpty() && roles.contains(param.getLines().get(0).replace("\"", ""))) //$NON-NLS-1$ //$NON-NLS-2$
{
return;
}
}
resultAceptor.addIssue(Messages.IsInRoleCheck_Use_AccessRight_instead_IsInRole, object);
}
}
}

View File

@ -166,6 +166,14 @@ final class Messages
public static String FormModuleMissingPragmaCheck_title;
public static String IsInRoleCheck_Exception_Roles;
public static String IsInRoleCheck_Use_AccessRight;
public static String IsInRoleCheck_Use_AccessRight_instead_IsInRole;
public static String IsInRoleCheck_Using_IsInRole;
static
{
// initialize resource bundle

View File

@ -82,6 +82,14 @@ FormModulePragmaCheck_description = Use form module compilation pragma
FormModulePragmaCheck_title = Use form module compilation pragma
IsInRoleCheck_Exception_Roles=Untested roles
IsInRoleCheck_Use_AccessRight=Use the AccessRight() function instead of IsInRole()
IsInRoleCheck_Use_AccessRight_instead_IsInRole=Use the AccessRight() function instead of IsInRole()
IsInRoleCheck_Using_IsInRole=Using "IsInRole" method
MethodTooManyPramsCheck_Max_parameters = Max parameters
MethodTooManyPramsCheck_Max_parameters_with_default_value = Max parameters with default value

View File

@ -82,6 +82,14 @@ FormModulePragmaCheck_description = Использование директив
FormModulePragmaCheck_title = Использование директив компиляции модуля формы
IsInRoleCheck_Exception_Roles = Непроверяемые роли
IsInRoleCheck_Use_AccessRight = Следует использовать метод "ПравоДоступа" вместо "РольДоступна"
IsInRoleCheck_Using_IsInRole = Использован не рекомендованный метод "РольДоступна"
IsInRoleCheck_Use_AccessRight_instead_IsInRole = Используйте функцию "ПравоДоступа()" вместо "РольДоступна()"
MethodTooManyPramsCheck_Max_parameters = Максимум параметров
MethodTooManyPramsCheck_Max_parameters_with_default_value = Максимум параметров со значением по умолчанию

View File

@ -0,0 +1,7 @@
Процедура Тест()
Если РольДоступна("ИмяРоли") Тогда
//
КонецЕсли
КонецПроцедуры

View File

@ -0,0 +1,55 @@
/*******************************************************************************
* Copyright (C) 2021, 1C-Soft LLC and others.
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* 1C-Soft LLC - initial API and implementation
*******************************************************************************/
package com.e1c.v8codestyle.bsl.check.itests;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Test;
import com._1c.g5.v8.dt.validation.marker.Marker;
import com.e1c.v8codestyle.bsl.check.IsInRoleCheck;
/**
* Tests for {@link IsInRoleCheck} check.
*
* @author Artem Iliukhin
*/
public class IsInRoleCheckTest
extends AbstractSingleModuleTestBase
{
private static final String USING_IS_IN_ROLE_METHOD = "Use the AccessRight() function instead of IsInRole()";
public IsInRoleCheckTest()
{
super(IsInRoleCheck.class);
}
/**
* Test IsInRole method.
*
* @throws Exception the exception
*/
@Test
public void testIsInRoleMethod() throws Exception
{
updateModule(FOLDER_RESOURCE + "isinrole-method.bsl");
List<Marker> markers = getModuleMarkers();
assertEquals(1, markers.size());
Marker marker = markers.get(0);
assertEquals(USING_IS_IN_ROLE_METHOD, marker.getMessage());
}
}