001/*
002 *  Copyright 2023 Anyware Services
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.ametys.plugins.extrausermgt.oauth;
017
018import java.util.Optional;
019
020import org.ametys.runtime.plugin.component.AbstractThreadSafeComponentExtensionPoint;
021
022import com.nimbusds.oauth2.sdk.id.State;
023import com.nimbusds.oauth2.sdk.token.AccessToken;
024
025/**
026 * Extension point registering all the OAuth provider currently available
027 */
028public class OauthProviderExtensionPoint extends AbstractThreadSafeComponentExtensionPoint<OAuthProvider>
029{
030    /** The avalon role */
031    public static final String ROLE = OauthProviderExtensionPoint.class.getName();
032    
033    /**
034     * Get the stored access token if it exist.
035     * 
036     * If a token exists, but is expired, this method will silently try to refresh it.
037     * @param providerId the provider that granted the token
038     * @return the access token or empty
039     */
040    public Optional<AccessToken> getStoredAccessToken(String providerId)
041    {
042        return getExtension(providerId).getStoredAccessToken();
043    }
044    
045    /**
046     * Get the provider linked to the state.
047     * @param state the state linked to a provider
048     * @return the provider id
049     * @throws IllegalStateException if the state is not linked to a provider
050     */
051    public OAuthProvider getProviderForState(State state)
052    {
053        for (String id : getExtensionsIds())
054        {
055            if (getExtension(id).isKnownState(state))
056            {
057                return getExtension(id);
058            }
059        }
060        return null;
061    }
062}