View Javadoc
1   /*
2    * Copyright 2019 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.bremersee.dccon.repository.ldap.transcoder;
18  
19  import java.util.Optional;
20  import lombok.extern.slf4j.Slf4j;
21  import org.bremersee.dccon.config.DomainControllerProperties;
22  import org.bremersee.dccon.model.Sid;
23  import org.ldaptive.ad.SecurityIdentifier;
24  import org.ldaptive.io.AbstractBinaryValueTranscoder;
25  
26  /**
27   * The SID value transcoder.
28   *
29   * @author Christian Bremer
30   */
31  @Slf4j
32  public class SidValueTranscoder extends AbstractBinaryValueTranscoder<Sid> {
33  
34    private DomainControllerProperties properties;
35  
36    /**
37     * Instantiates a new sid value transcoder.
38     *
39     * @param properties the properties
40     */
41    public SidValueTranscoder(DomainControllerProperties properties) {
42      this.properties = properties;
43    }
44  
45    @Override
46    public Sid decodeBinaryValue(byte[] value) {
47      return Optional.ofNullable(value)
48          .map(SecurityIdentifier::toString)
49          .map(objectSid -> Sid.builder()
50              .value(objectSid)
51              .systemEntity(isSystemEntity(objectSid))
52              .build())
53          .orElse(null);
54    }
55  
56    @Override
57    public byte[] encodeBinaryValue(Sid value) {
58      return Optional.ofNullable(value)
59          .map(Sid::getValue)
60          .map(SecurityIdentifier::toBytes)
61          .orElse(null);
62    }
63  
64    @Override
65    public Class<Sid> getType() {
66      return Sid.class;
67    }
68  
69    private boolean isSystemEntity(final String objectSid) {
70      if (!objectSid.startsWith(properties.getDefaultSidPrefix())) {
71        return true;
72      }
73      final int index = objectSid.lastIndexOf('-');
74      if (index > -1) {
75        try {
76          return properties
77              .getMaxSystemSidSuffix() >= Integer.parseInt(objectSid.substring(index + 1));
78        } catch (Exception ignored) {
79          // ignored
80        }
81      }
82      return false;
83    }
84  }