001/*
002 *   Copyright 2024 Vonage
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 com.vonage.client.auth.camara;
017
018import com.vonage.client.auth.BearerAuthMethod;
019
020/**
021 * Auth method for Vonage Network APIs. Designed to be replaced on each request.
022 */
023public final class NetworkAuthMethod extends BearerAuthMethod {
024    private final NetworkAuthClient networkAuthClient;
025    private TokenRequest tokenRequest;
026    private BackendAuthRequest backendParams;
027
028    /**
029     * Creates a new Bearer auth method which uses the specified params to exchange for an access token.
030     *
031     * @param client The network auth client to use.
032     * @param request The token request parameters.
033     */
034    public NetworkAuthMethod(NetworkAuthClient client, TokenRequest request) {
035        this.networkAuthClient = client;
036        this.tokenRequest = request;
037    }
038
039    /**
040     * Creates a new Bearer auth method which uses the specified params to
041     * automatically obtain the token parameters in order to exchange them for an access token.
042     *
043     * @param client The network auth client to use.
044     * @param request The initial Back-End request parameters to use for obtaining the tokens.
045     */
046    public NetworkAuthMethod(NetworkAuthClient client, BackendAuthRequest request) {
047        this.networkAuthClient = client;
048        this.backendParams = request;
049    }
050
051    @Override
052    protected String getBearerToken() {
053        if (backendParams != null) {
054            tokenRequest = new TokenRequest(networkAuthClient.buildOidcUrl(backendParams).getAuthReqId());
055        }
056        return networkAuthClient.getCamaraToken(tokenRequest).getAccessToken();
057    }
058
059    @Override
060    public int getSortKey() {
061        return 5;
062    }
063}