001package org.gbif.api.model.common;
002
003import org.gbif.api.vocabulary.UserRole;
004
005import java.util.Objects;
006
007import com.google.common.base.Strings;
008
009/**
010 * A wrapper class for a GBIF User that exposes the unique account name as the principal name.
011 * Replacement for {@link UserPrincipal}
012 */
013public class GbifUserPrincipal implements ExtendedPrincipal {
014  private final GbifUser user;
015
016  public GbifUserPrincipal(GbifUser user) {
017    Objects.requireNonNull(user, "user shall be provided");
018    this.user = user;
019  }
020
021  @Override
022  public String getName() {
023    return user.getUserName();
024  }
025
026  public GbifUser getUser() {
027    return user;
028  }
029
030  /**
031   * Checks if the user has the given string based role.
032   * We use strings here and not the enum to facilitate the use of the method with the standard SecurityContext
033   * which uses Strings for roles.
034   *
035   * @param role case insensitive role
036   *
037   * @return true if the user has the requested role
038   */
039  public boolean hasRole(String role) {
040    if (!Strings.isNullOrEmpty(role)) {
041      try {
042        UserRole r = UserRole.valueOf(role.toUpperCase());
043        return user.hasRole(r);
044      } catch (IllegalArgumentException e) {
045        // ignore
046      }
047    }
048    return false;
049  }
050}