Skip to content

Instantly share code, notes, and snippets.

@aelkz
Last active December 5, 2019 15:35
Show Gist options
  • Save aelkz/ef7b3c69b80d6dbaef093a849fdacb6a to your computer and use it in GitHub Desktop.
Save aelkz/ef7b3c69b80d6dbaef093a849fdacb6a to your computer and use it in GitHub Desktop.
3scale - Developer Portal
{% if current_user %}
<div class="panel-heading">
<h3>Introdução</h3>
<p>Este documento descreve as API de Negócio que a Organização <b>{{ current_account.name }}</b> possui acesso, que devem ser utilizadas por aplicações que necessitam de acesso aos serviços disponibilizados por essas API's. A documentação é baseada na especificação OpenAPI e utiliza o Swagger para expor de modo interativo.</p>
<p>Para realizar chamadas as API's é necessário enviar o access_token no cabeçalho HTTP <b>Authorization</b> usando o <a href="https://tools.ietf.org/html/rfc6750#section-2.1">Bearer authentication</a>.</p>
<p>As API's de <a href=/docs/auth>autenticação</a> estão descritas em outro documento.</p>
<p>Para facilitar a interação com as API's utilize o botão abaixo para Autenticar/Autorizar e Obter o Token de Acesso que será enviado no cabeçalho Authorization. Para Autenticar utilize as credenciais da Conta de Serviço. Após a autenticação, clique no botão Obter Token. O Token de acesso recebido será adicionado automaticamente ao cabeçalho Authorization das requisições.</p></br>
<pre style="background-color: #ddd; border: 1px solid #ccc; padding: 10px; word-wrap: break-word; white-space: pre-wrap; visibility:hidden" id="output"></pre>
{% include 'oauth-widget' %}
{% cdn_asset /swagger-ui/2.2.10/swagger-ui.js %}
{% cdn_asset /swagger-ui/2.2.10/swagger-ui.css %}
{% include 'shared/swagger_ui' %}
<div class="swagger-section">
<div id="message-bar" class="swagger-ui-wrap">&nbsp;</div>
{% for _service in current_account.subscribed_services %}
{% if _service.system_name == provider.api_specs[_service.system_name].system_name %}
<div id="swagger-ui-container-{{ provider.api_specs[_service.system_name].system_name }}"
class="swagger-ui-wrap">
</div>
{% assign have_service = true %}
{% endif %}
{% endfor %}
</div>
{% if have_service %}
<div class='apidocs-param-tips apidocs-signin-message' style='display:none;'>
<p><a href='#'>Entre</a> na sua conta para ter acesso rápido a dados úteis para preenchimento.</p>
</div>
<script type="text/javascript">
(function () {
var url = '';
{% for _service in current_account.subscribed_services %}
{% if _service.system_name == provider.api_specs[_service.system_name].system_name %}
url = "{{ provider.api_specs[_service.system_name].url }}";
window.swaggerUi{{ provider.api_specs[_service.system_name].system_name | replace: "-", "_" }} = new SwaggerUi({
url: url,
dom_id: 'swagger-ui-container-{{ provider.api_specs[_service.system_name].system_name }}',
supportedSubmitMethods: ['get', 'post', 'put', 'delete', 'patch'],
apisSorter: 'alpha', // can also be a function
operationsSorter: 'method', // can also be 'alpha' or a function
onComplete: function(swaggerApi, swaggerUi) {
$('#swagger-ui-container-{{ provider.api_specs[_service.system_name].system_name }} pre code').each(function(i, e) {hljs.highlightBlock(e)});},
docExpansion: 'list',
transport: function (httpClient, obj) {
obj.url = obj.url.replace(/^http:\/\//i, 'https://');
return httpClient.execute(obj);
}
});
window.swaggerUi{{ provider.api_specs[_service.system_name].system_name | replace: "-", "_" }}.load();
{% endif %}
{% endfor %}
}());
</script>
</div>
<!-- end swagger-section-->
{% else %}
<div>Nenhuma documentação disponível para {{ current_account.name }}.</div>
{% endif %}
{% include 'keycloak-client' %}
{% endif %}
{% for auth_provider in site.authentication_providers %}
{% case auth_provider.kind %}
{% when 'keycloak' %}
{% assign auth_url = {{auth_provider.authorize_url}} | split: '?' | first %}
{% endcase %}
{% endfor %}
{% assign auth_url = "https://sso73.apps.arekkusu.io/auth/realms/3scale-api/protocol/openid-connect/auth" %}
<script type="text/javascript">
var str = '{{auth_url}}',
delimiter = '/auth',
start = 2,
fragments = str.split(delimiter).slice(0,start),
result = fragments.join(delimiter);
var clientId;
var clientSecret;
function setCredentials(clientId, clientSecret, element) {
element.setAttribute("onclick", "getToken(clientId, clientSecret);")
}
function addKey(call) {
var sel = document.getElementById('keySelect');
var el = document.getElementById('oidc');
keys = sel.options[sel.selectedIndex].value;
clientSecret = keys.split("|")[0]
clientId = keys.split("|")[1]
if (call == 'auth') {
var state = setCookie('state', 12, 1)
setCookie('application', clientId, 2)
el.setAttribute("href", "{{auth_url}}?response_type=code&client_id=" + clientId + "&client_secret=" + clientSecret + "&redirect_uri=https://" + "{{provider.domain}}" + "{{request.path}}" + "&state=" + state);
} else if (call == 'token') {
setCredentials(clientId, clientSecret, el);
}
}
function getToken(clientId, clientSecret) {
{% assign path = request.path | remove_first: '/' %}
{% assign params = request.request_uri | split: '?' | last %}
{% if params contains 'state=' %}
window.history.replaceState({}, document.title, "/" + "{{path}}");
{% assign code = params | split: 'code=' | last | split: '&' | first %}
var code = '{{ code }}';
var tokenUrl = result + '/token';
var formData = "response_type=code&client_id=" + clientId + "&client_secret=" + clientSecret + "&redirect_uri=https://" + "{{provider.domain}}" + "{{request.path}}" + "&state=" + getCookie('state') + "&grant_type=authorization_code&code=" + code; //Name value Pair
$.ajax({
url : tokenUrl,
type: "POST",
data : formData,
success: function(response, textStatus, jqXHR)
{
var token = response.access_token;
console.log("reponse: " + response); //data - response from server
var tokenResponse = false;
var inputs = $("input[name='Authorization']");
if (inputs.length > 0) {
tokenResponse = true;
// set the value of the inputs
inputs.each(function(index) {
$(this).val('Bearer '+token);
});
console.log("Success! Access Token: " + token);
output("Sucesso! Token obtido.\nAccess Token: " + token + "\nExpires In:" + response.expires_in);
$('#keySelect').attr('onchange', 'addKey("auth")');
$('#oidc').text('Authorizar');
return;
}
},
error: function (response, textStatus, jqXHR)
{
if (response == null) {
console.log("reponse: " + response); //data - response from server
output("Erro! Erro: " + textStatus + "n\Erro: " + response.error + "\nMessage: " + error_description);
$('#keySelect').attr('onchange', 'addKey("auth")');
$('#oidc').text('Authorizar');
}else{
output("Erro! O ocorreu erro na solicitação de Token.\nFavor Autorizar novamente.");
$('#keySelect').attr('onchange', 'addKey("auth")');
$('#oidc').text('Authorizar');
}
}
});
{% elsif params contains 'state=&' %}
console.log('state is invalid or expired');
output("Erro! message: 'state é inválido ou expirou.\nFavor autorizar novamente.");
$('#keySelect').attr('onchange', 'addKey("auth")');
$('#oidc').text('Authorizar');
{% endif %}
};
</script>
<form action="{{ urls.signup }}" method="get">
<div class="container">
<h1>Pick your plan!</h1><br/>
{% for service in provider.services %}
<font style="size:16px;color:#ff0066;font-weight:bold;text-transform:uppercase">{{ service.name }}</font>
<div class="row">
{% for plan in service.application_plans%}
<div class="col-md-4">
<article class="panel panel-default">
<div class="panel-heading">
<font style="size:12px;color:blue;">{{ plan.name }}</font>
</div>
<div class="panel-body">
<div class="row">
{% if plan.features == present %}
<div class="col-md-6">
<h5>Features</h5>
<ul class="features list-unstyled">
{% for feature in plan.features %}
<li>
<i class="fa fa-check"></i> {{ feature.name }}
</li>
{% endfor %}
</ul>
</div>
{% endif %}
<div class="col-md-6">
<h5>Limits</h5>
<ul class="limits list-unstyled">
{% if plan.usage_limits == present %} {% for limit in plan.usage_limits %}
<li>
<i class="fa fa-signal" style="color:green"></i> {{ limit.metric.name }} <br> <img src="/images/right_arrow.png" weight="18" height="12"/> {{ limit.value }} {{ limit.metric.unit }}s per {{ limit.period }}
</li>
{% endfor %} {% else %}
<li>
<i class="fa fa-signal"></i> No limits
</li>
{% endif %}
</ul>
</div>
</div>
</div>
<div class="panel-footer">
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-12">
<input type="checkbox" name="plan_ids[]" value="{{ plan.id }}">&nbsp;Signup to {{ plan.name }}</input>
<!--
<input type="hidden" name="plan_ids[]" value="{{ service.service_plans.first.id }}"></input>
-->
</div>
</div>
</div>
</div>
</div>
</article>
</div>
{% endfor %}
</div>
{% endfor %}
<div class="container text-center">
<button type="submit" class="btn btn-cta-primary">Signup</button>
</div>
</div>
</form>
<script src="/javascripts/cookie.js"></script>
{% if request.request_uri contains "state=" %}
<script type="text/javascript">
var stateValue = getCookie('state');
{% assign url = request.request_uri %}
{% assign modified_params = url | replace: 'session_state', 'session_id'%}
{% assign returnedState = modified_params | split: '?state=' | last | split: '&' | first | split: 'state=' | last %}
if(stateValue == '{{returnedState}}') {
console.log("Sucesso! Autorizado.");
output("Sucesso! Autorizado.");
}else{
console.log("Error! Invalid state");
output("Erro! state inválido");
$('#keySelect').attr('onchange', 'addKey("auth")');
$('#oidc').text('Authorizar');
}
</script>
{% assign url = request.request_uri %}
{% assign param = url | split: 'client_id=' | last %}
<a class="btn btn-primary" id="oidc" href="javascript:void(0);" >Obter Token</a>
<select id="keySelect" onchange="addKey('token')">
<option>Selecione sua Aplicação e API</option>
{% for application in current_account.applications %}
<option value="{{application.keys.first}}|{{application.application_id}}">{{application.name}} | {{application.service.name}}</option>
{% endfor %}
</select>
{% else %}
<a class="btn btn-primary" id="oidc" href="">Authorizar</a>
<select id="keySelect" onchange="addKey('auth')">
<option>Selecione sua Aplicação e API</option>
{% for application in current_account.applications %}
<option value="{{application.keys.first}}|{{application.application_id}}">{{application.name}} | {{application.service.name}}</option>
{% endfor %}
</select>
{% endif %}
@aelkz
Copy link
Author

aelkz commented Dec 2, 2019

right_arrow

@aelkz
Copy link
Author

aelkz commented Dec 5, 2019

keycloak-client: change to your Keycloak host at variable auth_url.

@aelkz
Copy link
Author

aelkz commented Dec 5, 2019

arrow04
arrow03
arrow02
arrow01

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment