Tagged Node.js

Oracle Kubernetes (OKE): Deploying a Custom Node.js Web Application Integrated with Identity Cloud Service for Unique Single Sign On (SSO) User Experience


In this post we are deploying a custom Node.js web application in Oracle Kubernetes Engine (OKE).

What we want to show is how to configure the custom web application in order to have a unique Single Sing On experience.

First part

Follow this tutorial here explaining how to enable SSO to the web app running locally

Second part

Now we are making small changes to deploy on kubernetes

Create a Dockerfile in the nodejs folder of the cloned project with the following:
FROM oraclelinux:7-slim
WORKDIR /app
ADD . /app
RUN curl --silent --location https://rpm.nodesource.com/setup_11.x | bash -
RUN yum -y install nodejs npm --skip-broken
EXPOSE 3000
CMD ["npm","start"]
Create K8s deployment file as follows:
apiVersion: v1
kind: Service
metadata:
name: idcsnodeapp
spec:
type: LoadBalancer
selector:
app: idcsnodeapp
ports:
- name: client
protocol: TCP
port: 3000
Deploy to k8s:
kubectl apply -f service.yaml
Grab the url of the new external load-balancer service created in k8s and modify the file auth.js with the appropriate values in your cloud environment
var ids = {
oracle: {
"ClientId": "client id of the IdCS app",
"ClientSecret": "client secret of the IdCS app",
"ClientTenant": "tenant id (idcs-xxxxxxxxxxxx)",
"IDCSHost": "https://tenantid.identity.oraclecloud.com",
"AudienceServiceUrl" : "https://tenantid.identity.oraclecloud.com",
"TokenIssuer": "https://identity.oraclecloud.com/",
"scope": "urn:opc:idm:t.user.me openid",
"logoutSufix": "/oauth2/v1/userlogout",
"redirectURL": "http://k8sloadbalancerip:3000/callback",
"LogLevel":"warn",
"ConsoleLog":"True"
}
};
Build the container and push to a repo you have write access to, such as:
docker build -t javiermugueta/idcsnodeapp .
docker push javiermugueta/idcsnodeapp
Modify the IdCS application with the public IP of the k8s load-balancer service
a
Create k8s deployment file as follows:
apiVersion: apps/v1
kind: Deployment
metadata:
name: idcsnodeapp
labels:
app: idcsnodeapp
spec:
replicas: 1
selector:
matchLabels:
app: idcsnodeapp
strategy:
type: Recreate
template:
metadata:
labels:
app: idcsnodeapp
spec:
containers:
- image: javiermugueta/idcsnodeapp
name: idcsnodeapp
ports:
- containerPort: 3000
name: idcsnodeapp


Deploy to k8s
kubectl apply -f  deployment.yaml
Test the app and verify SSO is working:

This slideshow requires JavaScript.

Hope it helps! 🙂

 

Creating a Fast&Simple Container for Sending Messages to a Topic in Oracle Event Hub Cloud Service (aka OEHCS, which is a Kafka cluster) and Deploying it to Kubernetes Cluster


The container uses 4 environment variables, you can find a container already built for you here

SOURCE CODE OF THE PRODUCER

var sleep = require('system-sleep');

const oehcs_connect_url = process.env.OEHCS_CONNECTURL

const topic_name = process.env.TOPIC_NAME

const num_partitions = process.env.NUM_PARTITIONS

const message = process.env.MESSAGE

var kafka = require('kafka-node'),

HighLevelProducer = kafka.HighLevelProducer,

client = new kafka.KafkaClient({kafkaHost: oehcs_connect_url}),

producer = new HighLevelProducer(client);

var i = 0;

while (i >= 0 ){

var payloads = [{ topic: topic_name, messages: message , partition: i}];

//producer.on('ready', function () {

producer.send(payloads, function (err, data) {

console.log(data);

});

// });

i = i + 1;

if (i > num_partitions -1){

i = 0;

sleep( 1 );

}

}

THE DOCKERFILE

FROM oraclelinux:7-slim
WORKDIR /app
ADD . /app
RUN curl --silent --location https://rpm.nodesource.com/setup_10.x | bash -
RUN yum -y install nodejs npm
CMD ["node","producer-direct.js"]

THE YAML FOR K8S DEPLOYMENT

apiVersion: apps/v1

kind: Deployment

metadata:

name: oehcsnodeproducer-direct

labels:

app: oehcsnodeproducer-direct

spec:

replicas: 1

selector:

matchLabels:

app: oehcsnodeproducer-direct

strategy:

type: Recreate

template:

metadata:

labels:

app: oehcsnodeproducer-direct

spec:

containers:

- image: javiermugueta/oehcsnodeproducer-direct

env:

- name: OEHCS_CONNECTURL

value: "<ip1>:6667,<ip2>:6667,..."

- name: TOPIC_NAME

value: "R1"

- name: NUM_PARTITIONS

value: "10"

- name: MESSAGE

value: "{'put here what you want'}"

name: oehcsnodeproducer-direct

TEST IT AND SEE WHAT HAPPENS

Create the deployment and after 10 minutes take a look to production messages ratio:
kubectl apply -f my.yaml
oehcs-scale1.png
More or less 400/second…
Scale the deployment and take a look to new production ratios:
kubectl scale deployment oehcsnodeproducer-direct --replicas=2
Around 8000 messages/second!
Now add 9 partitions to the topic and take a look to new ratios:
add partitions
With 2 pods running and 10 partitions we are producing around 10K messages per second! As you can see partitioning improves performance!
10partitions.png
Let’s double the number of pods and see new ratios:
kubectl scale deployment oehcsnodeproducer-direct --replicas=4
And now 18K/second!
18k
That’s all folks!
Enjoy 😉

Oracle IdCS Tips Part II: Simple Workflow for Creating Registered Users in IdCS with Node.js


In this post we explained how to create users in IdCS with the REST API. Typically you would like to put an approval process in between, here we explain a simple solution for those use cases where you don’t have or don’t want to put in the picture other pieces such as BPM, workflow or other typical engines.

STEP ONE AND ONLY

Create a Node.js gadget that sends an email to an approval email account with a message body that exposes an Accept and a Reject Button. The Accept button should call the create user procedure explained here.

Replace the text in bold with your own values and change the default buttons actions to a call to an exposed service that implements the create user procedure mentioned.

const nodemailer = require('nodemailer');

let transporter = nodemailer.createTransport({

host: 'estibijaif.oracol.com',

port: 465,

secure: 'estibijaif.oracol.com',

auth: {

user: 'xxxxxx@oracol.com',

pass: 'morefoolsthanbottles'

}

});

let message = {

from: 'MRO  <xxxxxx@oracol.com>',

to: 'Recipient <xxxxxx@oracol.com>',

subject: 'New user request',

text: 'Hello!',

html: '<head><style>.button {background-color: #4ecdc4;border-color: #45b7af;border-radius: 5px;text-align: center;padding: \

10px;}.button a {color: #ffffff;display: block;font-size: 14px;text-decoration: none;text-transform: uppercase;}</style> \

</head>A new user alextorrijo@acme.com from Acme has been requested, please accept or reject with the buttons as follows<table> \

<tr><td style="background-color: #4ecdc4;border-color: #4c5764;border: 2px solid #45b7af;padding: 10px;text-align: center;"> <a style="display: block;color: #ffffff;font-size: 12px;text-decoration: none;text-transform: uppercase;" href="https://javiermugueta.wordpress.com">Accept</a></td></tr><tr><td style="background-color: #4ecdc4;border-color: #4c5764;border: 2px solid #45b7af;padding: 10px;text-align: center;"><a style="display: block;color: #ffffff;font-size: 12px;text-decoration: none;text-transform: uppercase;" href="https://javiermugueta.wordpress.com">Reject</a></td></tr></table>'

};

transporter.sendMail(message, (err, info) => {

if (err) {

console.log('Error occurred. ' + err.message);

return process.exit(1);

}

console.log('Message sent: %s', info.messageId);

});
actionableemail
This Node.js procedure can be developed in Oracle Developer Cloud Service (DevCS) and deployed in Oracle Application Container Cloud Service (ACCS) easily.
See also this post
Enjoy 😉

 

Oracle IdCS Tips Part I: Create Users Programatically in Node.js for Oracle Cloud Services with the REST API in less than a Basketball Quarter Length


Oracle Cloud provides Identity Cloud Services (IdCS) as the identity provider (and more) for all the cloud services offered in the stack.

STEP ONE

