Getting Users SessionID from Okta Sign-in Wudget - javascript

So I'm using the Okta Sign-In Widget to authenticated users for my internal WebApp.
However, I'm struggling how I get the sessionID from the created session stored in a cookie from my domain or posted back in a response to then be saved, so it can be then used later to carry out actions on that users session (for instance logout). My JavaScript ability is terrible but I'm trying to learn here. Please see below my code for the login page. If someone could help me how I can as a response from the login get the sessionID to then be used, it would be greatly appreciated.
<!DOCTYPE html>
<html>
<head>
<?php echo $MetaData['charset']."\n";?>
<?php echo $MetaData['viewport']."\n";?>
<?php echo $MetaData['description']."\n";?>
<?php echo $MetaData['author']."\n";?>
<?php echo $MetaData['title']."\n";?>
<link rel="shortcut icon" href="">
<script src="https://ok1static.oktacdn.com/assets/js/sdk/okta-signin-widget/1.7.0/js/okta-sign-in.min.js" type="text/javascript"></script>
<link href="https://ok1static.oktacdn.com/assets/js/sdk/okta-signin-widget/1.7.0/css/okta-sign-in.min.css" type="text/css" rel="stylesheet">
<link href="https://ok1static.oktacdn.com/assets/js/sdk/okta-signin-widget/1.7.0/css/okta-theme.css" type="text/css" rel="stylesheet">
<link href="<?php echo base_url().'assets/css/custom.css' ?>"type="text/css" rel="stylesheet">
</head>
<body style="background-color:#f5f5f5;">
<div id="okta-login-container"></div>
<script type="text/javascript">
var orgUrl = '<?php echo $OktaInstanceConfig['OktaInstanceURL'];?>';
var redirectUrl = '<?php echo base_url().'index.php/Dashboard' ?>';
var oktaSignIn = new OktaSignIn({
baseUrl: orgUrl,
logo: '<?php echo base_url()."assets/images/".$CompanyConfig["CompanyName"]."/logo.svg"?>',
authParams: {
responseType: 'id_token',
responseMode: 'okta_post_message',
scope: [
'openid',
'email',
'profile',
'address',
'phone',
'groups'
]
}
});
oktaSignIn.renderEl(
{ el: '#okta-login-container' },
function (res) {
if (res.status === 'SUCCESS')
{
console.log('User %s successfully authenticated %o', res.user.profile.login, res.user);
res.session.setCookieAndRedirect(redirectUrl);
}
}
);
</script>
</body>
</html>

Okta sets the user session after the method setCookieAndRedirect(redirectUrl) is called.
The logic inside of your redirectUrl (index.php) can get the sessionId by retrieving the current session using the Sign-In Widget:
<!-- index.php -->
<!DOCTYPE html>
<html>
<head> <!-- scripts and stylesheets --> </head>
<body>
<script type="text/javascript">
var oktaSignIn = new OktaSignIn({ /* config */});
oktaSignIn.session.exists(function (exists) {
if (exists) {
// Session exists
oktaSignIn.session.get(function (sessionInfo) {
// sessionInfo.id
}, function(err) { // error retrieving session })
return;
} else { console.log("No session");
}
});
</script>
</body>
</html>

Related

Stripe: Meta Data from HTML to Checkout-Sessions PHP

I use the samples (https://github.com/stripe-samples/checkout-single-subscription/tree/master/server/php) from Stripe to create a subscription. What I don't really understand, how can I pass metadata from my index.html over script.js to the create-checkout-session.php.
I thought I just add data attributes to the index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Stripe</title>
<meta name="description" content="A demo of Stripe Payment Intents" />
<link rel="icon" href="favicon.ico" type="image/x-icon" />
<script src="https://js.stripe.com/v3/"></script>
<script src="./script.js" defer></script>
</head>
<body>
<div class="sr-root">
<div class="sr-main" style="display: flex;">
<div class="sr-container">
<section class="container">
<button id="basic-plan-btn" data-partner="name" data-package="basic">USD 6.90</button>
</section>
<section class="container">
<button id="pro-plan-btn" data-partner="name" data-package="premium">USD 11.90</button>
</section>
</div>
</div>
</div>
</body>
</html>
then I have to read them somehow out in the script.js. But that I don't really figure out how.
// Create a Checkout Session with the selected plan ID
var createCheckoutSession = function(priceId) {
return fetch("/fileadmin/restaurant/stripe/create-checkout-session.php", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
priceId: priceId,
partner: 'name',
package: 'premium'
})
}).then(function(result) {
return result.json();
});
};
// Handle any errors returned from Checkout
var handleResult = function(result) {
if (result.error) {
var displayError = document.getElementById("error-message");
displayError.textContent = result.error.message;
}
};
/* Get your Stripe publishable key to initialize Stripe.js */
fetch("/fileadmin/restaurant/stripe/config.php")
.then(function(result) {
return result.json();
})
.then(function(json) {
var publishableKey = json.publishableKey;
var basicPriceId = json.basicPrice;
var proPriceId = json.proPrice;
var stripe = Stripe(publishableKey);
// Setup event handler to create a Checkout Session when button is clicked
document
.getElementById("basic-plan-btn")
.addEventListener("click", function(evt) {
createCheckoutSession(basicPriceId).then(function(data) {
// Call Stripe.js method to redirect to the new Checkout page
stripe
.redirectToCheckout({
sessionId: data.sessionId
})
.then(handleResult);
});
});
// Setup event handler to create a Checkout Session when button is clicked
document
.getElementById("pro-plan-btn")
.addEventListener("click", function(evt) {
createCheckoutSession(proPriceId).then(function(data) {
// Call Stripe.js method to redirect to the new Checkout page
stripe
.redirectToCheckout({
sessionId: data.sessionId
})
.then(handleResult);
});
});
});
by that I receive them in the create-checkout-session.php
<?php
require_once 'shared.php';
$domain_url = $config['domain'];
$checkout_session = \Stripe\Checkout\Session::create([
'success_url' => $domain_url . 'success.php?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => $domain_url . 'canceled.php',
'payment_method_types' => ['card'],
'mode' => 'subscription',
'allow_promotion_codes' => true,
'line_items' => [[
'price' => $body->priceId,
'quantity' => 1,
]],
'subscription_data' => ['trial_period_days' => 60],
'metadata' => [
'partner' => $body->partner,
'package' => $body->package
],
]);
echo json_encode(['sessionId' => $checkout_session['id']]);
Thank You.
What you've done adding to the JSON body of the fetch call looks right to me. If you're trying to set the 'name' and 'premium' values dynamically from some input, then take a look at this previous answer for some approaches for getting input values.

Linkedin login with js

I am trying to implement login with linked in my web app. Here is my code..
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: 'key here'
</script>
</head>
<body>
<script>
IN.User.authorize(function (e) {
console.log(e);
}, function (e) {
console.log(e);
});
</script>
</body>
But its giving me error 'Cannot read property 'then' of undefined at Object.authorize (in.js:18)'
i have also tried this way..
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: 'key here'
onLoad: 'onLinkedInLoad'
authorize: true
</script>
</head>
<body>
<!-- LinkedIn signin button -->
<script type="in/Login"></script>
<script type="text/javascript">
// Setup an event listener to make an API call once auth is complete
function onLinkedInLoad() {
IN.Event.on(IN, "auth", getProfileData);
}
</script>
</body>
but its giving me errror
'in.js:7 Uncaught (in promise) TypeError: Could not instantiate tag for 'login': Cannot read property 'on' of null
at new (Login.js?version=0.1.149:7)
at in.js:18'
The documentation and examples for linkedIn show api_key and onLoad function not being set as a string delimeter.
api_key: 0192afsdj10
onLoad: onLinkedInLoad
Secondly, you have not added in a function for the getProfileData function.
Here is an example of the should look like.
function getProfileData() {
IN.API.Profile("me").fields("id", "first-name", "last-name", "headline", "location", "picture-url", "public-profile-url", "email-address").result(displayProfileData);
}
function displayProfileData(profiles){
var member = profiles.values[0];
console.log(member);
}
See code referenced here

how to disable Cache in a REST Tree in DOJO with a complete code to reproduce it

The following code shows a tree in Dojo using dojox.data.JsonRestStore with one node named Changing0 with children to be lazy loaded. the problem is in updating the tree by renaming the one node (Changing1, Changing2,...) without changing its reference number or id.
The question is the following: if it is a caching problem, how to disable caching.
Please note that on the log file we can see that the REST is functioning well but the name is unchanged on the tree. Even if we use refresh2() instead of refresh1() by deleting the whole tree and its data and recreating it. Maybe it is the $ref that is kept in javascript referencing since we do not change the id.
the code is the following:
reproducing_problem.php:
<?php
if(!isset($_SESSION))
{
session_start();
}
$_SESSION['keyA']=0;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Reproducing Cache Problem</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!--META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE"-->
<script type="text/javascript" src="../external/dojo/dojo.js" djConfig="parseOnLoad: true"></script>
<script type="text/javascript">
dojo.require('dojox.data.JsonRestStore');
dojo.require('dijit.Tree');
dojo.require("dijit.form.Button");
var prod= {
store: null,
model: null,
tree: null,
init: function() {
this.store = new dojox.data.JsonRestStore({
target: 'reproducing-REST.php',
labelAttribute: "name"
});
this.model = new dijit.tree.ForestStoreModel({
store: this.store,
deferItemLoadingUntilExpand: true,
rootId: "products",
rootLabel: "Products",
query: {queryOptions:{cache:false}},
childrenAttrs: ['children']
});
}
};
function refresh1() {
tree=prod.tree
tree._itemNodesMap = {};
tree.rootNode.state = "UNCHECKED";
tree.model.root.children = null;
if (tree.rootNode) {
tree.rootNode.destroyRecursive();
}
tree._load();
}
function refresh2() {
delete prod.tree;
delete prod.model;
delete prod.store;
dijit.byId('products_tree').destroy(true);
prod.init();
prod.tree = new dijit.Tree({
model: prod.model,
query: {queryOptions:{preventCache:true}},
persist: false
}, 'products_tree');
prod.tree.startup();
}
dojo.addOnLoad(function() {
prod.init();
//prod.store.fetch({queryOptions:{cache:false}});
prod.tree = new dijit.Tree({
model: prod.model,
//query: {queryOptions:{cache:false}},
persist: false
}, 'products_tree');
prod.tree.startup();
});
</script>
<style type="text/css">
#import "../external/dijit/themes/soria/soria.css";
#import "../external/dojo/resources/dojo.css";
</style>
</head>
<body class="soria">
<div dojoType="dijit.form.Button">
Change name and refresh
<script type="dojo/event" event="onClick">
refresh1();
</script>
</div>
<div id="products_tree"></div>
<div id="notes">notes</div>
</body>
</html>
reproducing-REST.php:
<?php
if(!isset($_SESSION))
{
session_start();
}
$keyA=$_SESSION['keyA'];
$_SESSION['keyA']=$keyA+1;
if (array_key_exists('PATH_INFO', $_SERVER)) {
$arr = null;
$resource = $_SERVER['PATH_INFO'];
$method = $_SERVER['REQUEST_METHOD'];
error_log(" resource: ".$resource." \n",3,"mylogfile.txt");
if ($method == 'GET') {
if ($resource=='/'){
$arr=array();
$sameref='1234';
$name="Changing".$keyA;
error_log(" name: ".$name." \n",3,"mylogfile.txt");
array_push($arr,array('$ref' => $sameref, 'name' => $name, 'children' => true));
}
else{
$aProduct = ltrim($resource, '/');
$arr=array();
$name="exploding";
$child='2345';
array_push($arr,array('name' => $name,'idq' => $child));
$arr=array('idp' => $aProduct, 'name' => $name, 'children' => $arr);
}
$status = 'HTTP/1.1 200 OK';
}
header($status);
echo json_encode($arr);
}
?>
thank you

JavaScript function is undefined although it's loaded

I'm doing my homework for a JS course and I face a strange problem. I've made a request 'module' that I'm at the very beginning right after jquery then I'm loading the essential js scripts but when I try to use a function from the request module in another script file it always throws a TypeError undefined. The strange is that when I console.log the object it is' not undefined and everything is all right. I can't seem to figure it out why this is happening ... and I need some guideline
Here is part of the code:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SeenIt</title>
<link rel="stylesheet" href="style/site.css">
<link rel="stylesheet" href="style/post.css">
<link rel="stylesheet" href="style/header.css">
<link rel="stylesheet" href="style/menu.css">
<link rel="stylesheet" href="style/notifications.css">
<link rel="stylesheet" href="style/submit.css">
<link rel="stylesheet" href="style/comments.css">
<script src="../node_modules/jquery/dist/jquery.min.js"></script>
<script src="./scripts/request.js"></script>
<script src="../node_modules/handlebars/dist/handlebars.min.js"></script>
<script src="./scripts/pageView.js"></script>
<script src="./scripts/app.js"></script>
</head>
<body>
<div id="container">
</div>
</body>
</html>
My JS Request Module
let request = (function (){
const appKey = 'kid_rkR4UTRnb';
const appSecret = 'd3e9f15502a740fcb1413d7ffe109ab5';
const baseUrl = 'https://baas.kinvey.com';
function createAuth(type)
{
let authorize = {"Content-Type": "application/json"};
if(type === 'basic')
{
authorize.Authorization = "Basic " + btoa(appKey + ':' + appSecret);
}
else if(type === 'kinvey')
{
authorize.Authorization = "Kinvey " + localStorage.getItem('authtoken');
}
return authorize;
}
function makeRequest(destination, endpoint, method, authorization, data)
{
let req = {
url: baseUrl + '/' + destination + '/' + endpoint,
method: method,
headers: createAuth(authorization),
};
if(data != undefined) req.data = JSON.stringify(data);
$.ajax(req);
}
function register(username, password)
{
let data = {
"username": username,
"password": password
};
return makeRequest('user', appKey, 'POST', 'basic', data);
}
function logIn(username, password)
{
let data = {
"username": username,
"password": password
};
return makeRequest('user', appKey + '/login', 'POST', 'basic', data);
}
function logout()
{
makeRequest('user', appKey + '/_logout', 'POST', 'kinvey');
}
return {
createAuth,
register,
logIn,
logout
}
})();
Main JS App file
$(() => {
let main = $('#container');
initialState();
$(document).ajaxStart(() => $('#loadingBox').show());
$(document).ajaxComplete(() => $('#loadingBox').hide());
$('#infoBox').click(() => $('#infoBox').hide());
$('#errorBox').click(() => $('#errorBox').hide());
$(document).on('submit', '#loginForm', login);
async function viewPage(page)
{
if(page == 'home')
{
main.html(await loadWelcome(isLoggedIn()));
}
}
// initial functions
function initialState()
{
viewPage('home');
}
///////////////
// session control
function login(e)
{
e.preventDefault();
let loginForm = $(this);
let name = loginForm.find('input[name="username"]').val();
let password = loginForm.find('input[name="password"]').val();
request.logIn(name, password) // TYPEERROR UNDEFINED ?!?
.then(data => {
request.saveSession(data);
this.reset();
viewPage('home');
})
}
});
It crashes when you try to invoke the then() method because the request.logIn() function returns undefined instead of a promise. This can be traced to the makeRequest() function which doesn't return anything, i.e. undefined.
Your last line in the makeRequest() function needs to be:
return $.ajax(req);
Please try return object on JS Request Module like this,
return {
createAuth: createAuth,
register: register,
logIn: logIn,
logout: logout
}
You can try <script> attributes for the correct loading scripts:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SeenIt</title>
<link rel="stylesheet" href="style/site.css">
<link rel="stylesheet" href="style/post.css">
<link rel="stylesheet" href="style/header.css">
<link rel="stylesheet" href="style/menu.css">
<link rel="stylesheet" href="style/notifications.css">
<link rel="stylesheet" href="style/submit.css">
<link rel="stylesheet" href="style/comments.css">
<script src="../node_modules/jquery/dist/jquery.min.js"></script>
<script src="../node_modules/handlebars/dist/handlebars.min.js"></script>
<script defer src="./scripts/request.js"></script>
<script defer src="./scripts/pageView.js"></script>
<script defer src="./scripts/app.js"></script>
</head>
<body>
<div id="container">
</div>
</body>
</html>
in your code, function makeRequest doesn't return any value, so it will return undefined. try returning the value from the makeRequest function.

Error in browserbox javascript email code?

I tried using emailjs browserbox to connect to an imap server but the sample script with the correct port and host and username and password just throws out errors and doesn't work in a client-side html file?
https://github.com/whiteout-io/browserbox is a link to the api. What's wrong with how I wrote the code?
<html>
<head>
<title>Test</title>
<!-- Required for non-Unicode encodings -->
<script src="encoding-indexes.js"></script>
<script src="encoding.js"></script>
<script src="stringencoding.min.js"></script>
<script src="browserbox.js"></script>
<script src="browserbox-imap.js"></script>
<script> var client = new BrowserBox('host', port, {
auth: {
user: 'testuser',
pass: 'testpass'
},
id: {
name: 'My Client',
version: '0.1'
} });
</script>
</head>
<body>
</body>
</html>

Categories