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.util.Objects; 021 022import org.apache.commons.lang3.StringUtils; 023 024/** 025 * A wrapper class for a GBIF User that exposes the unique account name as the principal name. 026 * Replacement for {@link UserPrincipal} 027 */ 028public class GbifUserPrincipal implements ExtendedPrincipal { 029 private final GbifUser user; 030 031 public GbifUserPrincipal(GbifUser user) { 032 Objects.requireNonNull(user, "user shall be provided"); 033 this.user = user; 034 } 035 036 @Override 037 public String getName() { 038 return user.getUserName(); 039 } 040 041 public GbifUser getUser() { 042 return user; 043 } 044 045 /** 046 * Checks if the user has the given string based role. 047 * We use strings here and not the enum to facilitate the use of the method with the standard SecurityContext 048 * which uses Strings for roles. 049 * 050 * @param role case insensitive role 051 * 052 * @return true if the user has the requested role 053 */ 054 @Override 055 public boolean hasRole(String role) { 056 if (StringUtils.isNotEmpty(role)) { 057 try { 058 UserRole r = UserRole.valueOf(role.toUpperCase()); 059 return user.hasRole(r); 060 } catch (IllegalArgumentException e) { 061 // ignore 062 } 063 } 064 return false; 065 } 066}