001/*
002 * Copyright 2020 Global Biodiversity Information Facility (GBIF)
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.gbif.api.model.common;
017
018import org.gbif.api.vocabulary.UserRole;
019
020import java.security.Principal;
021import java.util.Objects;
022
023import org.apache.commons.lang3.StringUtils;
024
025/**
026 * A wrapper class for a GBIF User that exposes the unique account name as the principal name.
027 * @deprecated replaced by {@link GbifUserPrincipal}
028 */
029@Deprecated
030public class UserPrincipal implements Principal {
031  private final User user;
032
033  public UserPrincipal(User user) {
034    Objects.requireNonNull(user);
035    this.user = user;
036  }
037
038  @Override
039  public String getName() {
040    return user.getUserName();
041  }
042
043  public User getUser() {
044    return user;
045  }
046
047  /**
048   * Checks if the user has the given string based role.
049   * We use strings here and not the enum to facilitate the use of the method with the standard SecurityContext
050   * which uses Strings for roles.
051   *
052   * @param role case insensitive role
053   *
054   * @return true if the user has the requested role
055   */
056  public boolean hasRole(String role) {
057    if (StringUtils.isNotEmpty(role)) {
058      try {
059        UserRole r = UserRole.valueOf(role.toUpperCase());
060        return user.hasRole(r);
061      } catch (IllegalArgumentException e) {
062        // ignore
063      }
064    }
065    return false;
066  }
067}