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 java.util.Objects;
019
020import javax.security.auth.Subject;
021
022/**
023 * Similar to {@link GbifUserPrincipal} but represents an application instead of a user.
024 * The appKey is used as the unique account name and is exposed as the principal name.
025 */
026public class AppPrincipal implements ExtendedPrincipal {
027
028  private final String appKey;
029  private final String appRole;
030
031  /**
032   * {@link AppPrincipal} constructor.
033   *
034   * @param appKey  mandatory, appKey of the application that is now authenticated.
035   * @param appRole optionally, the "role" of the app as {@link String}. Mostly to use jsr250 @RolesAllowed.
036   */
037  public AppPrincipal(String appKey, String appRole) {
038    Objects.requireNonNull(appKey, "appKey shall be provided");
039    this.appKey = appKey;
040    this.appRole = appRole;
041  }
042
043  @Override
044  public String getName() {
045    return appKey;
046  }
047
048  @Override
049  public boolean implies(Subject subject) {
050    return false;
051  }
052
053  @Override
054  public boolean hasRole(String role) {
055    return appRole != null && appRole.equalsIgnoreCase(role);
056  }
057}