New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

nativescript-oauth2

Package Overview
Dependencies
Maintainers
1
Versions
38
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

nativescript-oauth2 - npm Package Compare versions

Comparing version 2.4.4 to 3.0.1

delegate/index.android.js

20

delegate/delegate.android.js

@@ -1,8 +0,6 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var appModule = require("tns-core-modules/application");
appModule.android.on(appModule.AndroidApplication.activityResumedEvent, function (args) {
import * as appModule from "tns-core-modules/application";
appModule.android.on(appModule.AndroidApplication.activityResumedEvent, (args) => {
if (new String(args.activity.getIntent().getAction()).valueOf() ===
new String(android.content.Intent.ACTION_VIEW).valueOf()) {
var url = args.activity
const url = args.activity
.getIntent()

@@ -22,12 +20,8 @@ .getData()

});
var TnsOAuthClientAppDelegate = (function () {
function TnsOAuthClientAppDelegate() {
}
TnsOAuthClientAppDelegate.setConfig = function (client, urlScheme) {
export class TnsOAuthClientAppDelegate {
static setConfig(client, urlScheme) {
this._client = client;
this._urlScheme = urlScheme;
};
return TnsOAuthClientAppDelegate;
}());
exports.TnsOAuthClientAppDelegate = TnsOAuthClientAppDelegate;
}
}
//# sourceMappingURL=delegate.android.js.map

@@ -1,20 +0,14 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var TnsOAuthClientAppDelegate = (function (_super) {
__extends(TnsOAuthClientAppDelegate, _super);
function TnsOAuthClientAppDelegate() {
return _super !== null && _super.apply(this, arguments) || this;
}
TnsOAuthClientAppDelegate_1 = TnsOAuthClientAppDelegate;
TnsOAuthClientAppDelegate.setConfig = function (client, urlScheme) {
var TnsOAuthClientAppDelegate_1;
let TnsOAuthClientAppDelegate = TnsOAuthClientAppDelegate_1 = class TnsOAuthClientAppDelegate extends UIResponder {
static setConfig(client, urlScheme) {
this._client = client;
this._urlScheme = urlScheme;
};
TnsOAuthClientAppDelegate.prototype.applicationOpenURLOptions = function (application, url, options) {
}
applicationOpenURLOptions(application, url, options) {
return this.handleIncomingUrl(url);
};
TnsOAuthClientAppDelegate.prototype.applicationOpenURLSourceApplicationAnnotation = function (application, url, sourceApplication, annotation) {
}
applicationOpenURLSourceApplicationAnnotation(application, url, sourceApplication, annotation) {
return this.handleIncomingUrl(url);
};
TnsOAuthClientAppDelegate.prototype.handleIncomingUrl = function (url) {
}
handleIncomingUrl(url) {
if (!TnsOAuthClientAppDelegate_1._client ||

@@ -32,10 +26,8 @@ !TnsOAuthClientAppDelegate_1._urlScheme) {

}
};
var TnsOAuthClientAppDelegate_1;
TnsOAuthClientAppDelegate = TnsOAuthClientAppDelegate_1 = __decorate([
ObjCClass(UIApplicationDelegate)
], TnsOAuthClientAppDelegate);
return TnsOAuthClientAppDelegate;
}(UIResponder));
exports.TnsOAuthClientAppDelegate = TnsOAuthClientAppDelegate;
}
};
TnsOAuthClientAppDelegate = TnsOAuthClientAppDelegate_1 = __decorate([
ObjCClass(UIApplicationDelegate)
], TnsOAuthClientAppDelegate);
export { TnsOAuthClientAppDelegate };
//# sourceMappingURL=delegate.ios.js.map

@@ -1,5 +0,7 @@

/// <reference path="./providers/providers.d.ts" />
import { Frame } from "tns-core-modules/ui/frame";
import { LoadEventData } from "tns-core-modules/ui/web-view/web-view";
import { HttpResponse } from "tns-core-modules/http/http";
import {
Application,
Frame,
HttpResponse,
LoadEventData,
} from "@nativescript/core";
import { TnsOaProvider, TnsOaProviderType } from "./providers";

@@ -20,5 +22,3 @@

) => void;
export type TnsOAuthClientLogoutBlock = (
error
) => void;
export type TnsOAuthClientLogoutBlock = (error) => void;
export type TnsOAuthPageLoadStarted = (args: LoadEventData) => void;

@@ -25,0 +25,0 @@ export type TnsOAuthPageLoadFinished = (args: LoadEventData) => void;

@@ -1,28 +0,26 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var applicationModule = require("tns-core-modules/application");
var platformModule = require("tns-core-modules/platform");
var frameModule = require("tns-core-modules/ui/frame");
var delegate_1 = require("./delegate");
var tns_oauth_native_view_controller_1 = require("./tns-oauth-native-view-controller");
var tns_oauth_login_webview_controller_1 = require("./tns-oauth-login-webview-controller");
var tns_oauth_client_connection_1 = require("./tns-oauth-client-connection");
var tns_oauth_utils_1 = require("./tns-oauth-utils");
var TnsOAuthClient = (function () {
function TnsOAuthClient(providerType, pkce) {
if (pkce === void 0) { pkce = true; }
import { Application, Frame } from "@nativescript/core";
import { TnsOAuthClientAppDelegate } from "./delegate";
import { TnsOAuthLoginNativeViewController } from "./tns-oauth-native-view-controller";
import { TnsOAuthLoginWebViewController } from "./tns-oauth-login-webview-controller";
import { TnsOAuthClientConnection } from "./tns-oauth-client-connection";
import { nsArrayToJSArray, jsArrayToNSArray, httpResponseToToken, } from "./tns-oauth-utils";
export class TnsOAuthClient {
constructor(providerType, pkce = true) {
this.pkce = pkce;
this.provider = null;
this.provider = exports.tnsOauthProviderMap.providerMap.get(providerType);
this.provider = tnsOauthProviderMap.providerMap.get(providerType);
if (this.provider) {
switch (this.provider.options.openIdSupport) {
case "oid-full":
delegate_1.TnsOAuthClientAppDelegate.setConfig(this, this.provider.options.urlScheme);
this.loginController = tns_oauth_native_view_controller_1.TnsOAuthLoginNativeViewController.initWithClient(this);
TnsOAuthClientAppDelegate.setConfig(this, this.provider.options.urlScheme);
console.log("TnsOAuthLoginNativeViewController:", TnsOAuthLoginNativeViewController);
console.log("typeof TnsOAuthLoginNativeViewController:", typeof TnsOAuthLoginNativeViewController);
console.log("TnsOAuthLoginNativeViewController.initWithClient:", TnsOAuthLoginNativeViewController.initWithClient);
this.loginController = TnsOAuthLoginNativeViewController.initWithClient(this);
break;
case "oid-none":
this.loginController = tns_oauth_login_webview_controller_1.TnsOAuthLoginWebViewController.initWithClient(this);
this.loginController = TnsOAuthLoginWebViewController.initWithClient(this);
break;
default:
this.loginController = tns_oauth_login_webview_controller_1.TnsOAuthLoginWebViewController.initWithClient(this);
this.loginController = TnsOAuthLoginWebViewController.initWithClient(this);
break;

@@ -32,5 +30,5 @@ }

}
TnsOAuthClient.prototype.loginWithCompletion = function (completion) {
loginWithCompletion(completion) {
if (this.provider) {
this.loginController.loginWithParametersFrameCompletion(null, frameModule.topmost(), this.provider.options.urlScheme, completion);
this.loginController.loginWithParametersFrameCompletion(null, Frame.topmost(), this.provider.options.urlScheme, completion);
}

@@ -40,6 +38,6 @@ else {

}
};
TnsOAuthClient.prototype.logoutWithCompletion = function (completion) {
}
logoutWithCompletion(completion) {
if (this.provider) {
this.loginController.logoutWithParametersFrameCompletion(null, frameModule.topmost(), this.provider.options.urlScheme, completion);
this.loginController.logoutWithParametersFrameCompletion(null, Frame.topmost(), this.provider.options.urlScheme, completion);
}

@@ -49,4 +47,4 @@ else {

}
};
TnsOAuthClient.prototype.refreshTokenWithCompletion = function (completion) {
}
refreshTokenWithCompletion(completion) {
if (this.provider) {

@@ -58,18 +56,17 @@ this.callRefreshEndpointWithCompletion(completion);

}
};
TnsOAuthClient.prototype.logout = function () {
}
logout() {
this.callRevokeEndpoint();
this.removeCookies();
this.removeToken();
};
TnsOAuthClient.prototype.resumeWithUrl = function (url) {
}
resumeWithUrl(url) {
this.loginController.resumeWithUrl(url);
};
TnsOAuthClient.prototype.removeCookies = function () {
var _this = this;
if (platformModule.isIOS) {
var cookieArr = tns_oauth_utils_1.nsArrayToJSArray(NSHTTPCookieStorage.sharedHTTPCookieStorage.cookies);
for (var i = 0; i < cookieArr.length; i++) {
var cookie = cookieArr[i];
for (var j = 0; j < this.provider.cookieDomains.length; j++) {
}
removeCookies() {
if (global.isIOS) {
let cookieArr = nsArrayToJSArray(NSHTTPCookieStorage.sharedHTTPCookieStorage.cookies);
for (let i = 0; i < cookieArr.length; i++) {
const cookie = cookieArr[i];
for (let j = 0; j < this.provider.cookieDomains.length; j++) {
if (cookie.domain.endsWith(this.provider.cookieDomains[j])) {

@@ -80,24 +77,21 @@ NSHTTPCookieStorage.sharedHTTPCookieStorage.deleteCookie(cookie);

}
var dataStore_1 = WKWebsiteDataStore.defaultDataStore();
dataStore_1.fetchDataRecordsOfTypesCompletionHandler(WKWebsiteDataStore.allWebsiteDataTypes(), function (records) {
var cookieArr = tns_oauth_utils_1.nsArrayToJSArray(records);
var _loop_1 = function (k) {
var cookieRecord = cookieArr[k];
for (var l = 0; l < _this.provider.cookieDomains.length; l++) {
if (cookieRecord.displayName.endsWith(_this.provider.cookieDomains[l])) {
dataStore_1.removeDataOfTypesForDataRecordsCompletionHandler(cookieRecord.dataTypes, tns_oauth_utils_1.jsArrayToNSArray([cookieRecord]), function () {
console.log("Cookies for " + cookieRecord.displayName + " deleted successfully");
const dataStore = WKWebsiteDataStore.defaultDataStore();
dataStore.fetchDataRecordsOfTypesCompletionHandler(WKWebsiteDataStore.allWebsiteDataTypes(), (records) => {
const cookieArr = nsArrayToJSArray(records);
for (let k = 0; k < cookieArr.length; k++) {
const cookieRecord = cookieArr[k];
for (let l = 0; l < this.provider.cookieDomains.length; l++) {
if (cookieRecord.displayName.endsWith(this.provider.cookieDomains[l])) {
dataStore.removeDataOfTypesForDataRecordsCompletionHandler(cookieRecord.dataTypes, jsArrayToNSArray([cookieRecord]), () => {
console.log(`Cookies for ${cookieRecord.displayName} deleted successfully`);
});
}
}
};
for (var k = 0; k < cookieArr.length; k++) {
_loop_1(k);
}
});
}
else if (platformModule.isAndroid) {
var cookieManager = android.webkit.CookieManager.getInstance();
else if (global.isAndroid) {
let cookieManager = android.webkit.CookieManager.getInstance();
if (cookieManager.removeAllCookies) {
var cm23 = cookieManager;
let cm23 = cookieManager;
cm23.removeAllCookies(null);

@@ -111,11 +105,11 @@ cm23.flush();

}
};
TnsOAuthClient.prototype.removeToken = function () {
}
removeToken() {
this.tokenResult = null;
};
TnsOAuthClient.prototype.callRevokeEndpoint = function () {
}
callRevokeEndpoint() {
if (!this.provider.revokeEndpoint) {
return;
}
var responseCompletion = function (data, response, responseError) {
let responseCompletion = (data, response, responseError) => {
if (!responseError) {

@@ -128,7 +122,6 @@ if (response.statusCode === 200) {

};
var connection = tns_oauth_client_connection_1.TnsOAuthClientConnection.initWithRequestClientCompletion(this, responseCompletion);
const connection = TnsOAuthClientConnection.initWithRequestClientCompletion(this, responseCompletion);
connection.startTokenRevocation();
};
TnsOAuthClient.prototype.callRefreshEndpointWithCompletion = function (completion) {
var _this = this;
}
callRefreshEndpointWithCompletion(completion) {
if (!this.provider.tokenEndpoint) {

@@ -140,43 +133,38 @@ return;

}
var connection = tns_oauth_client_connection_1.TnsOAuthClientConnection.initWithRequestClientCompletion(this, function (data, result, error) {
const connection = TnsOAuthClientConnection.initWithRequestClientCompletion(this, (data, result, error) => {
if (result) {
var tokenResult = tns_oauth_utils_1.httpResponseToToken(result);
if (!tokenResult.refreshToken && _this.tokenResult) {
tokenResult.refreshToken = _this.tokenResult.refreshToken;
tokenResult.refreshTokenExpiration = _this.tokenResult.refreshTokenExpiration;
const tokenResult = httpResponseToToken(result);
if (!tokenResult.refreshToken && this.tokenResult) {
tokenResult.refreshToken = this.tokenResult.refreshToken;
tokenResult.refreshTokenExpiration = this.tokenResult.refreshTokenExpiration;
}
_this.tokenResult = tokenResult;
this.tokenResult = tokenResult;
}
completion(_this.tokenResult, error);
completion(this.tokenResult, error);
});
connection.startTokenRefresh();
};
return TnsOAuthClient;
}());
exports.TnsOAuthClient = TnsOAuthClient;
var TnsOauthProviderMap = (function () {
function TnsOauthProviderMap() {
}
}
export class TnsOauthProviderMap {
constructor() {
this.providerMap = new Map();
}
TnsOauthProviderMap.prototype.addProvider = function (providerType, provider) {
addProvider(providerType, provider) {
this.providerMap.set(providerType, provider);
};
return TnsOauthProviderMap;
}());
exports.TnsOauthProviderMap = TnsOauthProviderMap;
exports.tnsOauthProviderMap = new TnsOauthProviderMap();
}
}
export const tnsOauthProviderMap = new TnsOauthProviderMap();
function configureClientAuthAppDelegate() {
applicationModule.ios.delegate = delegate_1.TnsOAuthClientAppDelegate;
Application.ios.delegate = TnsOAuthClientAppDelegate;
}
function configureTnsOAuth(providers) {
if (platformModule.isIOS) {
if (providers.some(function (p) { return p.options.openIdSupport === "oid-full"; })) {
export function configureTnsOAuth(providers) {
if (global.isIOS) {
if (providers.some((p) => p.options.openIdSupport === "oid-full")) {
configureClientAuthAppDelegate();
}
}
for (var i = 0; i < providers.length; ++i) {
exports.tnsOauthProviderMap.addProvider(providers[i].providerType, providers[i]);
for (let i = 0; i < providers.length; ++i) {
tnsOauthProviderMap.addProvider(providers[i].providerType, providers[i]);
}
}
exports.configureTnsOAuth = configureTnsOAuth;
//# sourceMappingURL=oauth.js.map
{
"name": "nativescript-oauth2",
"version": "2.4.4",
"version": "3.0.1",
"description": "OAuth 2 generic authorization plugin for NativeScript that doesn't install third party native libraries",

@@ -9,4 +9,4 @@ "main": "oauth",

"platforms": {
"android": "5.2.0",
"ios": "5.2.0"
"android": "7.0.0",
"ios": "7.0.0"
}

@@ -16,3 +16,3 @@ },

"tsc": "tsc",
"build": "npm i && tsc",
"build": "npm i && ts-patch install && tsc",
"build.native": "node scripts/build-native.js",

@@ -71,8 +71,10 @@ "postclone": "npm i && node scripts/postclone.js && cd ../demo && npm i && npx rimraf -- package-lock.json && cd ../src",

"devDependencies": {
"tns-core-modules": "^5.2.0",
"tns-platform-declarations": "^5.2.0",
"typescript": "3.1.1",
"@nativescript/core": "7.0.0",
"@nativescript/types": "7.0.0",
"@nativescript/webpack": "~3.0.0",
"typescript": "~3.9.0",
"prompt": "^1.0.0",
"rimraf": "^2.6.2",
"tslint": "5.18.0",
"ts-patch": "1.3.0",
"semver": "^5.5.0"

@@ -82,2 +84,3 @@ },

"querystring": "0.2.0",
"ts-node": "^9.0.0",
"url": "0.11.0"

@@ -84,0 +87,0 @@ },

@@ -1,18 +0,14 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var DEFAULT_CODE_VERIFIER_ENTROPY = 64;
var PKCE_BASE64_ENCODE_SETTINGS = android.util.Base64.NO_WRAP | android.util.Base64.NO_PADDING | android.util.Base64.URL_SAFE;
function getCodeVerifier() {
var randomBytes = Array.create("byte", DEFAULT_CODE_VERIFIER_ENTROPY);
const DEFAULT_CODE_VERIFIER_ENTROPY = 64;
const PKCE_BASE64_ENCODE_SETTINGS = android.util.Base64.NO_WRAP | android.util.Base64.NO_PADDING | android.util.Base64.URL_SAFE;
export function getCodeVerifier() {
const randomBytes = Array.create("byte", DEFAULT_CODE_VERIFIER_ENTROPY);
new java.security.SecureRandom().nextBytes(randomBytes);
return android.util.Base64.encodeToString(randomBytes, PKCE_BASE64_ENCODE_SETTINGS);
}
exports.getCodeVerifier = getCodeVerifier;
function sha256base64encoded(codeVerifier) {
var sha256Digester = java.security.MessageDigest.getInstance("SHA-256");
export function sha256base64encoded(codeVerifier) {
const sha256Digester = java.security.MessageDigest.getInstance("SHA-256");
sha256Digester.update(new java.lang.String(codeVerifier).getBytes("ISO_8859_1"));
var digestBytes = sha256Digester.digest();
const digestBytes = sha256Digester.digest();
return android.util.Base64.encodeToString(digestBytes, PKCE_BASE64_ENCODE_SETTINGS);
}
exports.sha256base64encoded = sha256base64encoded;
//# sourceMappingURL=pkce-util.android.js.map

@@ -1,7 +0,5 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var SHA256_DIGEST_LENGTH = 32;
function getCodeVerifier() {
var randomData = NSMutableData.dataWithLength(SHA256_DIGEST_LENGTH);
var result = SecRandomCopyBytes(kSecRandomDefault, randomData.length, randomData.mutableBytes);
const SHA256_DIGEST_LENGTH = 32;
export function getCodeVerifier() {
const randomData = NSMutableData.dataWithLength(SHA256_DIGEST_LENGTH);
const result = SecRandomCopyBytes(kSecRandomDefault, randomData.length, randomData.mutableBytes);
if (result !== 0) {

@@ -14,12 +12,10 @@ return null;

}
exports.getCodeVerifier = getCodeVerifier;
function sha256base64encoded(inputString) {
var verifierData = NSString.stringWithString(inputString).dataUsingEncoding(NSUTF8StringEncoding);
var sha256Verifier = NSMutableData.dataWithLength(SHA256_DIGEST_LENGTH);
export function sha256base64encoded(inputString) {
const verifierData = NSString.stringWithString(inputString).dataUsingEncoding(NSUTF8StringEncoding);
const sha256Verifier = NSMutableData.dataWithLength(SHA256_DIGEST_LENGTH);
CC_SHA256(verifierData.bytes, verifierData.length, sha256Verifier.mutableBytes);
return encodeBase64urlNoPadding(sha256Verifier);
}
exports.sha256base64encoded = sha256base64encoded;
function encodeBase64urlNoPadding(data) {
var base64string = data.base64EncodedStringWithOptions(0);
let base64string = data.base64EncodedStringWithOptions(0);
base64string = base64string.replace(/\+/g, "-");

@@ -26,0 +22,0 @@ base64string = base64string.replace(/\//g, "_");

@@ -1,5 +0,3 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var TnsOaProviderMicrosoft = (function () {
function TnsOaProviderMicrosoft(options) {
export class TnsOaProviderMicrosoft {
constructor(options) {
this.openIdSupport = "oid-full";

@@ -14,10 +12,8 @@ this.providerType = "microsoft";

}
TnsOaProviderMicrosoft.prototype.parseTokenResult = function (jsonData) {
parseTokenResult(jsonData) {
return jsonData;
};
return TnsOaProviderMicrosoft;
}());
exports.TnsOaProviderMicrosoft = TnsOaProviderMicrosoft;
var TnsOaProviderGoogle = (function () {
function TnsOaProviderGoogle(options) {
}
}
export class TnsOaProviderGoogle {
constructor(options) {
this.openIdSupport = "oid-full";

@@ -32,13 +28,11 @@ this.providerType = "google";

}
TnsOaProviderGoogle.prototype.parseTokenResult = function (jsonData) {
parseTokenResult(jsonData) {
return jsonData;
};
TnsOaProviderGoogle.prototype.getLogoutUrlStr = function () {
return "https://www.google.com/accounts/Logout";
};
return TnsOaProviderGoogle;
}());
exports.TnsOaProviderGoogle = TnsOaProviderGoogle;
var TnsOaProviderFacebook = (function () {
function TnsOaProviderFacebook(options) {
}
getLogoutUrlStr() {
return `https://www.google.com/accounts/Logout`;
}
}
export class TnsOaProviderFacebook {
constructor(options) {
this.openIdSupport = "oid-none";

@@ -53,10 +47,8 @@ this.providerType = "facebook";

}
TnsOaProviderFacebook.prototype.parseTokenResult = function (jsonData) {
parseTokenResult(jsonData) {
return jsonData;
};
return TnsOaProviderFacebook;
}());
exports.TnsOaProviderFacebook = TnsOaProviderFacebook;
var TnsOaProviderLinkedIn = (function () {
function TnsOaProviderLinkedIn(options) {
}
}
export class TnsOaProviderLinkedIn {
constructor(options) {
this.openIdSupport = "oid-none";

@@ -71,10 +63,8 @@ this.providerType = "linkedIn";

}
TnsOaProviderLinkedIn.prototype.parseTokenResult = function (jsonData) {
parseTokenResult(jsonData) {
return jsonData;
};
return TnsOaProviderLinkedIn;
}());
exports.TnsOaProviderLinkedIn = TnsOaProviderLinkedIn;
var TnsOaProviderIdentityServer = (function () {
function TnsOaProviderIdentityServer(options) {
}
}
export class TnsOaProviderIdentityServer {
constructor(options) {
this.openIdSupport = 'oid-full';

@@ -89,3 +79,3 @@ this.providerType = 'identityServer';

this.tokenEndpointBase = options.issuerUrl;
var match = /^https:\/\/(.*?)$/.exec(options.issuerUrl);
const match = /^https:\/\/(.*?)$/.exec(options.issuerUrl);
if (match) {

@@ -95,8 +85,6 @@ this.cookieDomains = [match[1].toString()];

}
TnsOaProviderIdentityServer.prototype.parseTokenResult = function (jsonData) {
parseTokenResult(jsonData) {
return jsonData;
};
return TnsOaProviderIdentityServer;
}());
exports.TnsOaProviderIdentityServer = TnsOaProviderIdentityServer;
}
}
//# sourceMappingURL=providers.js.map

@@ -8,9 +8,9 @@ # OAuth 2 Plugin for NativeScript

[build-status]:https://travis-ci.org/alexziskind1/nativescript-oauth2.svg?branch=master
[build-url]:https://travis-ci.org/alexziskind1/nativescript-oauth2
[npm-image]:http://img.shields.io/npm/v/nativescript-oauth2.svg
[npm-url]:https://npmjs.org/package/nativescript-oauth2
[downloads-image]:http://img.shields.io/npm/dm/nativescript-oauth2.svg
[twitter-image]:https://img.shields.io/twitter/follow/digitalix.svg?style=social&label=Follow%20me
[twitter-url]:https://twitter.com/digitalix
[build-status]: https://travis-ci.org/alexziskind1/nativescript-oauth2.svg?branch=master
[build-url]: https://travis-ci.org/alexziskind1/nativescript-oauth2
[npm-image]: http://img.shields.io/npm/v/nativescript-oauth2.svg
[npm-url]: https://npmjs.org/package/nativescript-oauth2
[downloads-image]: http://img.shields.io/npm/dm/nativescript-oauth2.svg
[twitter-image]: https://img.shields.io/twitter/follow/digitalix.svg?style=social&label=Follow%20me
[twitter-url]: https://twitter.com/digitalix

@@ -21,5 +21,6 @@ Library for interacting with OAuth 2.0 in NativeScript applications that provides simplified direct client access with a OAuth providers that support the OAuth 2.0 protocol such as Microsoft, Facebook, and Google, but not limited to any login providers, and even allows you to plug in your own. This library doesn't use any native libraries and relies only on what comes in the box - making it really lightweight.

**_NOTE:_** For **NativeScript 7** support, use version 3+ of this plugin. For versions of NativeScript that are less than 7, use versions less than 3 of this plugin.
<img src="https://raw.githubusercontent.com/alexziskind1/nativescript-oauth2/master/docs/images/nativescript-oauth2-logo.png" alt="NativeScript OAuth 2"/>
<br/>

@@ -92,3 +93,3 @@

The default IdentityServer provider is configured to use the [demo server](https://demo.identityserver.io/) with __client id: native.code__ _grant type: authorization code with PKCE and client credentials_.
The default IdentityServer provider is configured to use the [demo server](https://demo.identityserver.io/) with **client id: native.code** _grant type: authorization code with PKCE and client credentials_.

@@ -154,3 +155,3 @@ login with `bob/bob`, `alice/alice` or choose external login with `Google` or `Azure AD`.

TnsOaProviderOptionsMicrosoft,
TnsOaProviderMicrosoft
TnsOaProviderMicrosoft,
} from "nativescript-oauth2/providers";

@@ -167,3 +168,3 @@

"com.googleusercontent.apps.932931520457-buv2dnhgo7jjjjv5fckqltn367psbrlb",
scopes: ["email"]
scopes: ["email"],
};

@@ -180,3 +181,3 @@ const googleProvider = new TnsOaProviderGoogle(googleProviderOptions);

redirectUri: "https://www.facebook.com/connect/login_success.html",
scopes: ["email"]
scopes: ["email"],
};

@@ -189,3 +190,3 @@ const facebookProvider = new TnsOaProviderFacebook(facebookProviderOptions);

configureOAuthProviderGoogle(),
configureOAuthProviderFacebook()
configureOAuthProviderFacebook(),
]);

@@ -227,4 +228,4 @@ ```

* The scope `offline_access` was requested when you logged in.
* The `TnsOAuthClient` must have the token result from your previous login. If you have the original instance you used to log in, it will already be on the object. If you do not have the original instance of `TnsOAuthClient` which you used to log in, such as if the app was restarted, then assign the client's `tokenResult` property to your token.
- The scope `offline_access` was requested when you logged in.
- The `TnsOAuthClient` must have the token result from your previous login. If you have the original instance you used to log in, it will already be on the object. If you do not have the original instance of `TnsOAuthClient` which you used to log in, such as if the app was restarted, then assign the client's `tokenResult` property to your token.

@@ -257,3 +258,3 @@ If that criteria is met, then you can refresh the token like so:

Implement your provider's options by extending the `TnsOaUnsafeProviderOptions` interface **if your provider is not Open Id compliant**, or the `TnsOaOpenIdProviderOptions` interface **if your provider *is* Open Id compliant**.
Implement your provider's options by extending the `TnsOaUnsafeProviderOptions` interface **if your provider is not Open Id compliant**, or the `TnsOaOpenIdProviderOptions` interface **if your provider _is_ Open Id compliant**.

@@ -265,3 +266,4 @@ > Note: the interface is named with the word 'unsafe' in the name because non-open id compliant providers (like Facebook) usually make you use a client secret to send to the provider in exchange for the token. Storing the secret somewhere other than the client app is recommended (like a proxy), but most people don't do this and just store the secret with the app - thus unsafe.

export interface TnsOaMyCustomProviderOptions extends TnsOaUnsafeProviderOptions { }
export interface TnsOaMyCustomProviderOptions
extends TnsOaUnsafeProviderOptions {}
```

@@ -277,18 +279,18 @@

export class TnsOaProviderMyCustomProvider implements TnsOaProvider {
public options: TnsOaProviderOptions;
public openIdSupport: OpenIdSupportNone = "oid-none";
public providerType = "myCustomProvider";
public authority = "https://www.facebook.com/v3.1/dialog";
public tokenEndpointBase = "https://graph.facebook.com";
public authorizeEndpoint = "/oauth";
public tokenEndpoint = "/v3.1/oauth/access_token";
public cookieDomains = ["facebook.com"];
public options: TnsOaProviderOptions;
public openIdSupport: OpenIdSupportNone = "oid-none";
public providerType = "myCustomProvider";
public authority = "https://www.facebook.com/v3.1/dialog";
public tokenEndpointBase = "https://graph.facebook.com";
public authorizeEndpoint = "/oauth";
public tokenEndpoint = "/v3.1/oauth/access_token";
public cookieDomains = ["facebook.com"];
constructor(options: TnsOaMyCustomProviderOptions) {
this.options = options;
}
constructor(options: TnsOaMyCustomProviderOptions) {
this.options = options;
}
public parseTokenResult(jsonData): ITnsOAuthTokenResult {
return jsonData;
}
public parseTokenResult(jsonData): ITnsOAuthTokenResult {
return jsonData;
}
}

@@ -323,6 +325,8 @@ ```

customQueryParams: {
foo: "bar"
}
foo: "bar",
},
};
const facebookProvider = new TnsOaProviderMyCustomProvider(facebookProviderOptions);
const facebookProvider = new TnsOaProviderMyCustomProvider(
facebookProviderOptions
);
return facebookProvider;

@@ -332,3 +336,2 @@ }

### Custom URL Scheme

@@ -335,0 +338,0 @@

@@ -1,2 +0,2 @@

/// <reference path="./node_modules/tns-platform-declarations/ios.d.ts" />
/// <reference path="./node_modules/tns-platform-declarations/android.d.ts" />
/// <reference path="./node_modules/@nativescript/types/index.d.ts" />
/// <reference path="./providers/providers.d.ts" />

@@ -1,5 +0,3 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var TnsOAuthState = (function () {
function TnsOAuthState(codeVerifier, isLogout, loginCompletion, urlScheme) {
export class TnsOAuthState {
constructor(codeVerifier, isLogout, loginCompletion, urlScheme) {
this._loginCompletion = loginCompletion;

@@ -10,33 +8,15 @@ this._codeVerifier = codeVerifier;

}
Object.defineProperty(TnsOAuthState.prototype, "loginCompletion", {
get: function () {
return this._loginCompletion;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TnsOAuthState.prototype, "codeVerifier", {
get: function () {
return this._codeVerifier;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TnsOAuthState.prototype, "urlScheme", {
get: function () {
return this._urlScheme;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TnsOAuthState.prototype, "isLogout", {
get: function () {
return this._isLogout;
},
enumerable: true,
configurable: true
});
return TnsOAuthState;
}());
exports.TnsOAuthState = TnsOAuthState;
get loginCompletion() {
return this._loginCompletion;
}
get codeVerifier() {
return this._codeVerifier;
}
get urlScheme() {
return this._urlScheme;
}
get isLogout() {
return this._isLogout;
}
}
//# sourceMappingURL=tns-oauth-auth-state.js.map

@@ -1,30 +0,18 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var querystring = require("querystring");
var URL = require("url");
var http = require("tns-core-modules/http");
var tns_oauth_utils_1 = require("./tns-oauth-utils");
var accessTokenName = "access_token";
var TnsOAuthClientConnection = (function () {
function TnsOAuthClientConnection() {
import * as querystring from "querystring";
import * as URL from "url";
import { Http } from "@nativescript/core";
import { httpResponseToToken } from "./tns-oauth-utils";
const accessTokenName = "access_token";
export class TnsOAuthClientConnection {
get client() {
return this._client;
}
Object.defineProperty(TnsOAuthClientConnection.prototype, "client", {
get: function () {
return this._client;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TnsOAuthClientConnection.prototype, "completion", {
get: function () {
return this._completion;
},
enumerable: true,
configurable: true
});
TnsOAuthClientConnection.initWithRequestClientCompletion = function (client, completion) {
get completion() {
return this._completion;
}
static initWithRequestClientCompletion(client, completion) {
return TnsOAuthClientConnection.initWithRequestClientFeaturesCompletion(client, 0, completion);
};
TnsOAuthClientConnection.initWithRequestClientFeaturesCompletion = function (client, features, completion) {
var instance = new TnsOAuthClientConnection();
}
static initWithRequestClientFeaturesCompletion(client, features, completion) {
const instance = new TnsOAuthClientConnection();
if (instance) {

@@ -35,49 +23,45 @@ instance._client = client;

return instance;
};
TnsOAuthClientConnection.prototype.startGetTokenFromCode = function (authCode) {
}
startGetTokenFromCode(authCode) {
this.getTokenFromCode(this.client, authCode, this.completion);
};
TnsOAuthClientConnection.prototype.startTokenRevocation = function () {
var _this = this;
var revokeUrl = this.client.provider.authority + this.client.provider.revokeEndpoint;
var headers = {
"Content-Type": "application/x-www-form-urlencoded"
}
startTokenRevocation() {
const revokeUrl = this.client.provider.authority + this.client.provider.revokeEndpoint;
const headers = {
"Content-Type": "application/x-www-form-urlencoded",
};
var body = querystring.stringify({
token: this.client.tokenResult.refreshToken
const body = querystring.stringify({
token: this.client.tokenResult.refreshToken,
});
http
.request({
Http.request({
url: revokeUrl,
method: "POST",
headers: headers,
content: body
})
.then(function (response) {
content: body,
}).then((response) => {
if (response.statusCode !== 200) {
_this.completion(null, response, new Error("Failed logout with status " + response.statusCode + "."));
this.completion(null, response, new Error(`Failed logout with status ${response.statusCode}.`));
}
else {
_this.completion(null, response, null);
this.completion(null, response, null);
}
}, function (error) { return _this.completion(null, null, error); });
};
TnsOAuthClientConnection.prototype.startTokenRefresh = function () {
var _this = this;
var tokenUrl = this.client.provider.authority + this.client.provider.tokenEndpoint;
var headers = {
"Content-Type": "application/x-www-form-urlencoded"
}, (error) => this.completion(null, null, error));
}
startTokenRefresh() {
const tokenUrl = this.client.provider.authority + this.client.provider.tokenEndpoint;
const headers = {
"Content-Type": "application/x-www-form-urlencoded",
};
var body = null;
let body = null;
switch (this.client.provider.options.openIdSupport) {
case "oid-full":
var options1 = (this.client.provider.options);
const options1 = (this.client.provider.options);
body = querystring.stringify({
grant_type: "refresh_token",
refresh_token: this.client.tokenResult.refreshToken,
client_id: options1.clientId
client_id: options1.clientId,
});
break;
case "oid-none":
var options2 = (this.client.provider.options);
const options2 = (this.client.provider.options);
body = querystring.stringify({

@@ -87,32 +71,30 @@ grant_type: "refresh_token",

client_id: options2.clientId,
client_secret: options2.clientSecret
client_secret: options2.clientSecret,
});
}
http
.request({
Http.request({
url: tokenUrl,
method: "POST",
headers: headers,
content: body
})
.then(function (response) {
content: body,
}).then((response) => {
if (response.statusCode !== 200) {
_this.completion(null, response, new Error("Failed refresh token with status " + response.statusCode + "."));
this.completion(null, response, new Error(`Failed refresh token with status ${response.statusCode}.`));
}
else {
_this.completion(null, response, null);
this.completion(null, response, null);
}
}, function (error) { return _this.completion(null, null, error); });
};
TnsOAuthClientConnection.prototype.getTokenFromCode = function (client, code, completion) {
var oauthParams = {
grant_type: "authorization_code"
}, (error) => this.completion(null, null, error));
}
getTokenFromCode(client, code, completion) {
let oauthParams = {
grant_type: "authorization_code",
};
return this.getOAuthAccessToken(client, code, oauthParams, completion);
};
TnsOAuthClientConnection.prototype.getAccessTokenUrl = function (client) {
var oauth2 = null;
}
getAccessTokenUrl(client) {
let oauth2 = null;
switch (client.provider.options.openIdSupport) {
case "oid-full":
var options1 = client.provider.options;
const options1 = client.provider.options;
oauth2 = {

@@ -123,7 +105,7 @@ clientId: options1.clientId,

authorizePath: client.provider.authorizeEndpoint,
accessTokenPath: client.provider.tokenEndpoint
accessTokenPath: client.provider.tokenEndpoint,
};
break;
case "oid-none":
var options2 = client.provider.options;
const options2 = client.provider.options;
oauth2 = {

@@ -135,14 +117,14 @@ clientId: options2.clientId,

authorizePath: client.provider.authorizeEndpoint,
accessTokenPath: client.provider.tokenEndpoint
accessTokenPath: client.provider.tokenEndpoint,
};
}
var _clientId = oauth2.clientId;
var _clientSecret = oauth2.clientSecret;
var _baseSite = oauth2.baseSite;
var _baseSiteToken = oauth2.baseSiteToken;
var _authorizeUrl = oauth2.authorizePath || "/oauth/authorize";
var _accessTokenUrl = oauth2.accessTokenPath || "/oauth/access_token";
var _accessTokenName = "access_token";
var _authMethod = "Bearer";
var _useAuthorizationHeaderForGET = false;
const _clientId = oauth2.clientId;
const _clientSecret = oauth2.clientSecret;
const _baseSite = oauth2.baseSite;
const _baseSiteToken = oauth2.baseSiteToken;
const _authorizeUrl = oauth2.authorizePath || "/oauth/authorize";
const _accessTokenUrl = oauth2.accessTokenPath || "/oauth/access_token";
const _accessTokenName = "access_token";
const _authMethod = "Bearer";
const _useAuthorizationHeaderForGET = false;
if (_baseSiteToken && _baseSiteToken !== "") {

@@ -154,9 +136,8 @@ return _baseSiteToken + _accessTokenUrl;

}
};
TnsOAuthClientConnection.prototype.getOAuthAccessToken = function (client, code, parameters, completion) {
var _this = this;
var params = parameters || {};
}
getOAuthAccessToken(client, code, parameters, completion) {
const params = parameters || {};
params["client_id"] = client.provider.options.clientId;
if (client.provider.options.openIdSupport === "oid-none") {
var options = client.provider.options;
const options = client.provider.options;
if (options.clientSecret && options.clientSecret !== "") {

@@ -166,3 +147,3 @@ params["client_secret"] = options.clientSecret;

}
var codeParam = params.grant_type === "refresh_token" ? "refresh_token" : "code";
const codeParam = params.grant_type === "refresh_token" ? "refresh_token" : "code";
params[codeParam] = code;

@@ -172,28 +153,28 @@ if (client.codeVerifier) {

}
params['redirect_uri'] = client.provider.options.redirectUri;
var post_data = querystring.stringify(params);
var post_headers = {
"Content-Type": "application/x-www-form-urlencoded"
params["redirect_uri"] = client.provider.options.redirectUri;
let post_data = querystring.stringify(params);
const post_headers = {
"Content-Type": "application/x-www-form-urlencoded",
};
var accessTokenUrl = this.getAccessTokenUrl(client);
return new Promise(function (resolve, reject) {
_this._createRequest("POST", accessTokenUrl, post_headers, post_data, null)
.then(function (response) {
var tokenResult = tns_oauth_utils_1.httpResponseToToken(response);
const accessTokenUrl = this.getAccessTokenUrl(client);
return new Promise((resolve, reject) => {
this._createRequest("POST", accessTokenUrl, post_headers, post_data, null)
.then((response) => {
let tokenResult = httpResponseToToken(response);
completion(tokenResult, response);
resolve(response);
})
.catch(function (er) {
.catch((er) => {
reject(er);
});
});
};
TnsOAuthClientConnection.prototype._createRequest = function (method, url, headers, post_body, access_token) {
var parsedUrl = URL.parse(url, true);
var realHeaders = {};
for (var key in this._customHeaders) {
}
_createRequest(method, url, headers, post_body, access_token) {
const parsedUrl = URL.parse(url, true);
const realHeaders = {};
for (let key in this._customHeaders) {
realHeaders[key] = this._customHeaders[key];
}
if (headers) {
for (var key in headers) {
for (let key in headers) {
realHeaders[key] = headers[key];

@@ -209,7 +190,7 @@ }

}
var queryStr = querystring.stringify(parsedUrl.query);
let queryStr = querystring.stringify(parsedUrl.query);
if (queryStr) {
queryStr = "?" + queryStr;
}
var options = {
const options = {
host: parsedUrl.hostname,

@@ -219,18 +200,16 @@ port: parsedUrl.port,

method: method,
headers: realHeaders
headers: realHeaders,
};
return this._executeRequest(options, url, post_body);
};
TnsOAuthClientConnection.prototype._executeRequest = function (options, url, post_body) {
var promise = http.request({
}
_executeRequest(options, url, post_body) {
const promise = Http.request({
url: url,
method: options.method,
headers: options.headers,
content: post_body
content: post_body,
});
return promise;
};
return TnsOAuthClientConnection;
}());
exports.TnsOAuthClientConnection = TnsOAuthClientConnection;
}
}
//# sourceMappingURL=tns-oauth-client-connection.js.map

@@ -1,37 +0,36 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var pkce_util_1 = require("./pkce-util");
var tns_oauth_auth_state_1 = require("./tns-oauth-auth-state");
var tns_oauth_client_connection_1 = require("./tns-oauth-client-connection");
var tns_oauth_utils_1 = require("./tns-oauth-utils");
var TnsOAuthLoginSubController = (function () {
function TnsOAuthLoginSubController(client) {
import { getCodeVerifier, sha256base64encoded } from "./pkce-util";
import { TnsOAuthState } from "./tns-oauth-auth-state";
import { TnsOAuthClientConnection } from "./tns-oauth-client-connection";
import { authorizationCodeFromRedirectUrl, getAccessTokenUrlWithCodeStr, getAuthUrlStr, getLogoutUrlStr, } from "./tns-oauth-utils";
export class TnsOAuthLoginSubController {
constructor(client) {
this.client = client;
}
TnsOAuthLoginSubController.prototype.preLoginSetup = function (frame, urlScheme, completion) {
preLoginSetup(frame, urlScheme, completion) {
this.frame = frame;
if (this.authState) {
var error = "Login failed because another login operation in progress.";
const error = "Login failed because another login operation in progress.";
completion(null, error);
}
var codeChallenge;
let codeChallenge;
if (this.client.pkce) {
this.client.codeVerifier = pkce_util_1.getCodeVerifier();
codeChallenge = pkce_util_1.sha256base64encoded(this.client.codeVerifier);
this.client.codeVerifier = getCodeVerifier();
codeChallenge = sha256base64encoded(this.client.codeVerifier);
}
this.authState = new tns_oauth_auth_state_1.TnsOAuthState(this.client.codeVerifier, false, completion);
return tns_oauth_utils_1.getAuthUrlStr(this.client.provider, codeChallenge);
};
TnsOAuthLoginSubController.prototype.preLogoutSetup = function (frame, urlScheme, completion) {
this.authState = new TnsOAuthState(this.client.codeVerifier, false, completion);
return getAuthUrlStr(this.client.provider, codeChallenge);
}
preLogoutSetup(frame, urlScheme, completion) {
this.frame = frame;
if (this.authState) {
var error = "Logout failed because another logout operation is in progress.";
const error = "Logout failed because another logout operation is in progress.";
completion(error);
}
this.authState = new tns_oauth_auth_state_1.TnsOAuthState(this.client.codeVerifier, true, completion);
return tns_oauth_utils_1.getLogoutUrlStr(this.client.provider, this.client);
};
TnsOAuthLoginSubController.prototype.resumeWithUrl = function (url, completion) {
this.authState = new TnsOAuthState(this.client.codeVerifier, true, completion);
return getLogoutUrlStr(this.client.provider, this.client);
}
resumeWithUrl(url, completion) {
if (this.authState) {
if (this.authState.isLogout && url === this.client.provider.options.redirectUri) {
if (this.authState.isLogout &&
url === this.client.provider.options.redirectUri) {
this.client.logout();

@@ -42,3 +41,3 @@ completion(undefined);

else {
var codeExchangeRequestUrl = this.codeExchangeRequestUrlFromRedirectUrl(url);
const codeExchangeRequestUrl = this.codeExchangeRequestUrlFromRedirectUrl(url);
if (codeExchangeRequestUrl) {

@@ -51,38 +50,38 @@ this.codeExchangeWithUrlCompletion(codeExchangeRequestUrl, completion);

return false;
};
TnsOAuthLoginSubController.prototype.codeExchangeRequestUrlFromRedirectUrl = function (url) {
var codeExchangeUrl = null;
var isRedirectUrlValid = true;
}
codeExchangeRequestUrlFromRedirectUrl(url) {
let codeExchangeUrl = null;
const isRedirectUrlValid = true;
if (isRedirectUrlValid) {
var authorizationCode = tns_oauth_utils_1.authorizationCodeFromRedirectUrl(url);
const authorizationCode = authorizationCodeFromRedirectUrl(url);
if (authorizationCode) {
this.authState.authCode = authorizationCode;
codeExchangeUrl = tns_oauth_utils_1.getAccessTokenUrlWithCodeStr(this.client.provider, authorizationCode);
codeExchangeUrl = getAccessTokenUrlWithCodeStr(this.client.provider, authorizationCode);
}
}
return codeExchangeUrl;
};
TnsOAuthLoginSubController.prototype.codeExchangeWithUrlCompletion = function (url, completion) {
var _this = this;
var responseCompletion;
}
codeExchangeWithUrlCompletion(url, completion) {
let responseCompletion;
if (completion) {
responseCompletion = function (data, response, responseError) {
if ((response.statusCode === 200 || (data && data.accessToken)) && !responseError) {
var tokenResult = _this.client.provider.parseTokenResult(data);
_this.client.tokenResult = tokenResult;
responseCompletion = (data, response, responseError) => {
if ((response.statusCode === 200 || (data && data.accessToken)) &&
!responseError) {
const tokenResult = this.client.provider.parseTokenResult(data);
this.client.tokenResult = tokenResult;
completion(tokenResult, null);
}
else {
var msg_1 = (response ? response.statusCode : '') + " ERROR Occurred";
console.error(msg_1);
completion(null, responseError ? responseError : new Error(msg_1));
const msg = `${response ? response.statusCode : ""} ERROR Occurred`;
console.error(msg);
completion(null, responseError ? responseError : new Error(msg));
}
};
}
var connection = tns_oauth_client_connection_1.TnsOAuthClientConnection.initWithRequestClientCompletion(this.client, responseCompletion);
const connection = TnsOAuthClientConnection.initWithRequestClientCompletion(this.client, responseCompletion);
connection.startGetTokenFromCode(this.authState.authCode);
};
TnsOAuthLoginSubController.prototype.completeLoginWithTokenResponseError = function (tokenResult, responseError) {
}
completeLoginWithTokenResponseError(tokenResult, responseError) {
if (this.authState) {
var loginCompletion = this.authState
const loginCompletion = this.authState
.loginCompletion;

@@ -92,6 +91,4 @@ this.authState = null;

}
};
return TnsOAuthLoginSubController;
}());
exports.TnsOAuthLoginSubController = TnsOAuthLoginSubController;
}
}
//# sourceMappingURL=tns-oauth-login-sub-controller.js.map

@@ -1,68 +0,60 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var web_view_1 = require("tns-core-modules/ui/web-view");
var application_1 = require("tns-core-modules/application");
var page_1 = require("tns-core-modules/ui/page");
var grid_layout_1 = require("tns-core-modules/ui/layouts/grid-layout");
var action_bar_1 = require("tns-core-modules/ui/action-bar/action-bar");
var tns_oauth_login_sub_controller_1 = require("./tns-oauth-login-sub-controller");
var SOFT_INPUT_ADJUST_RESIZE = 16;
var TnsOAuthLoginWebViewController = (function () {
function TnsOAuthLoginWebViewController() {
import { Application, Page, GridLayout, NavigationButton, WebView, } from "@nativescript/core";
import { TnsOAuthLoginSubController, } from "./tns-oauth-login-sub-controller";
const SOFT_INPUT_ADJUST_RESIZE = 16;
export class TnsOAuthLoginWebViewController {
constructor() {
this.loginController = null;
}
TnsOAuthLoginWebViewController.initWithClient = function (client) {
var instance = new TnsOAuthLoginWebViewController();
static initWithClient(client) {
const instance = new TnsOAuthLoginWebViewController();
if (instance) {
instance.loginController = new tns_oauth_login_sub_controller_1.TnsOAuthLoginSubController(client);
instance.loginController = new TnsOAuthLoginSubController(client);
}
return instance;
};
TnsOAuthLoginWebViewController.prototype.loginWithParametersFrameCompletion = function (parameters, frame, urlScheme, completion) {
var fullUrl = this.loginController.preLoginSetup(frame, urlScheme, completion);
}
loginWithParametersFrameCompletion(parameters, frame, urlScheme, completion) {
const fullUrl = this.loginController.preLoginSetup(frame, urlScheme, completion);
this.openUrlWithParametersCompletion(fullUrl, frame);
};
TnsOAuthLoginWebViewController.prototype.logoutWithParametersFrameCompletion = function (parameters, frame, urlScheme, completion) {
var fullUrl = this.loginController.preLogoutSetup(frame, urlScheme, completion);
}
logoutWithParametersFrameCompletion(parameters, frame, urlScheme, completion) {
const fullUrl = this.loginController.preLogoutSetup(frame, urlScheme, completion);
this.openUrlWithParametersCompletion(fullUrl, frame);
};
TnsOAuthLoginWebViewController.prototype.openUrlWithParametersCompletion = function (fullUrl, frame) {
}
openUrlWithParametersCompletion(fullUrl, frame) {
this.goToWebViewPage(frame, fullUrl);
};
TnsOAuthLoginWebViewController.prototype.goToWebViewPage = function (frame, url) {
var _this = this;
frame.navigate(function () { return _this.createWebViewPage(url); });
};
TnsOAuthLoginWebViewController.prototype.createWebViewPage = function (url) {
var _this = this;
var webView = this.createWebView(url, this.pageLoadStarted.bind(this), this.pageLoadFinished.bind(this));
var grid = new grid_layout_1.GridLayout();
}
goToWebViewPage(frame, url) {
frame.navigate(() => this.createWebViewPage(url));
}
createWebViewPage(url) {
const webView = this.createWebView(url, this.pageLoadStarted.bind(this), this.pageLoadFinished.bind(this));
const grid = new GridLayout();
grid.addChild(webView);
var page = new page_1.Page();
const page = new Page();
page.content = grid;
if (page_1.isAndroid) {
if (global.isAndroid) {
page.actionBarHidden = true;
page.on("navigatedTo", function () {
_this.setAndroidSoftInputModeToResize();
page.on("navigatedTo", () => {
this.setAndroidSoftInputModeToResize();
webView.android.getSettings().setDomStorageEnabled(true);
webView.android.getSettings().setBuiltInZoomControls(false);
});
page.on("navigatingFrom", function () {
_this.restoreAndroidSoftInputMode();
page.on("navigatingFrom", () => {
this.restoreAndroidSoftInputMode();
});
}
else {
var navBtn = new action_bar_1.NavigationButton();
const navBtn = new NavigationButton();
navBtn.text = "";
page.actionBar.navigationButton = navBtn;
}
var onCancel = function () {
_this.loginController.completeLoginWithTokenResponseError(null, new Error("User cancelled."));
const onCancel = () => {
this.loginController.completeLoginWithTokenResponseError(null, new Error("User cancelled."));
};
page.on("navigatedFrom", onCancel);
this.unbindCancelEvent = function () { return page.off("navigatedFrom", onCancel); };
this.unbindCancelEvent = () => page.off("navigatedFrom", onCancel);
return page;
};
TnsOAuthLoginWebViewController.prototype.createWebView = function (url, loadStarted, loadFinished) {
var webView = new web_view_1.WebView();
}
createWebView(url, loadStarted, loadFinished) {
const webView = new WebView();
webView.on("loadStarted", loadStarted);

@@ -72,37 +64,34 @@ webView.on("loadFinished", loadFinished);

return webView;
};
TnsOAuthLoginWebViewController.prototype.resumeWithUrl = function (url) {
var _this = this;
return this.loginController.resumeWithUrl(url, function (tokenResult, error) {
_this.loginController.completeLoginWithTokenResponseError(tokenResult, error);
if (_this.unbindCancelEvent) {
_this.unbindCancelEvent();
}
resumeWithUrl(url) {
return this.loginController.resumeWithUrl(url, (tokenResult, error) => {
this.loginController.completeLoginWithTokenResponseError(tokenResult, error);
if (this.unbindCancelEvent) {
this.unbindCancelEvent();
}
_this.loginController.frame.goBack();
this.loginController.frame.goBack();
});
};
TnsOAuthLoginWebViewController.prototype.pageLoadStarted = function (args) {
}
pageLoadStarted(args) {
console.log("WebView loadStarted " + args.url);
if (args.url.startsWith(this.loginController.client.provider.options.redirectUri)) {
if (page_1.isAndroid && args.object && args.object['stopLoading']) {
args.object['stopLoading']();
if (global.isAndroid && args.object && args.object["stopLoading"]) {
args.object["stopLoading"]();
}
this.resumeWithUrl(args.url);
}
};
TnsOAuthLoginWebViewController.prototype.pageLoadFinished = function (args) {
}
pageLoadFinished(args) {
console.log("WebView loadFinished " + args.url);
};
TnsOAuthLoginWebViewController.prototype.setAndroidSoftInputModeToResize = function () {
var window = application_1.android.foregroundActivity.getWindow();
}
setAndroidSoftInputModeToResize() {
const window = Application.android.foregroundActivity.getWindow();
this.originalSoftInputMode = window.getAttributes().softInputMode;
window.setSoftInputMode(SOFT_INPUT_ADJUST_RESIZE);
};
TnsOAuthLoginWebViewController.prototype.restoreAndroidSoftInputMode = function () {
var window = application_1.android.foregroundActivity.getWindow();
}
restoreAndroidSoftInputMode() {
const window = Application.android.foregroundActivity.getWindow();
window.setSoftInputMode(this.originalSoftInputMode);
};
return TnsOAuthLoginWebViewController;
}());
exports.TnsOAuthLoginWebViewController = TnsOAuthLoginWebViewController;
}
}
//# sourceMappingURL=tns-oauth-login-webview-controller.js.map

@@ -1,52 +0,48 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var appModule = require("tns-core-modules/application");
var colorModule = require("tns-core-modules/color");
var tns_oauth_login_sub_controller_1 = require("./tns-oauth-login-sub-controller");
import { Application, Color } from "@nativescript/core";
import { TnsOAuthLoginSubController, } from "./tns-oauth-login-sub-controller";
function useAndroidX() {
return global.androidx && global.androidx.appcompat;
}
var customtabs = useAndroidX() ? androidx.browser.customtabs : android.support.customtabs;
var TnsOAuthLoginNativeViewController = (function () {
function TnsOAuthLoginNativeViewController() {
const customtabs = useAndroidX()
? androidx.browser.customtabs
: android.support.customtabs;
export class TnsOAuthLoginNativeViewController {
constructor() {
this.loginController = null;
}
TnsOAuthLoginNativeViewController.initWithClient = function (client) {
var instance = new TnsOAuthLoginNativeViewController();
static initWithClient(client) {
const instance = new TnsOAuthLoginNativeViewController();
if (instance) {
instance.loginController = new tns_oauth_login_sub_controller_1.TnsOAuthLoginSubController(client);
instance.loginController = new TnsOAuthLoginSubController(client);
}
return instance;
};
TnsOAuthLoginNativeViewController.prototype.loginWithParametersFrameCompletion = function (parameters, frame, urlScheme, completion) {
var fullUrl = this.loginController.preLoginSetup(frame, urlScheme, completion);
}
loginWithParametersFrameCompletion(parameters, frame, urlScheme, completion) {
const fullUrl = this.loginController.preLoginSetup(frame, urlScheme, completion);
this.openUrlWithParametersCompletion(fullUrl, frame);
};
TnsOAuthLoginNativeViewController.prototype.logoutWithParametersFrameCompletion = function (parameters, frame, urlScheme, completion) {
var fullUrl = this.loginController.preLogoutSetup(frame, urlScheme, completion);
}
logoutWithParametersFrameCompletion(parameters, frame, urlScheme, completion) {
const fullUrl = this.loginController.preLogoutSetup(frame, urlScheme, completion);
this.openUrlWithParametersCompletion(fullUrl, frame);
};
TnsOAuthLoginNativeViewController.prototype.openUrlWithParametersCompletion = function (fullUrl, frame) {
var builder = new customtabs.CustomTabsIntent.Builder();
builder.setToolbarColor(new colorModule.Color("#335da0").android);
}
openUrlWithParametersCompletion(fullUrl, frame) {
const builder = new customtabs.CustomTabsIntent.Builder();
builder.setToolbarColor(new Color("#335da0").android);
builder.setShowTitle(true);
var customTabsIntent = builder.build();
customTabsIntent.launchUrl(appModule.android.startActivity, android.net.Uri.parse(fullUrl));
};
TnsOAuthLoginNativeViewController.prototype.resumeWithUrl = function (url) {
var _this = this;
const customTabsIntent = builder.build();
customTabsIntent.launchUrl(Application.android.startActivity, android.net.Uri.parse(fullUrl));
}
resumeWithUrl(url) {
if (!!url) {
return this.loginController.resumeWithUrl(url, function (tokenResult, error) {
_this.loginController.completeLoginWithTokenResponseError(tokenResult, error);
return this.loginController.resumeWithUrl(url, (tokenResult, error) => {
this.loginController.completeLoginWithTokenResponseError(tokenResult, error);
});
}
else {
var er = "The login operation was canceled.";
const er = "The login operation was canceled.";
this.loginController.completeLoginWithTokenResponseError(null, er);
return true;
}
};
return TnsOAuthLoginNativeViewController;
}());
exports.TnsOAuthLoginNativeViewController = TnsOAuthLoginNativeViewController;
}
}
//# sourceMappingURL=tns-oauth-native-view-controller.android.js.map

@@ -1,2 +0,3 @@

import { Frame } from "tns-core-modules/ui/frame";
import { Frame } from "@nativescript/core";
import { ITnsOAuthLoginController } from "./tns-oauth-login-sub-controller";

@@ -3,0 +4,0 @@ import { TnsOAuthClient, TnsOAuthClientLoginBlock } from "./index";

@@ -1,5 +0,4 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tns_oauth_login_sub_controller_1 = require("./tns-oauth-login-sub-controller");
var TnsOAuthLoginNativeViewController = (function (_super) {
import { TnsOAuthLoginSubController, } from "./tns-oauth-login-sub-controller";
function setup() {
var TnsOAuthLoginNativeViewController = /** @class */ (function (_super) {
__extends(TnsOAuthLoginNativeViewController, _super);

@@ -14,3 +13,3 @@ function TnsOAuthLoginNativeViewController() {

if (instance) {
instance.loginController = new tns_oauth_login_sub_controller_1.TnsOAuthLoginSubController(client);
instance.loginController = new TnsOAuthLoginSubController(client);
}

@@ -54,7 +53,10 @@ return instance;

};
// SFSafariViewControllerDelegate delegate members
TnsOAuthLoginNativeViewController.prototype.safariViewControllerDidFinish = function (controller) {
if (controller !== this.safariViewController) {
// Ignore this call if safari view controller doesn't match
return;
}
if (!this.loginController.authState) {
// Ignore this call if there is no pending login flow
return;

@@ -68,3 +70,5 @@ }

}(NSObject));
exports.TnsOAuthLoginNativeViewController = TnsOAuthLoginNativeViewController;
return TnsOAuthLoginNativeViewController;
}
export const TnsOAuthLoginNativeViewController = setup();
//# sourceMappingURL=tns-oauth-native-view-controller.ios.js.map

@@ -1,10 +0,7 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var querystring = require("querystring");
var UrlLib = require("url");
import * as querystring from "querystring";
import * as UrlLib from "url";
function addCustomQueryParams(params, provider) {
var customQueryParams = provider.options.customQueryParams;
const customQueryParams = provider.options.customQueryParams;
if (customQueryParams) {
for (var _i = 0, _a = Object.keys(customQueryParams); _i < _a.length; _i++) {
var paramName = _a[_i];
for (const paramName of Object.keys(customQueryParams)) {
params[paramName] = customQueryParams[paramName];

@@ -14,11 +11,12 @@ }

}
function getAuthUrlStr(provider, codeChallenge) {
export function getAuthUrlStr(provider, codeChallenge) {
if (provider.getAuthUrlStr) {
return provider.getAuthUrlStr();
}
var params = {};
const params = {};
params["client_id"] = provider.options.clientId;
params["response_type"] = "code";
params["redirect_uri"] = provider.options.redirectUri;
params["scope"] = provider.options.scopes && provider.options.scopes.join(' ');
params["scope"] =
provider.options.scopes && provider.options.scopes.join(" ");
params["response_mode"] = "query";

@@ -31,8 +29,7 @@ params["state"] = "abcd";

addCustomQueryParams(params, provider);
var pararmsStr = querystring.stringify(params);
var retAuthUrlStr = provider.authority + provider.authorizeEndpoint + "?" + pararmsStr;
const pararmsStr = querystring.stringify(params);
const retAuthUrlStr = provider.authority + provider.authorizeEndpoint + "?" + pararmsStr;
return retAuthUrlStr;
}
exports.getAuthUrlStr = getAuthUrlStr;
function getLogoutUrlStr(provider, client) {
export function getLogoutUrlStr(provider, client) {
if (provider.getLogoutUrlStr) {

@@ -44,16 +41,15 @@ return provider.getLogoutUrlStr();

}
var params = {};
const params = {};
params["id_token_hint"] = client.tokenResult.idToken;
params["post_logout_redirect_uri"] = provider.options.redirectUri;
addCustomQueryParams(params, provider);
var pararmsStr = querystring.stringify(params);
var retAuthUrlStr = provider.authority + provider.endSessionEndpoint + "?" + pararmsStr;
const pararmsStr = querystring.stringify(params);
const retAuthUrlStr = provider.authority + provider.endSessionEndpoint + "?" + pararmsStr;
return retAuthUrlStr;
}
exports.getLogoutUrlStr = getLogoutUrlStr;
function authorizationCodeFromRedirectUrl(url) {
var authorizationCode = null;
export function authorizationCodeFromRedirectUrl(url) {
let authorizationCode = null;
if (url) {
var parsedRetStr = UrlLib.parse(url);
var qsObj = querystring.parse(parsedRetStr.query);
let parsedRetStr = UrlLib.parse(url);
let qsObj = querystring.parse(parsedRetStr.query);
authorizationCode = qsObj["code"];

@@ -63,5 +59,4 @@ }

}
exports.authorizationCodeFromRedirectUrl = authorizationCodeFromRedirectUrl;
function getAccessTokenUrlStr(provider) {
var retStr = "";
export function getAccessTokenUrlStr(provider) {
let retStr = "";
if (provider.tokenEndpointBase && provider.tokenEndpointBase !== "") {

@@ -75,21 +70,20 @@ retStr = provider.tokenEndpointBase + provider.tokenEndpoint;

}
exports.getAccessTokenUrlStr = getAccessTokenUrlStr;
function getAccessTokenUrlWithCodeStr(provider, authCode) {
export function getAccessTokenUrlWithCodeStr(provider, authCode) {
if (provider.getAccessTokenUrlWithCodeStr) {
return provider.getAccessTokenUrlWithCodeStr(authCode);
}
var params = {};
const params = {};
params["code"] = authCode;
params["client_id"] = provider.options.clientId;
params["client_secret"] = provider.options.clientSecret;
params["scope"] = provider.options.scopes && provider.options.scopes.join(' ');
params["scope"] =
provider.options.scopes && provider.options.scopes.join(" ");
params["state"] = "abcd";
addCustomQueryParams(params, provider);
var pararmsStr = querystring.stringify(params);
var paramsWithRedirectStr = pararmsStr + "&redirect_uri=" + provider.options.redirectUri;
var retAccessTokenWithCodeUrlStr = getAccessTokenUrlStr(provider) + "?" + paramsWithRedirectStr;
const pararmsStr = querystring.stringify(params);
const paramsWithRedirectStr = pararmsStr + "&redirect_uri=" + provider.options.redirectUri;
const retAccessTokenWithCodeUrlStr = getAccessTokenUrlStr(provider) + "?" + paramsWithRedirectStr;
return retAccessTokenWithCodeUrlStr;
}
exports.getAccessTokenUrlWithCodeStr = getAccessTokenUrlWithCodeStr;
function newUUID(a, b) {
export function newUUID(a, b) {
for (b = a = ""; a++ < 36; b +=

@@ -102,5 +96,4 @@ (a * 51) & 52

}
exports.newUUID = newUUID;
function getAuthHeaderFromCredentials(provider) {
var customAuthHeader;
export function getAuthHeaderFromCredentials(provider) {
let customAuthHeader;
if (provider["basicAuthHeader"]) {

@@ -111,8 +104,7 @@ customAuthHeader = { Authorization: provider["basicAuthHeader"] };

}
exports.getAuthHeaderFromCredentials = getAuthHeaderFromCredentials;
function nsArrayToJSArray(a) {
var arr = [];
export function nsArrayToJSArray(a) {
const arr = [];
if ("undefined" !== typeof a) {
var count = a.count;
for (var i = 0; i < count; i++) {
const count = a.count;
for (let i = 0; i < count; i++) {
arr.push(a.objectAtIndex(i));

@@ -123,9 +115,7 @@ }

}
exports.nsArrayToJSArray = nsArrayToJSArray;
function jsArrayToNSArray(str) {
export function jsArrayToNSArray(str) {
return NSArray.arrayWithArray(str);
}
exports.jsArrayToNSArray = jsArrayToNSArray;
function httpResponseToToken(response) {
var results;
export function httpResponseToToken(response) {
let results;
try {

@@ -137,9 +127,9 @@ results = response.content.toJSON();

}
var access_token = results["access_token"];
var refresh_token = results["refresh_token"];
var id_token = results["id_token"];
var expires_in = results["expires_in"];
let access_token = results["access_token"];
let refresh_token = results["refresh_token"];
let id_token = results["id_token"];
let expires_in = results["expires_in"];
delete results["refresh_token"];
var expSecs = Math.floor(parseFloat(expires_in));
var expDate = new Date();
let expSecs = Math.floor(parseFloat(expires_in));
let expDate = new Date();
expDate.setSeconds(expDate.getSeconds() + expSecs);

@@ -152,6 +142,5 @@ return {

refreshTokenExpiration: expDate,
idTokenExpiration: expDate
idTokenExpiration: expDate,
};
}
exports.httpResponseToToken = httpResponseToToken;
//# sourceMappingURL=tns-oauth-utils.js.map
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc