I am currently attempting to deploy an app that uses ionic + okta. I actually started with the ionic + okta template which can be found here: https://github.com/oktadeveloper/okta-ionic-auth-example
import { Component, ViewChild } from '#angular/core';
import { IonicPage, NavController } from 'ionic-angular';
import { JwksValidationHandler, OAuthService } from 'angular-oauth2-oidc';
import * as OktaAuth from '#okta/okta-auth-js';
import { TabsPage } from '../tabs/tabs';
declare const window: any;
#IonicPage()
#Component({
selector: 'page-login',
templateUrl: 'login.html'
})
export class LoginPage {
#ViewChild('email') email: any;
private username: string;
private password: string;
private error: string;
constructor(public navCtrl: NavController, private oauthService: OAuthService) {
oauthService.redirectUri = 'http://localhost:8100';
oauthService.clientId = '0oabqsotq17CoayEm0h7';
oauthService.scope = 'openid profile email';
oauthService.issuer = 'https://dev-158606.oktapreview.com/oauth2/default';
oauthService.tokenValidationHandler = new JwksValidationHandler();
// Load Discovery Document and then try to login the user
this.oauthService.loadDiscoveryDocument().then(() => {
this.oauthService.tryLogin();
});
}
ionViewDidLoad(): void {
setTimeout(() => {
this.email.setFocus();
}, 500);
}
login(): void {
this.oauthService.createAndSaveNonce().then(nonce => {
const authClient = new OktaAuth({
clientId: this.oauthService.clientId,
redirectUri: this.oauthService.redirectUri,
url: 'https://dev-158606.oktapreview.com',
issuer: 'default'
});
return authClient.signIn({
username: this.username,
password: this.password
}).then((response) => {
if (response.status === 'SUCCESS') {
return authClient.token.getWithoutPrompt({
nonce: nonce,
responseType: ['id_token', 'token'],
sessionToken: response.sessionToken,
scopes: this.oauthService.scope.split(' ')
})
.then((tokens) => {
const idToken = tokens[0].idToken;
const accessToken = tokens[1].accessToken;
const keyValuePair = `#id_token=${encodeURIComponent(idToken)}&access_token=${encodeURIComponent(accessToken)}`;
this.oauthService.tryLogin({
customHashFragment: keyValuePair,
disableOAuth2StateCheck: true
});
this.navCtrl.push(TabsPage);
});
} else {
throw new Error('We cannot handle the ' + response.status + ' status');
}
}).fail((error) => {
console.error(error);
this.error = error.message;
});
});
}
redirectLogin() {
this.oktaLogin().then(success => {
const idToken = success.id_token;
const accessToken = success.access_token;
const keyValuePair = `#id_token=${encodeURIComponent(idToken)}&access_token=${encodeURIComponent(accessToken)}`;
this.oauthService.tryLogin({
customHashFragment: keyValuePair,
disableOAuth2StateCheck: true
});
this.navCtrl.push(TabsPage);
}, (error) => {
this.error = error;
});
}
oktaLogin(): Promise<any> {
return this.oauthService.createAndSaveNonce().then(nonce => {
let state: string = Math.floor(Math.random() * 1000000000).toString();
if (window.crypto) {
const array = new Uint32Array(1);
window.crypto.getRandomValues(array);
state = array.join().toString();
}
return new Promise((resolve, reject) => {
const oauthUrl = this.buildOAuthUrl(state, nonce);
const browser = window.cordova.InAppBrowser.open(oauthUrl, '_blank',
'location=no,clearsessioncache=yes,clearcache=yes');
browser.addEventListener('loadstart', (event) => {
if ((event.url).indexOf('http://localhost:8100') === 0) {
browser.removeEventListener('exit', () => {});
browser.close();
const responseParameters = ((event.url).split('#')[1]).split('&');
const parsedResponse = {};
for (let i = 0; i < responseParameters.length; i++) {
parsedResponse[responseParameters[i].split('=')[0]] =
responseParameters[i].split('=')[1];
}
const defaultError = 'Problem authenticating with Okta';
if (parsedResponse['state'] !== state) {
reject(defaultError);
} else if (parsedResponse['access_token'] !== undefined &&
parsedResponse['access_token'] !== null) {
resolve(parsedResponse);
} else {
reject(defaultError);
}
}
});
browser.addEventListener('exit', function (event) {
reject('The Okta sign in flow was canceled');
});
});
});
}
buildOAuthUrl(state, nonce): string {
return this.oauthService.issuer + '/v1/authorize?' +
'client_id=' + this.oauthService.clientId + '&' +
'redirect_uri=' + this.oauthService.redirectUri + '&' +
'response_type=id_token%20token&' +
'scope=' + encodeURI(this.oauthService.scope) + '&' +
'state=' + state + '&nonce=' + nonce;
}
}
I can build the app using ionic cordova build ios and load it into xcode. It is properly signed and loads on my phone. I can click through to the okta login page, but when I attempt to log in, I get redirected back to the login page, and get the following errors in xcode:
API error: returned 0 width
nw_socket_connect connectx SAE_ASSOCID_ANY 0, Null, 0, Null, failed
connectx failed
TIC TCP Conn Failed Err(61)
NSURLConnection finished with error - code 1004
webView:didFailLoadWithError - -1004: Could not connect to the server
ERROR: ERROR Error: Uncaught (in promise): Error: Parameter jwks expected!
ValidateSignature#http://localhost...
ProcessIdToken#http://localhost...
...
I didn't modify the login code other than to use setRoot vs push for the successful redirect. The app works when I run it in browser or the ionic lab. I noticed that the source code uses localhost as an event url. I assume that's the address of the cordova browser - does this need to change?
I feel like it's a setting in xcode. I am trying to build for iOS9 with xcode10.
Related
I am using Capacitor v3, NextJS static export, and a Django backend to build out an iOS app based on a production website.
The current backend authentication scheme uses Django sessions via cookies as well as setting the CSRF token via cookies. The CSRF token can be bypassed pretty easily for the app and not worried about disabling that but forking our authentication scheme would be somewhat of a hassle. The capacitor-community/http claims to allow Cookies but I haven't been able to configure that correctly.
Capacitor Config:
import { CapacitorConfig } from '#capacitor/cli';
const config: CapacitorConfig = {
appId: 'com.nextwebapp.app',
appName: 'nextwebapp',
webDir: 'out',
bundledWebRuntime: false
};
export default config;
Note that I have tried setting server.hostname to myapp.com as well.
Based on the comments at the bottom of the capacitor http readme I set the following Info.plist values.
App/Info.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
....
<key>WKAppBoundDomains</key>
<array>
<string>staging.myapp.com</string>
<string>myapp.com</string>
</array>
</dict>
</plist>
The web app uses a react hooks wrapper package for axios so in order to keep changes minimal I made a hook that mimics the state returned from that package.
hooks/useNativeRequest.ts
import { useEffect, useState } from "react";
import { Http } from "#capacitor-community/http";
import {
BASE_URL,
DEFAULT_HEADERS,
HOST_NAME,
ERROR_MESSAGE,
Refetch,
RequestOptions,
ResponseValues,
RequestConfig,
} from "#utils/http";
import { handleResponseToast } from "#utils/toast";
const makeUrl = (url): string => `${BASE_URL}${url}`;
const getCSRFToken = async () =>
await Http.getCookie({ key: "csrftoken", url: HOST_NAME });
const combineHeaders = async (headers: any) => {
const newHeaders = Object.assign(DEFAULT_HEADERS, headers);
const csrfHeader = await getCSRFToken();
if (csrfHeader.value) {
newHeaders["X-CSRFToken"] = csrfHeader.value;
}
return newHeaders;
};
function useNativeRequest<T>(
config?: RequestConfig,
options?: RequestOptions
): [ResponseValues<T>, Refetch<T>] {
const [responseState, setResponseState] = useState({
data: null,
error: null,
loading: false,
});
let method = "get";
let url = config;
let headers = {};
let params = undefined;
let data = undefined;
if (config && typeof config !== "string") {
url = config.url;
method = config.method?.toLowerCase() ?? method;
headers = config.headers;
params = config.params;
data = config.data;
}
const requestMethod = Http[method];
const makeRequest = async () => {
setResponseState({ error: null, data: null, loading: true });
try {
const reqHeaders = await combineHeaders(headers);
console.log({
url,
reqHeaders,
params,
data
})
const response = await requestMethod({
url: makeUrl(url),
headers: reqHeaders,
params,
data,
});
if (response?.status === 200) {
setResponseState({ error: null, data: response.data, loading: false });
handleResponseToast(response?.data?.detail);
} else {
const errorMessage = response?.data?.detail || ERROR_MESSAGE;
handleResponseToast(errorMessage);
setResponseState({
error: errorMessage,
data: response.data,
loading: false,
});
}
return response;
} catch {
setResponseState({
error: ERROR_MESSAGE,
data: null,
loading: false,
});
return Promise.reject(ERROR_MESSAGE);
}
};
useEffect(() => {
if (!options?.manual) {
makeRequest();
}
}, [options?.manual]);
return [responseState, makeRequest];
}
export { useNativeRequest };
The console.log above never includes the additional csrf cookie and in the getter logs it doesn't contain a value.
Backend Django
MIDDLEWARE = [
...
'myapp_webapp.middle.CustomCSRFMiddleWare',
]
CORS_ALLOWED_ORIGINS = [
...
"capacitor://localhost",
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
}
middleware
class CustomCSRFMiddleWare(CsrfViewMiddleware):
def process_request(self, request):
# Special Processing for API Requests
if "/api/v1" in request.path:
try:
requested_with = request.headers['X-Requested-With']
myapp_request = request.headers['X-Myapp-Request']
# Check Custom Headers
if not (requested_with == 'XMLHttpRequest' and myapp_request == '1'):
raise PermissionDenied()
return None
except KeyError:
# All API Requests should include the above headers
raise PermissionDenied()
# Call original CSRF Middleware
return super(CustomCSRFMiddleWare, self).process_request(request)
Occasionally the backend will also show that X-Requested-With is not being sent but it is included in the DEFAULT_HEADERS constant I have in the UI and appears in the console.log.
Is anything above preventing me from being able to read and send cookies from Capacitor on iOS? Does Cookie based authentication even work with capacitor?
Here is my updated react hook that combine's my above question and thread mentioned in the comments as well as some manual cookie setting.
The below client side code worked without changes to existing Django Session authentication.
The changes from my code above
Added credentials: "include" to webFetchExtra
Added "Content-Type": "application/json" to headers
Handle override of the initial config for manual request & refetch
Set Session Cookie After Response
Based on the docs this shouldn't be necessary but I am keeping in my code for now.
import { useCallback, useEffect, useState } from "react";
import { AxiosRequestConfig } from "axios";
import { Http } from "#capacitor-community/http";
const DEFAULT_HEADERS = {
"X-Requested-With": "XMLHttpRequest",
"X-MyApp-Request": "1",
"Content-Type": "application/json",
};
const makeUrl = (url): string => `${BASE_URL}${url}`;
const getCSRFToken = async () =>
await Http.getCookie({ key: "csrftoken", url: HOST_NAME });
const setSessionCookie = async () => {
const sessionId = await Http.getCookie({ key: "sessionid", url: HOST_NAME });
if (sessionId.value) {
await Http.setCookie({
key: "sessionid",
value: sessionId.value,
url: HOST_NAME,
});
}
};
const combineHeaders = async (headers: any) => {
const newHeaders = Object.assign(DEFAULT_HEADERS, headers);
const csrfHeader = await getCSRFToken();
if (csrfHeader.value) {
newHeaders["X-CSRFToken"] = csrfHeader.value;
}
return newHeaders;
};
const parseConfig = (config: RequestConfig, configOverride?: RequestConfig) => {
let method = "get";
let url = config;
let headers = {};
let params = undefined;
let data = undefined;
if (config && typeof config !== "string") {
url = config.url;
method = config.method ?? method;
headers = config.headers;
params = config.params;
data = config.data;
}
return {
url,
method,
headers,
params,
data,
...(configOverride as AxiosRequestConfig),
};
};
function useNativeRequest<T>(
config?: RequestConfig,
options?: RequestOptions
): [ResponseValues<T>, Refetch<T>] {
const [responseState, setResponseState] = useState({
data: null,
error: null,
loading: false,
});
const makeRequest = useCallback(
async (configOverride) => {
setResponseState({ error: null, data: null, loading: true });
const { url, method, headers, params, data } = parseConfig(
config,
configOverride
);
try {
const reqHeaders = await combineHeaders(headers);
const response = await Http.request({
url: makeUrl(url),
headers: reqHeaders,
method,
params,
data,
webFetchExtra: {
credentials: "include",
},
});
if (response?.status === 200) {
setResponseState({
error: null,
data: response.data,
loading: false,
});
await setSessionCookie();
} else {
setResponseState({
error: errorMessage,
data: response.data,
loading: false,
});
}
return response;
} catch {
setResponseState({
error: ERROR_MESSAGE,
data: null,
loading: false,
});
return Promise.reject(ERROR_MESSAGE);
}
},
[config]
);
useEffect(() => {
if (!options?.manual) {
makeRequest(config);
}
}, [options?.manual]);
return [responseState, makeRequest];
}
export { useNativeRequest };
I am currently building a microservice that is responsible to communicate with Microsoft Graph, I have already made one with Loopback 3 and this was not a problem.
Except now, I am trying to do the same thing but with Loopback 4, but since the language changes from JavaScript to TypeScript I don't know if it's still possible to achieve this.
This was the code I used for Loopback 3 in my root server file:
'use strict';
const express = require('express');
const erouter = require('express').Router();
var session = require('express-session');
var passport = require('passport');
var OIDCStrategy = require('passport-azure-ad').OIDCStrategy;
const request = require('request');
var querystring = require('querystring');
const graph = require('./graph.service');
const getBookings = require('./getBookings.service');
const cors = require('cors');
var compression = require('compression');
module.exports = function(server) {
// Install a `/` route that returns server status
var router = server.loopback.Router();
router.get('/', server.loopback.status());
// Configure simple-oauth2
const oauth2 = require('simple-oauth2').create({
client: {
id: process.env.OAUTH_APP_ID,
secret: process.env.OAUTH_APP_PASSWORD
},
auth: {
tokenHost: process.env.OAUTH_AUTHORITY,
authorizePath: process.env.OAUTH_AUTHORIZE_ENDPOINT,
tokenPath: process.env.OAUTH_TOKEN_ENDPOINT
}
});
passport.serializeUser(function(user, done) {
var MSUser = server.models.MSUser;
var id = user.profile.oid;
MSUser.find({ where: { oid: id } }, function(err, msu) {
if (err) return done(err, null);
if (!msu) {
MSUser.create(user);
} else {
done(null, id);
}
});
});
passport.deserializeUser(function(id, done) {
var MSUser = server.models.MSUser;
MSUser.findById(id, function(err, user) {
if (err) return next(err);
done(null, user);
});
});
async function signInComplete(iss, sub, profile, accessToken, refreshToken, params, done) {
if (!profile.oid) {
return done(new Error("No OID found in user profile."), null);
}
try {
const user = await graph.getUserDetails(accessToken);
if (user) {
profile['email'] = user.mail ? user.mail.toLowerCase() : user.userPrincipalName.toLowerCase();
}
} catch (err) {
done(err, null);
}
let oauthToken = oauth2.accessToken.create(params);
var AuthUser = server.models.AuthUser;
var user = {};
AuthUser.find({ where: { email: profile['email'] } }, function(err, au) {
if (err) return done(err, null);
if (au.length != 1) return done(new Error("User was not found with that email address."), null);
user = au[0];
const dataMsAuth = querystring.stringify({
"created": new Date().toDateString(),
"token_type": oauthToken.token.token_type,
"expires_in": oauthToken.token.expires_in,
"access_token": oauthToken.token.access_token,
"scope": oauthToken.token.scope,
"ext_expires_in": oauthToken.token.ext_expires_in,
"refresh_token": oauthToken.token.refresh_token,
"id_token": oauthToken.token.id_token,
"expires_at": new Date(oauthToken.token.expires_at).toDateString()
});
const postMSAuth = {
url: process.env.API_URL + "api/Companies/" + user.companyId + "/msauth",
method: 'POST',
body: dataMsAuth,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
request(postMSAuth, function(err, resp, body) {
if (err) return done(err, null);
var MSUser = server.models.MSUser;
var id = profile.oid;
var msuser = { profile, oauthToken, oid: id, email: profile.email }
MSUser.findById(id, function(err, msu) {
if (err) return done(err, null);
if (!msu) {
MSUser.create(msuser);
}
});
return done(null, msuser);
});
});
}
passport.use(new OIDCStrategy({
identityMetadata: `${process.env.OAUTH_AUTHORITY}${process.env.OAUTH_ID_METADATA}`,
clientID: process.env.OAUTH_APP_ID,
responseType: 'code id_token',
responseMode: 'form_post',
redirectUrl: process.env.OAUTH_REDIRECT_URI,
allowHttpForRedirectUrl: true,
clientSecret: process.env.OAUTH_APP_PASSWORD,
validateIssuer: false,
passReqToCallback: false,
scope: process.env.OAUTH_SCOPES.split(' ')
},
signInComplete
));
var app = express();
app.use(compression());
app.use(session({
secret: process.env.BOOKINGS_LOOPBACK_SECRET,
resave: false,
saveUninitialized: false,
unset: 'destroy'
}));
app.use("/result", express.static('client'));
app.use(passport.initialize());
app.use(passport.session());
app.use(cors({
origin: '*'
}));
erouter.get('/API/bookings/:companyid', getBookings());
erouter.get('/auth/signin',
function(req, res, next) {
passport.authenticate('azuread-openidconnect', {
response: res,
prompt: 'login',
state: req.query.state,
failureRedirect: process.env.WEBSITE_URL + 'settings?error=incorrect_request',
successRedirect: process.env.WEBSITE_URL + 'settings?auth=success'
})(req, res, next);
}
);
erouter.post('/auth/callback',
function(req, res, next) {
passport.authenticate('azuread-openidconnect', {
response: res,
failureRedirect: process.env.WEBSITE_URL + 'settings?error=permission_denied',
successRedirect: process.env.WEBSITE_URL + 'settings?auth=success'
})(req, res, next);
}
);
app.use(erouter);
server.use(app);
server.use(router);
};
So my question is: "Is it possible to implement Microsoft Graph API in TypeScript using Loopback 4 or should I keep using Loopback 3 In JavaScript?"
Thanks in advance,
Billy Cottrell
SDK Version: 39.0.0
Platforms(Android/iOS/web/all): All
I am not getting accept or decline notifications permissions alert when loading my app in production.
I have tried clearing certificates and keys and allowing expo to add everything from a clean slate, but still no luck. I am starting to think maybe it’s my code which is the reason why the alert doesn’t get fired.
import Constants from "expo-constants";
import * as Notifications from "expo-notifications";
import { Permissions } from "expo-permissions";
import { Notifications as Notifications2 } from "expo";
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: true,
shouldSetBadge: false
})
});
export default class LoginScreen extends React.Component {
state = {
email: "",
password: "",
notification: {},
errorMessage: null
};
async componentDidMount() {
this.registerForPushNotificationsAsync();
//Notifications.addNotificationReceivedListener(this._handleNotification);
Notifications2.addListener(data => {
this.setState({ notification: data });
});
Notifications.addNotificationResponseReceivedListener(
this._handleNotificationResponse
);
}
_handleNotification = notification => {
this.setState({ notification: notification });
};
_handleNotificationResponse = response => {
console.log(response);
};
handleLogin = async () => {
try {
const { email, password } = this.state;
const expoPushToken = await Notifications.getExpoPushTokenAsync();
console.log(expoPushToken);
const userinfo = await firebase
.auth()
.signInWithEmailAndPassword(email, password);
console.log("user ID ", userinfo.user.uid);
await firebase
.firestore()
.collection("users")
.doc(userinfo.user.uid.toString())
.update({
expo_token: expoPushToken["data"]
})
.then(function() {
console.log("token successfully updated!");
})
.catch(function(error) {
// The document probably doesn't exist.
console.error("Error updating document: ", error);
});
} catch (error) {
console.log("=======Error in login", error);
this.setState({ errorMessage: error.message });
}
};
registerForPushNotificationsAsync = async () => {
if (Constants.isDevice) {
const { status: existingStatus } = await Permissions.getAsync(
Permissions.NOTIFICATIONS
);
let finalStatus = existingStatus;
if (existingStatus !== "granted") {
const { status } = await Permissions.askAsync(
Permissions.NOTIFICATIONS
);
finalStatus = status;
}
if (finalStatus !== "granted") {
alert("Failed to get push token for push notification!");
return;
}
const token = await Notifications.getExpoPushTokenAsync();
console.log(token);
//this.setState({ expoPushToken: token });
} else {
alert("Must use physical device for Push Notifications");
}
if (Platform.OS === "android") {
Notifications.setNotificationChannelAsync("default", {
name: "default",
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: "#FF231F7C"
});
}
};
import { Permissions } from "expo-permissions";
should of been
import * as Permissions from 'expo-permissions';
Sometimes we all make simple mistakes.
Please help me if any body resolved the issue and below is my lambda funciton code.
when i comment all funcitons in exports.handler funciton and execute/test single function it is working but if we enable all funcitons then i am getting the error as Error handled: Cannot read property 'value' of undefined
Node JS code for alexa skill kit for different intents created.
GetNewFactHandler,
CreateJIRAIssueHandler,
UpdateJIRAIssueHandler,
GetJIRAIssueHandler,
GetJIRAIssueCountHandler,
/* eslint-disable func-names */
/* eslint-disable no-console */
var http = require('http');
var https = require('https');
var projectKey='';
var iType='';
var keyValueID='';
var userName='';
var IssueNumber='';
const Alexa = require('ask-sdk');
const GetNewFactHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'LaunchRequest'
|| (request.type === 'IntentRequest'
&& request.intent.name === 'GetNewFactIntent');
},
handle(handlerInput) {
const factArr = data;
const factIndex = Math.floor(Math.random() * factArr.length);
const randomFact = factArr[factIndex];
const speechOutput = GET_FACT_MESSAGE + randomFact;
return handlerInput.responseBuilder
.speak(speechOutput)
.withSimpleCard(SKILL_NAME, randomFact)
.getResponse();
},
};
var reqTimeout = 3000;
const CreateJIRAIssueHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
const proKey = request.intent.slots.PROJECTKEY.value;
const issueType = request.intent.slots.ISSUETYPE.value;
iType = capitalize_Words(issueType);
projectKey = proKey.toUpperCase();
return request.type === 'IntentRequest' &&
request.intent.name === 'CreateJIRAIssue';
},
async handle(handlerInput) {
const createIssue = await createJiraIssue(projectKey, iType);
const speechOutput = JSON.parse(createIssue).key;
return handlerInput.responseBuilder
.speak('Issue ' + speechOutput + ' created')
.getResponse();
},
};
function capitalize_Words(str) {
return str.replace(/\w\S*/g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
};
//mule real time server
var muleCreateIssuePath = '/jira/createissue';
var muleProtocol = 'https';
var createIssueMethod = 'POST';
var muleUpdateIssuePath = '/jira/issue/';
var updateIssueMethod = 'PUT';
var getIssueMethod = 'GET';
var MuleReqOpts = {
host: '',
port: 443,
path: undefined, // To be set.
method: undefined,
headers: {
'Content-Type': 'application/json'
},
agent: false,
// auth: jiraUsername + ':' + jiraPassword
auth: ''
};
var MuleHttp = muleProtocol === 'https' ? https : http;
function createJiraIssue(projectKey, iType) {
MuleReqOpts.path = muleCreateIssuePath;
MuleReqOpts.method = createIssueMethod;
var MuleReqBody = {
'fields': {
'project': {
'key': projectKey
},
'summary': 'Test Message',
'description': 'Issue created for alexa skill kit from Integration alexa to jira',
'issuetype': {
'name': iType // Make sure your JIRA project configuration(s) supports this Issue Type.
}
}
};
return doApiCall(MuleHttp, MuleReqOpts, MuleReqBody, 'creating issue', 201);
};
function doApiCall(httplib, reqOpts, reqBody, happening, successCode) {
return new Promise(((resolve, reject) => {
var req = httplib.request(reqOpts, (res) => {
res.setEncoding('utf8');
let returnData = '';
res.on('data', (chunk) => {
returnData += chunk;
});
res.on('end', () => {
resolve(returnData);
});
res.on('error', (error) => {
reject(error);
});
});
req.write(JSON.stringify(reqBody));
req.end();
req.on('error', function(err) {
context.done(new Error(' request error: ' + err.message));
});
req.setTimeout(reqTimeout, function() {
context.done(new Error(' request timeout after ' + reqTimeout + ' milliseconds.'));
});
}));
};
const UpdateJIRAIssueHandler = {
canHandle(handlerInput) {
console.log('1');
const request = handlerInput.requestEnvelope.request;
console.log('2');
userName = request.intent.slots.USER.value;
var keyValue = request.intent.slots.PROJECTKEY.value;
console.log('keyValue : ' + keyValue);
keyValueID = keyValue.toUpperCase();
IssueNumber = request.intent.slots.ISSUENUMBER.value;
let INumber = Number(IssueNumber);
console.log('IssueNumber value: '+INumber);
console.log('key value id: ' + keyValueID);
return request.type === 'IntentRequest' &&
request.intent.name === 'UpdateJIRAIssue';
},
async handle(handlerInput) {
const updateIssue = await updateJiraIssue(userName);
console.log('updateIssue log: ' + updateIssue);
const speechOutput = JSON.parse(updateIssue).responseMessage;
console.log('speechOutput log: ' + speechOutput);
return handlerInput.responseBuilder
.speak(speechOutput)
.getResponse();
},
};
function updateJiraIssue(userName) {
console.log('inside method: ' +userName);
MuleReqOpts.method = updateIssueMethod;
var postdata = {
"fields": {
"assignee": {
"name": userName
}
}
}
return doApiUpdateCall(MuleHttp, MuleReqOpts, postdata, 'updating issue', 201);
};
function doApiUpdateCall(httplib, options, postdata, happening, successCode) {
options.path = muleUpdateIssuePath + keyValueID +'-'+IssueNumber ;
return new Promise(((resolve, reject) => {
var req = httplib.request(options, (res) => {
console.log(options);
res.setEncoding('utf8');
let returnData = '';
res.on('data', (body) => {
returnData += body;
console.log(returnData);
});
res.on('end', () => {
resolve(returnData);
});
console.log('1');
console.log('Body: ');
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
var jirapostString = JSON.stringify(postdata);
console.log(jirapostString);
req.write(jirapostString);
req.end();
}));
};
const GetJIRAIssueHandler = {
canHandle(handlerInput) {
console.log('1');
const request = handlerInput.requestEnvelope.request;
var keyValue = request.intent.slots.Issue.value;
console.log('keyValue: ' + keyValue);
keyValueID = keyValue.toUpperCase();
return request.type === 'IntentRequest' &&
request.intent.name === 'GetJIRAIssue';
},
async handle(handlerInput) {
const getIssue = await GetJIRAIssue();
console.log('getIssue log: ' + getIssue);
const assigneeName = JSON.parse(getIssue).fields.assignee.name;
const key = JSON.parse(getIssue).fields.assignee.key;
const reporterName = JSON.parse(getIssue).fields.reporter.name;
const issueType = JSON.parse(getIssue).fields.issuetype.name;
const projectName = JSON.parse(getIssue).fields.project.name;
const summaryDetails = JSON.parse(getIssue).fields.summary;
const speechOutput = 'Here are the issue details summary: Assignee : ' + assigneeName.concat(' ,reporter : ' + reporterName, ' ,Issue Key : ' + key, ' ,IssueType : ' + issueType, ' ,ProjectName : ' + projectName, ' ,Summary : ' + summaryDetails);
console.log('speechOutput log: ' + speechOutput);
return handlerInput.responseBuilder
.speak(speechOutput)
.getResponse();
},
};
function GetJIRAIssue() {
MuleReqOpts.method = getIssueMethod;
return doApiGetIssueCall(MuleHttp, MuleReqOpts, 'get issue details', 201);
};
function doApiGetIssueCall(httplib, options, happening, successCode) {
options.path = muleUpdateIssuePath + keyValueID;
return new Promise(((resolve, reject) => {
https.get(options, (res) => {
console.log(options);
res.setEncoding('utf8');
let returnData = '';
res.on('data', (body) => {
returnData += body;
console.log('response :', returnData);
});
res.on('end', () => {
resolve(returnData);
});
});
}));
};
const GetJIRAIssueCountHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
userName = request.intent.slots.USER.value;
console.log('userName Value: ' + userName);
const issueType = request.intent.slots.ISSUETYPE.value;
iType = capitalize_Words(issueType);
return request.type === 'IntentRequest' &&
request.intent.name === 'GetJIRAIssueCount';
},
async handle(handlerInput) {
const getIssueCount = await GetJIRAIssueCount();
console.log('getIssue log: ' + getIssueCount);
const total = JSON.parse(getIssueCount).total;
const speechOutput = ('Here is the '+iType+' count details: ' +total );
console.log('speechOutput log: ' + speechOutput);
return handlerInput.responseBuilder
.speak(speechOutput)
.getResponse();
},
};
function GetJIRAIssueCount() {
MuleReqOpts.method = getIssueMethod;
return doApiGetIssueCountCall(MuleHttp, MuleReqOpts, 'get issue count details', 201);
};
function doApiGetIssueCountCall(httplib, options, happening, successCode) {
options.path = muleUpdateIssuePath + userName +'/'+iType;
return new Promise(((resolve, reject) => {
https.get(options, (res) => {
console.log(options);
res.setEncoding('utf8');
let returnData = '';
res.on('data', (body) => {
returnData += body;
console.log('response :', returnData);
});
res.on('end', () => {
resolve(returnData);
});
});
}));
};
const HelpHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest'
&& request.intent.name === 'AMAZON.HelpIntent';
},
handle(handlerInput) {
return handlerInput.responseBuilder
.speak(HELP_MESSAGE)
.reprompt(HELP_REPROMPT)
.getResponse();
},
};
const ExitHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest'
&& (request.intent.name === 'AMAZON.CancelIntent'
|| request.intent.name === 'AMAZON.StopIntent');
},
handle(handlerInput) {
return handlerInput.responseBuilder
.speak(STOP_MESSAGE)
.getResponse();
},
};
const SessionEndedRequestHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'SessionEndedRequest';
},
handle(handlerInput) {
console.log(`Session ended with reason: ${handlerInput.requestEnvelope.request.reason}`);
return handlerInput.responseBuilder.getResponse();
},
};
const ErrorHandler = {
canHandle() {
return true;
},
handle(handlerInput, error) {
console.log(`Error handled: ${error.message}`);
return handlerInput.responseBuilder
.speak('Sorry, an error occurred.')
.reprompt('Sorry, an error occurred.')
.getResponse();
},
};
const SKILL_NAME = 'Space Facts';
const GET_FACT_MESSAGE = 'Here\'s your fact: ';
const HELP_MESSAGE = 'You can say tell me a space fact, or, you can say exit... What can I help you with?';
const HELP_REPROMPT = 'What can I help you with?';
const STOP_MESSAGE = 'Goodbye!';
const data = [
'A year on Mercury is just 88 days long.',
'Despite being farther from the Sun, Venus experiences higher temperatures than Mercury.',
'Venus rotates counter-clockwise, possibly because of a collision in the past with an asteroid.',
'On Mars, the Sun appears about half the size as it does on Earth.',
'Earth is the only planet not named after a god.',
'Jupiter has the shortest day of all the planets.',
'The Milky Way galaxy will collide with the Andromeda Galaxy in about 5 billion years.',
'The Sun contains 99.86% of the mass in the Solar System.',
'The Sun is an almost perfect sphere.',
'A total solar eclipse can happen once every 1 to 2 years. This makes them a rare event.',
'Saturn radiates two and a half times more energy into space than it receives from the sun.',
'The temperature inside the Sun can reach 15 million degrees Celsius.',
'The Moon is moving approximately 3.8 cm away from our planet every year.',
];
const skillBuilder = Alexa.SkillBuilders.custom();
exports.handler = skillBuilder
.addRequestHandlers(
GetNewFactHandler,
CreateJIRAIssueHandler,
UpdateJIRAIssueHandler,
GetJIRAIssueHandler,
GetJIRAIssueCountHandler,
HelpHandler,
ExitHandler,
SessionEndedRequestHandler
)
.addErrorHandlers(ErrorHandler)
.lambda();
Check all of your code for instances where you are looking for someObject.someNestedProperty.value.
I suspect that your slot values in your Intents are not the same as defined in your model/some-LANG.json file. Trying to access value property from someObject without a someNestedProperty will cause your error (i.e. request.intent.slots.PROJECTKEY.value).
If this is a Alexa-hosted skill, CloudWatch logging is built right in. Open the Alexa Developer Console, edit your skill, then go to the Code tab. On the bottom left, you should see a link for Logs: Amazon CloudWatch. You can log anything you want with a simple console.log() statement.
Also, be aware that the ask-sdk-core npm package contains helper methods to get slotValues (among other great tools). For more information, see this link: https://developer.amazon.com/en-US/docs/alexa/alexa-skills-kit-sdk-for-nodejs/utilities.html
Thanks all for your suggestions and prompt response.
Now the issue is resolved and the solution is the addRequestHandlers method will execute methods sequentially even if you execute/trigger third handler it will execute 1st and 2nd and goes to 3rd one. Here the issue is when you trigger a 3rd handler command from alexa it will passs the slot values related to the 3rd handler utterance and hence the 1st and 2nd haldler having slot values are not able to resolve and failed. so i put a condition overthere to skip 1st and 2nd handler execution and it worked.
Hi i am trying to implement oauth2 with Zapier platform, and i am facing some error.
I just have a testing node.js app where i am login request from zapier platform.
const express = require('express');
const jwt = require('jsonwebtoken');
const uuidv4 = require('uuid/v4');
const app = express();
const port = process.env.PORT || 3000;
let count = 0;
// const redirect url = https://zapier.com/dashboard/auth/oauth/return/App77581CLIAPI/
app.get('/', (req, res) => res.json({
count
}));
app.post('/zapier', (req, res) => {
count++;
res.json({
count
})
})
app.get('/api/login', (req, res) => {
// console.log('req', req);
const { state } = req.query;
// const state = 1578212496.13945431311;
console.log(state);
const user = {
name: "ankit",
id: 12344
}
const token = jwt.sign(user, "luciferTonify");
const code = uuidv4();
res.redirect(`https://zapier.com/dashboard/auth/oauth/return/App77581CLIAPI?code=${code}&state=${state}&access_token=${code}&token_type=bearer`);
})
app.post('/api/login', (req, res) => {
const user = {
name: "ankit",
id: 12344
}
const token = jwt.sign(user, "luciferTonify");
res.json({ token });
});
function verifyToken(req, res, next) {
const { authorization: token } = req.headers;
if (typeof token == 'undefined' || !token) {
req.token = token;
next();
} else {
res.sendStatus(403);
}
}
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
its just a testing app, so i am trying to send an access_token, but zapier is giving me this error
**
Zapier could not connect to your account. Field named access_token
not found in OAuth2 results
**
?
can anyone help me what i am doing wrong ?