Ask your identity administrator to create a trusted application in IdCS with the settings as shown in the following screenshots:

This slideshow requires JavaScript.

STEP TWO

Ask your IdCS administrator for the ClientID and secret values for the previously created application.

idcs4

STEP THREE

Test the following code changing the values in bold with your specific values:

// jmu, april 2018

var express = require('express');
var app = express();
var https = require('https');
var fs = require('fs');
// this data comes from your IdCS administrator
const client_id = "43tgh656uhdh67ur67ruth"
const secret = "4erte-b04e-49b3-be06-534gdfg"
const idcsHost = 'idcs-45a9gsdg7876eac2935dcbd62.identity.oraclecloud.com'
// the user you want to create
var userName = "alextorrijo";
var userMail = "alextorrijo@acme.com";;
var familyName = "torrijo";
var givenName = "alex"
//
var userJSONData = {
"schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
"userName": userName,
"name": {
"familyName": familyName,
"givenName": givenName
},
"emails": [{
"value": userMail,
"type": "work",
"primary": true
}]
};
var userData = JSON.stringify(userJSONData);
const tokenData = "grant_type=client_credentials&scope=urn:opc:idm:__myscopes__";
var token = ""
var credentials = Buffer.from(client_id + ":" + secret).toString('base64');
var token_options = {
host: idcsHost,
port: 443,
path: '/oauth2/v1/token',
method: 'POST',
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic "+ credentials,
"Accept": "application/json, text/plain, */*"
}
};
app.get('/', function (req, res) {
res.send('Hi!<br>/createUser is your choice!');
});
app.get('/createUser', function (req, res) {
var x = https.request(token_options,function(res){
res.on('data',function(data){
token = JSON.parse(data).access_token;
fs.appendFile('logfile.log', token + '\r\n', function(err){;});
var create_user_options = {
host: idcsHost,
port: 443,
path: '/admin/v1/Users',
method: 'POST',
headers: {
"Content-Type": "application/scim+json",
"Authorization": "Bearer "+ token,
"Accept": "application/json, text/plain, */*"
}
};
var y = https.request(create_user_options,function(res){
res.on('data',function(data){
fs.appendFile('logfile.log', data + '\r\n', function(err){;});
});
});
y.write(userData);
y.end();
});
});
x.write(tokenData);
x.end();
res.send('Usuario creado, mira <a href="https://idcs-sdfgwrgsfsdfgsdfg.identity.oraclecloud.com/ui/v1/adminconsole?root=users" target="_blank"> aqui </a>');
});
app.listen(3456, function () {
console.log('Example app listening on port 3456!');
});
Run the file:
node idcscreateuser.js

Open a browser:

http://localhost:3456

Execute the createUser method:

http://localhost:3456/createUser

FINALY

Verify the user was created successfully.
idcs5

MORE INFO

Enjoy -)

node-oracledb: Connect Node program to Oracle Database Cloud Service in 30 minutes


If you want to execute sequel code against ORCL DB from Node your approach is node-oracledb. To get started follow setup instructions here.

Follow the steps I made to get it running in my new Mac here but documentation explains how to do it for a bunch of platforms.

NOTE: You need an oracle client, in my case I installed instant client. Steps are included in the mentioned doco.

Download the  zip or git clone this repo: [ https://github.com/oracle/node-oracledb.git ]

Ask for or grab your database connections details from the DBCS MyServices portal, then open examples directory with the latest trendy editor and edit dbconfig.js to point to your DBCS instance for example (settings are ficticious):

module.exports = {
 user : process.env.NODE_ORACLEDB_USER || "scott",
 password : process.env.NODE_ORACLEDB_PASSWORD || "tiger",
 connectString : process.env.NODE_ORACLEDB_CONNECTIONSTRING || "329.944.719.908/PDB1.contoso.oraclecloud.internal",
 externalAuth : process.env.NODE_ORACLEDB_EXTERNALAUTH ? true : false
};

Now you can test a couple of examples immediately:

MacBook-Pro-de-javier:examples javiermugueta$ node connect.js 

Connection was successful!

MacBook-Pro-de-javier:examples javiermugueta$ node select1.js 

[ { name: 'DEPARTMENT_ID' }, { name: 'DEPARTMENT_NAME' } ]

[ [ 180, 'Construction' ] ]

That’s all Folks!

Enjoy 😉