repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
turkaytunc/redux-like
|
src/components/post-list/PostList.tsx
|
import React, { FC } from 'react';
import { Store } from '../../state-store/Store';
const PostList: FC = () => {
const { state, dispatch } = React.useContext(Store);
const [input, setInput] = React.useState('');
const addPost = () => {
const parsed = JSON.parse(input);
if (parsed.hasOwnProperty('id')) {
dispatch({
type: 'ADD_POST',
payload: parsed,
});
}
};
const deletePost = (id: number) => {
dispatch({
type: 'REMOVE_POST',
payload: id,
});
};
return (
<div className="post-container">
<input
type="text"
value={input}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setInput(e.target.value)}
/>
<button onClick={() => addPost()}>Add Post</button>
{state.posts.map((e) => (
<div key={e.id}>
<div>title: {e.title}</div>
<hr />
<div>{e.body}</div>
<button onClick={() => deletePost(e.id)} style={{ fontSize: '2em' }}>
×
</button>
</div>
))}
</div>
);
};
export default PostList;
|
turkaytunc/redux-like
|
src/state-store/Store.tsx
|
import React from 'react';
import { PostActions } from './actions/PostActions';
import { UserActions } from './actions/UserActions';
import { IPost } from './interfaces/IPost';
import { IUser } from './interfaces/IUser';
import { postReducer } from './reducers/postReducer';
import { userReducer } from './reducers/userReducer';
type InitialStateType = {
posts: IPost[];
users: IUser[];
};
const initialState = {
posts: [],
users: [],
};
const rootReducer = ({ posts, users }: InitialStateType, action: PostActions | UserActions) => ({
posts: postReducer(posts, action as PostActions),
users: userReducer(users, action as UserActions),
});
export const Store = React.createContext<{
state: InitialStateType;
dispatch: React.Dispatch<PostActions | UserActions>;
}>({
state: (initialState as unknown) as InitialStateType,
dispatch: () => null,
});
export const StoreProvider: React.FC = (props: { children?: React.ReactNode }): JSX.Element => {
const [state, dispatch] = React.useReducer(rootReducer, (initialState as unknown) as InitialStateType);
return <Store.Provider value={{ state, dispatch }}>{props.children}</Store.Provider>;
};
|
turkaytunc/redux-like
|
src/state-store/actions/UserActions.ts
|
import { IUser } from '../interfaces/IUser';
export type UserActions =
| {
type: 'ADD_USER';
payload: IUser;
}
| {
type: 'REMOVE_USER';
payload: number;
};
|
DjDeveloperr/Keydb
|
mod.ts
|
export * from "./keydb.ts";
export * from "./adapter.ts";
export * from "./memory.ts";
|
DjDeveloperr/Keydb
|
jsonb.ts
|
<reponame>DjDeveloperr/Keydb
import { Buffer } from "https://deno.land/std@0.88.0/node/buffer.ts";
// deno-lint-ignore no-namespace
export namespace JSONB {
// deno-lint-ignore no-explicit-any
export const stringify = function stringify(o: any) {
if ("undefined" == typeof o) return o;
if (o && Buffer.isBuffer(o))
return JSON.stringify(":base64:" + o.toString("base64"));
if (o && o instanceof Map)
return JSON.stringify(":map:" + JSON.stringify(Object.fromEntries(o)));
if (o && o.toJSON) o = o.toJSON();
if (o && "object" === typeof o) {
var s = "";
var array = Array.isArray(o);
s = array ? "[" : "{";
var first = true;
for (var k in o) {
var ignore =
"function" == typeof o[k] || (!array && "undefined" === typeof o[k]);
if (Object.hasOwnProperty.call(o, k) && !ignore) {
if (!first) s += ",";
first = false;
if (array) {
if (o[k] == undefined) s += "null";
else s += stringify(o[k]);
} else if (o[k] !== void 0) {
s += stringify(k) + ":" + stringify(o[k]);
}
}
}
s += array ? "]" : "}";
return s;
} else if ("string" === typeof o) {
return JSON.stringify(/^:/.test(o) ? ":" + o : o);
} else if ("undefined" === typeof o) {
return "null";
} else return JSON.stringify(o);
};
export const parse = function (s: string) {
return JSON.parse(s, function (_, value) {
if ("string" === typeof value) {
if (/^:base64:/.test(value))
return Buffer.from(value.substring(8), "base64");
if (/^:map:/.test(value))
return new Map(Object.entries(JSON.parse(value.substring(5))));
else return /^:/.test(value) ? value.substring(1) : value;
}
return value;
});
};
}
|
DjDeveloperr/Keydb
|
adapter.ts
|
import { ModuleCache } from "https://deno.land/x/module_cache@0.0.3/mod.ts";
export interface KeydbFields {
key: string;
value: string;
ns: string;
ttl: number;
}
/** Interface to be implemented by Adapter Implementations */
export interface Adapter {
/** Promise used to await the adapter to be ready (in some cases connected to Database Server) */
awaitReady?: Promise<Adapter>;
/** Set a value by key name */
set(
key: string,
// deno-lint-ignore no-explicit-any
value: any,
namespace: string,
ttl: number
): this | Promise<this>;
/** Get a value by key name */
get(
key: string,
namespace: string
): KeydbFields | undefined | Promise<KeydbFields | undefined>;
/** Delete a key */
delete(key: string, namespace: string): boolean | Promise<boolean>;
/** Check whether DB has a specific key */
has(key: string, namespace: string): boolean | Promise<boolean>;
/** Clear (delete) all keys. */
clear(namespace: string): this | Promise<this>;
/** Get all keys. */
keys(namespace: string): string[] | Promise<string[]>;
/** Delete all expired keys. Called before read-related operations. */
deleteExpired(namespace: string): void | Promise<void>;
}
export interface AdapterInitializer {
/** Protocol name. For example `sqlite` for `sqlite://path/to/file` */
protocol: string;
/** Initializer method */
init: (uri: URL) => Adapter | Promise<Adapter>;
}
const cache = new ModuleCache("keydb");
/** Namespace to manage Adapters Protocol Registry (for URI-based initialization) */
// deno-lint-ignore no-namespace
export namespace Adapters {
/** Get all registered Adapter protocols */
export function getAll(): AdapterInitializer[] {
return cache.get("adapters") || [];
}
/** Get an Adapter protocol by name */
export function get(protocol: string): AdapterInitializer | undefined {
return getAll().find(
(e) => e.protocol.toLowerCase() == protocol.toLowerCase()
);
}
/** Register a new Adapter Protocol */
export function register(adapter: AdapterInitializer): void {
if (/^[A-Za-z0-9]+$/.test(adapter.protocol) === false)
throw new Error("Bad Adapter protocol. Must have only A-Z, a-z and 0-9.");
const adapters = getAll();
if (
adapters.find(
(e) => e.protocol.toLowerCase() == adapter.protocol.toLowerCase()
)
)
throw new Error("Adapter with this protocol already exists");
adapters.push(adapter);
cache.set("adapters", adapters);
}
}
|
DjDeveloperr/Keydb
|
memory.ts
|
<reponame>DjDeveloperr/Keydb
import { Adapter } from "./adapter.ts";
export class MemoryAdapter implements Adapter {
namespaces: Map<
string,
Map<string, { value: string; ttl: number }>
> = new Map();
checkNamespace(ns: string) {
if (this.namespaces.has(ns)) return;
else this.namespaces.set(ns, new Map());
}
ns(ns: string) {
this.checkNamespace(ns);
return this.namespaces.get(ns);
}
// deno-lint-ignore no-explicit-any
set(k: string, v: any, ns = "", ttl = 0) {
const n = this.ns(ns);
n?.set(k, { value: v, ttl });
return this;
}
get(k: string, ns = "") {
const n = this.ns(ns);
const v = n?.get(k);
return !v ? undefined : { key: k, ns, value: v.value, ttl: v.ttl };
}
has(k: string, ns = "") {
return this.ns(ns)?.has(k) ?? false;
}
delete(k: string, ns = "") {
const n = this.ns(ns);
return n?.delete(k) ?? false;
}
keys(ns = "") {
return [...(this.ns(ns)?.keys() ?? [])];
}
clear(ns = "") {
this.namespaces.set(ns, new Map());
return this;
}
deleteExpired(ns = "") {
const n = this.ns(ns)!;
for (const e of n.entries()) {
if (e[1].ttl !== 0 && Date.now() > e[1].ttl) {
n.delete(e[0]);
}
}
}
}
|
DjDeveloperr/Keydb
|
sqlite.ts
|
import { DB } from "https://deno.land/x/sqlite@v2.3.2/mod.ts";
import { Adapter, Adapters, KeydbFields } from "./adapter.ts";
import { Keydb } from "./keydb.ts";
export class SqliteAdapter implements Adapter {
db: DB;
table: string;
constructor(path?: string, table: string = "keydb") {
this.db = new DB(path);
this.table = table;
this.query(
`CREATE TABLE IF NOT EXISTS ${this.table} (key VARCHAR(255), value TEXT, ns VARCHAR(255), ttl INTEGER)`
);
}
// deno-lint-ignore no-explicit-any
query<T = any>(sql: string, params: any[] = []): T[] {
return [...this.db.query(sql, params).asObjects()] as T[];
}
get(key: string, namespace = ""): KeydbFields | undefined {
const res = this.query<{
key: string;
value: string;
ns: string;
ttl: number;
}>(`SELECT * FROM ${this.table} WHERE key = ? AND ns = ?`, [
key,
namespace,
])[0];
return res;
}
has(key: string, namespace = ""): boolean {
const res = this.query<{ key: string }>(
`SELECT key FROM ${this.table} WHERE key = ? AND ns = ?`,
[key, namespace]
);
return res.length > 0;
}
// deno-lint-ignore no-explicit-any
set(key: string, value: any, namespace = "", ttl = 0): this {
if (this.has(key))
this.query(
`UPDATE ${this.table} SET value = ?, ttl = ? WHERE key = ? AND ns = ?`,
[value, ttl, key, namespace]
);
else
this.query(
`INSERT INTO ${this.table} (key, value, ns, ttl) VALUES (?, ?, ?, ?)`,
[key, value, namespace, ttl]
);
return this;
}
clear(namespace = ""): this {
this.query(`DELETE FROM ${this.table} WHERE ns = ?`, [namespace]);
return this;
}
delete(key: string, namespace = ""): boolean {
if (!this.has(key)) return false;
this.query(`DELETE FROM ${this.table} WHERE key = ? AND ns = ?`, [
key,
namespace,
]);
return true;
}
keys(namespace = ""): string[] {
return this.query<{ key: string }>(
`SELECT key FROM ${this.table} WHERE ns = ?`,
[namespace]
).map((e) => e.key);
}
deleteExpired(namespace = ""): void {
this.query(
`DELETE FROM ${this.table} WHERE ns = ? AND ttl != 0 AND ttl < ?`,
[namespace, Date.now()]
);
}
}
Adapters.register({
protocol: "sqlite",
init(uri) {
let path: string | undefined = uri.toString().slice(7);
if (path.startsWith("//")) path = path.slice(2);
if (path == "memory") path = undefined;
return new SqliteAdapter(path);
},
});
export { Keydb };
|
DjDeveloperr/Keydb
|
keydb.ts
|
<filename>keydb.ts
import { Adapter, Adapters } from "./adapter.ts";
import { JSONB } from "./jsonb.ts";
import { MemoryAdapter } from "./memory.ts";
export interface KeydbOptions {
namespace?: string;
ttl?: number;
// deno-lint-ignore no-explicit-any
serialize?: (value: any) => string | undefined;
// deno-lint-ignore no-explicit-any
deserialize?: (value: string) => any;
}
function tryParseURL(q: string) {
try {
return new URL(q);
} catch (e) {
return;
}
}
/** Simple and common Key-value storage interface for multiple Database backends. */
export class Keydb {
adapter?: Adapter;
awaitReady?: Promise<Adapter>;
namespace = "";
// deno-lint-ignore no-explicit-any
serialize: (value: any) => string | undefined = JSONB.stringify;
// deno-lint-ignore no-explicit-any
deserialize: (value: string) => any = JSONB.parse;
ttl?: number;
constructor(
adapter: Adapter | string = new MemoryAdapter(),
options?: KeydbOptions
) {
this.adapter = typeof adapter === "object" ? adapter : undefined;
if (this.adapter === undefined && typeof adapter !== "object") {
const proto = tryParseURL(adapter);
if (!proto) throw new Error("Invalid Adapter Connection URI");
const protocol = proto.protocol;
const adp = Adapters.get(protocol.substr(0, protocol.length - 1));
if (!adp) throw new Error(`Adapter not found for Protocol: ${protocol}`);
const res = adp.init(proto);
if (res instanceof Promise) {
this.awaitReady = res.then((a) => {
this.adapter = a;
this.awaitReady = undefined;
return a;
});
} else this.adapter = res;
}
this.namespace = options?.namespace ?? "";
if (options?.serialize) this.serialize = options.serialize;
if (options?.deserialize) this.deserialize = options.deserialize;
if (options?.ttl) this.ttl = options.ttl;
}
/**
* Get a Value by Key name.
*
* @param key Name of Key to get Value.
*/
// deno-lint-ignore no-explicit-any
async get<T = any>(key: string): Promise<T | undefined> {
if (this.awaitReady) await this.awaitReady;
await this.adapter?.deleteExpired(this.namespace);
const val = await this.adapter?.get(key, this.namespace);
if (val == undefined) return undefined;
const res = this.deserialize(val.value);
return res;
}
/**
* Set a Key's Value.
*
* @param key Name of the Key to set.
* @param value Value to set.
*/
// deno-lint-ignore no-explicit-any
async set(key: string, value: any, ttl?: number): Promise<this> {
if (this.awaitReady) await this.awaitReady;
const _ttl = ttl ?? this.ttl;
value = {
value,
ttl: _ttl && typeof _ttl === "number" ? Date.now() + _ttl : undefined,
};
await this.adapter?.set(
key,
this.serialize(value.value),
this.namespace,
value.ttl
);
return this;
}
/**
* Delete a Key from Database.
*
* @param key Name of the Key to delete.
*/
async delete(key: string): Promise<boolean> {
if (this.awaitReady) await this.awaitReady;
return (await this.adapter?.delete(key, this.namespace)) ?? false;
}
/** Clear complete Database. */
async clear(): Promise<this> {
if (this.awaitReady) await this.awaitReady;
await this.adapter?.clear(this.namespace);
return this;
}
/** Get an Array of all Key Names. */
async keys(): Promise<string[]> {
if (this.awaitReady) await this.awaitReady;
await this.adapter?.deleteExpired(this.namespace);
const keys = (await this.adapter?.keys(this.namespace)) ?? [];
return keys;
}
}
|
DjDeveloperr/Keydb
|
test.ts
|
import { Keydb } from "./sqlite.ts";
import { assertEquals } from "https://deno.land/std@0.86.0/testing/asserts.ts";
const sleep = (ms: number) => new Promise((res) => setTimeout(res, ms));
let db: Keydb;
Deno.test({
name: "Connect to DB",
sanitizeResources: false,
async fn() {
db = new Keydb("sqlite://test.sqlite");
await db.awaitReady;
},
});
Deno.test({
name: "Clear DB",
async fn() {
await db.clear();
const keys = await db.keys();
assertEquals(keys.length, 0);
},
});
Deno.test({
name: "Set values",
async fn() {
await db.set("test_string", "hello world");
await db.set("test_number", 69);
await db.set("test_json", { hello: "world", cool: true, rate: 100 });
const map = new Map();
map.set("key", "value");
await db.set("test_map", map);
const keys = await db.keys();
assertEquals(keys.length, 4);
},
});
Deno.test({
name: "Get Values",
async fn() {
const testString = await db.get("test_string");
assertEquals(testString, "hello world");
const testNumber = await db.get("test_number");
assertEquals(testNumber, 69);
const testJson = await db.get("test_json");
assertEquals(typeof testJson, "object");
const testMap = await db.get("test_map");
assertEquals("value", testMap.get("key"));
},
});
Deno.test({
name: "Delete Key",
async fn() {
let testNumber = await db.get("test_number");
assertEquals(testNumber, 69);
await db.delete("test_number");
testNumber = await db.get("test_number");
assertEquals(testNumber, undefined);
const keys = await db.keys();
assertEquals(keys.length, 3);
},
});
Deno.test({
name: "TTL Values",
async fn() {
await db.set("test_ttl", "exists", 500);
assertEquals("exists", await db.get("test_ttl"));
await sleep(500);
assertEquals(undefined, await db.get("test_ttl"));
},
});
Deno.test({
name: "Clean Up",
async fn() {
await db.clear();
const keys = await db.keys();
assertEquals(keys.length, 0);
await Deno.remove("test.sqlite");
},
});
|
DjDeveloperr/Keydb
|
postgres.ts
|
<filename>postgres.ts<gh_stars>1-10
import { Client } from "https://deno.land/x/postgres@v0.7.1/mod.ts";
import { ConnectionOptions } from "https://deno.land/x/postgres@v0.7.1/connection_params.ts";
import { Adapter, Adapters, KeydbFields } from "./adapter.ts";
import { Keydb } from "./keydb.ts";
export class PostgresAdapter implements Adapter {
db: Client;
table: string;
constructor(client: Client, table: string = "keydb") {
this.db = client;
this.table = table;
}
/** Connect to a Postgres Database and create Adapter. */
static async connect(dbOptions?: ConnectionOptions | string, table?: string) {
const client = new Client(dbOptions);
await client.connect();
const res = new PostgresAdapter(client, table);
const exists = res
.query(`SELECT key FROM ${res.table} LIMIT 1`)
.then(() => true)
.catch(() => false);
if (!exists)
await res.query(
`CREATE TABLE IF NOT EXISTS ${res.table} (key VARCHAR(255) PRIMARY KEY, value TEXT, ns VARCHAR(255), ttl BIGINT)`
);
return res;
}
// deno-lint-ignore no-explicit-any
async query<T = any>(sql: string, params: any[] = []): Promise<T[]> {
const res = await this.db.queryObject(sql, ...params);
return [...res.rows] as T[];
}
async get(key: string, namespace = ""): Promise<KeydbFields | undefined> {
return await this.query<{
key: string;
value: string;
ns: string;
ttl: number;
}>(`SELECT * FROM ${this.table} WHERE key = $1 AND ns = $2`, [
key,
namespace,
]).then((r) => (r.length == 0 ? undefined : r[0]));
}
async has(key: string, namespace = ""): Promise<boolean> {
const res = await this.query<{ key: string }>(
`SELECT key FROM ${this.table} WHERE key = $1 AND ns = $2`,
[key, namespace]
);
return res.length > 0;
}
async set(
key: string,
// deno-lint-ignore no-explicit-any
value: any,
namespace = "",
ttl = 0
): Promise<this> {
const has = await this.has(key);
if (has)
await this.query(
`UPDATE ${this.table} SET value = $1, ttl = $4 WHERE key = $2 AND ns = $3`,
[value, key, namespace, ttl]
);
else
await this.query(
`INSERT INTO ${this.table} (key, value, ns, ttl) VALUES ($1, $2, $3, $4)`,
[key, value, namespace, ttl]
);
return this;
}
async clear(namespace = ""): Promise<this> {
await this.query(`DELETE FROM ${this.table} WHERE ns = $1`, [namespace]);
return this;
}
async delete(key: string, namespace = ""): Promise<boolean> {
const has = await this.has(key);
if (!has) return false;
this.query(`DELETE FROM ${this.table} WHERE key = $1 AND ns = $2`, [
key,
namespace,
]);
return true;
}
async keys(namespace = ""): Promise<string[]> {
return (
await this.query<{ key: string }>(
`SELECT key FROM ${this.table} WHERE ns = $1`,
[namespace]
)
).map((e) => e.key);
}
async deleteExpired(namespace = ""): Promise<void> {
await this.query(
`DELETE FROM ${this.table} WHERE ttl != 0 AND ttl < $1 AND ns = $2`,
[Date.now(), namespace]
);
}
}
Adapters.register({
protocol: "postgres",
init(uri) {
return PostgresAdapter.connect(uri.toString());
},
});
export { Keydb };
|
DjDeveloperr/Keydb
|
redis.ts
|
// Redis Adapter is untested and incomplete!
import {
connect,
Redis,
RedisConnectOptions,
} from "https://deno.land/x/redis@v0.18.0/mod.ts";
import { Adapter, Adapters, KeydbFields } from "./adapter.ts";
import { Keydb } from "./keydb.ts";
export class RedisAdapter implements Adapter {
db: Redis;
table: string;
constructor(client: Redis, table: string = "") {
this.db = client;
this.table = table;
}
/** Connect to a Postgres Database and create Adapter. */
static async connect(dbOptions: RedisConnectOptions, table?: string) {
const client = await connect(dbOptions);
const res = new RedisAdapter(client, table);
return res;
}
getPrefixedKey(key: string, ns = "") {
return `${ns}:${key}`;
}
async get(key: string, namespace = ""): Promise<KeydbFields | undefined> {
const res = await this.db.hgetall(this.getPrefixedKey(key, namespace));
if (res.length === 0) return undefined;
return {
key: res[0],
value: res[1],
ns: res[2],
ttl: Number(res[3]),
};
}
async has(key: string, namespace = ""): Promise<boolean> {
const res = await this.db.hget(this.getPrefixedKey(key, namespace), "key");
return res !== undefined;
}
async set(
key: string,
// deno-lint-ignore no-explicit-any
value: any,
namespace = "",
ttl = 0
): Promise<this> {
key = this.getPrefixedKey(key, namespace);
const fields: [string, string][] = [
["key", key],
["value", value],
["ns", namespace],
["ttl", ttl.toString()],
];
await this.db.hset(key, ...fields);
if (ttl !== 0)
await this.db.expireat(
this.getPrefixedKey(key, namespace),
(ttl / 1000).toString()
);
return this;
}
async clear(namespace = ""): Promise<this> {
const keys = await this.keys(namespace);
if (keys.length !== 0) await this.db.del(...keys);
return this;
}
async delete(key: string, namespace = ""): Promise<boolean> {
const has = await this.has(key);
if (!has) return false;
await this.db.del(this.getPrefixedKey(key, namespace));
return true;
}
async keys(namespace = ""): Promise<string[]> {
return await this.db.keys(`${namespace}:*`);
}
async deleteExpired(_namespace = ""): Promise<void> {}
}
Adapters.register({
protocol: "redis",
init(uri) {
return RedisAdapter.connect({
hostname: uri.hostname,
password: uri.searchParams.get("password") || <PASSWORD>,
port: uri.port,
name: uri.username || undefined,
db: uri.searchParams.get("db")
? Number(uri.searchParams.get("db"))
: undefined,
tls: uri.searchParams.get("tls") === "true",
maxRetryCount: uri.searchParams.get("max_retry")
? Number(uri.searchParams.get("max_retry"))
: undefined,
retryInterval: uri.searchParams.get("retry_interval")
? Number(uri.searchParams.get("retry_interval"))
: undefined,
});
},
});
export { Keydb };
|
IzarchTech/CPQLib
|
tests/Drain/drain.test.ts
|
import CPQLib, { Drain } from "../../src";
type drainData = {
depth: number;
width: number;
span: number;
thickness: number;
blindingThickness?: number;
workingAllowance?: number;
};
type drainExpectedData = {
volumeOfConcrete: number;
areaOfFormwork: number;
volumeOfExcavtion: number;
volumeOfCartAway: number;
volumeOfBlinding: number;
};
type drainTestData = {
drain: Drain;
expected: drainExpectedData;
};
const testData: Array<drainTestData> = [
{
drain: CPQLib.Drain.instance(0.6, 0.6, 1, 0.15, 0.05, 0.225),
expected: {
volumeOfConcrete: 0.315,
areaOfFormwork: 2.7,
volumeOfExcavtion: 1.08,
volumeOfCartAway: 0.6,
volumeOfBlinding: 0.068,
},
},
{
drain: CPQLib.Drain.instance(0.6, 0.6, 1, 0.15, 0.05),
expected: {
volumeOfConcrete: 0.315,
areaOfFormwork: 1.2,
volumeOfExcavtion: 0.72,
volumeOfCartAway: 0.6,
volumeOfBlinding: 0.045,
},
},
{
drain: CPQLib.Drain.instance(1.2, 1.8, 1, 0.15, 0.05, 0.225),
expected: {
volumeOfConcrete: 0.675,
areaOfFormwork: 5.1,
volumeOfExcavtion: 3.57,
volumeOfCartAway: 1.89,
volumeOfBlinding: 0.128,
},
},
];
describe("Drain tests", () => {
describe("Intialization tests", () => {
const drain: drainData = {
width: 0.6,
depth: 0.6,
span: 1.0,
thickness: 0.15,
blindingThickness: 0.05,
workingAllowance: 0.225,
};
const staticDrainInstance = CPQLib.Drain.instance(
drain.depth,
drain.width,
drain.span,
drain.thickness,
drain.blindingThickness,
drain.workingAllowance
);
const drainInstance = new CPQLib.Drain(
drain.depth,
drain.width,
drain.span,
drain.thickness,
drain.blindingThickness,
drain.workingAllowance
);
test("Class instantiation works", () => {
expect(drainInstance).toBeInstanceOf(CPQLib.Drain);
});
test("Static instance works", () => {
expect(staticDrainInstance).toBeInstanceOf(CPQLib.Drain);
});
test("Static instance is same with Class instantiation", () => {
expect(drainInstance).toEqual(staticDrainInstance);
});
});
describe.each(testData)(
"Quantity calculation tests",
({ drain, expected }) => {
test(`Volume of concrete for ${drain.Depth} x ${drain.Width} x ${drain.Span} = ${expected.volumeOfConcrete}`, () => {
expect(drain.getVolumeOfConcrete()).toBeCloseTo(
expected.volumeOfConcrete
);
});
test(`Area of formwork for ${drain.Depth} x ${drain.Width} x ${drain.Span} = ${expected.areaOfFormwork}`, () => {
expect(drain.getAreaOfFormwork()).toBeCloseTo(expected.areaOfFormwork);
});
test(`Volume of excavation for ${drain.Depth} x ${drain.Width} x ${drain.Span} = ${expected.volumeOfExcavtion}`, () => {
expect(drain.getVolumeOfExcavation()).toBeCloseTo(
expected.volumeOfExcavtion
);
});
test(`Volume of cart away for ${drain.Depth} x ${drain.Width} x ${drain.Span} = ${expected.volumeOfCartAway}`, () => {
expect(drain.getVolumeOfCartAway()).toBeCloseTo(
expected.volumeOfCartAway
);
});
test(`Volume of blinding for ${drain.Depth} x ${drain.Width} x ${drain.Span} = ${expected.volumeOfBlinding}`, () => {
expect(drain.getVolumeofBlinding()).toBeCloseTo(
expected.volumeOfBlinding
);
});
}
);
});
|
IzarchTech/CPQLib
|
src/index.ts
|
import Drain, { IDrain } from "./Drain";
const CPQLib = { Drain };
export { Drain, IDrain };
export default CPQLib;
|
IzarchTech/CPQLib
|
src/Drain/Drain.ts
|
import { IDrain } from "./IDrain";
export class Drain implements IDrain {
readonly BlindingThickness: number;
readonly Depth: number;
readonly Span: number;
readonly Thickness: number;
readonly Width: number;
readonly WorkingAllowance: number;
constructor(
depth: number,
width: number,
span: number,
thickness: number,
blindingThickness: number = 0,
workingAllowance: number = 0
) {
this.Depth = depth;
this.Width = width;
this.Span = span;
this.Thickness = thickness;
this.BlindingThickness = blindingThickness;
this.WorkingAllowance = workingAllowance;
}
static instance = (
depth: number,
width: number,
span: number,
thickness: number,
blindingThickness: number = 0,
workingAllowance: number = 0
) => {
return new Drain(
depth,
width,
span,
thickness,
blindingThickness,
workingAllowance
);
};
getAreaOfFormwork(): number {
if (this.WorkingAllowance > 0)
return 2 * this.Span * (this.Depth + this.getDrainDepth());
return 2 * this.Span * this.Depth;
}
getDrainDepth(): number {
return this.Thickness + this.Depth;
}
getDrainWidth(): number {
return this.Thickness * 2 + this.Width;
}
getExcavationDepth(): number {
return this.getDrainDepth() + this.BlindingThickness;
}
getExcavationWidth(): number {
return this.getDrainWidth() + 2 * this.WorkingAllowance;
}
getVolumeOfCartAway(): number {
return this.getDrainDepth() * this.getExcavationDepth() * this.Span;
}
getVolumeOfConcrete(): number {
return this.Span * this.Thickness * (2 * this.Depth + this.getDrainWidth());
}
getVolumeOfExcavation(): number {
return this.getExcavationDepth() * this.getExcavationWidth() * this.Span;
}
getVolumeofBlinding(): number {
return this.getExcavationWidth() * this.BlindingThickness * this.Span;
}
}
|
IzarchTech/CPQLib
|
src/Drain/IDrain.ts
|
<gh_stars>0
export interface IDrain {
readonly Width: number;
readonly Span: number;
readonly Depth: number;
readonly Thickness: number;
readonly BlindingThickness: number;
readonly WorkingAllowance: number;
getDrainDepth(): number;
getDrainWidth(): number;
getExcavationDepth(): number;
getExcavationWidth(): number;
getVolumeOfConcrete(): number;
getAreaOfFormwork(): number;
getVolumeOfExcavation(): number;
getVolumeOfCartAway(): number;
getVolumeofBlinding(): number;
}
|
IzarchTech/CPQLib
|
src/Drain/index.ts
|
<gh_stars>0
import { Drain } from "./Drain";
import { IDrain } from "./IDrain";
export { IDrain };
export default Drain;
|
gfortil/HPCC-Platform
|
esp/src/src/react/index.ts
|
export * from "./render";
export * from "./wuStatus";
export * from "./recentFilters";
export * from "./aboutDialog";
|
gfortil/HPCC-Platform
|
esp/src/src-react/components/Title.tsx
|
<filename>esp/src/src-react/components/Title.tsx
import * as React from "react";
import { Breadcrumb, DefaultPalette, FontSizes, IBreadcrumbItem, IBreadcrumbStyleProps, IBreadcrumbStyles, Image, IStyleFunctionOrObject, Link, SearchBox, Stack, Toggle } from "@fluentui/react";
import nlsHPCC from "src/nlsHPCC";
const breadCrumbStyles: IStyleFunctionOrObject<IBreadcrumbStyleProps, IBreadcrumbStyles> = {
itemLink: { fontSize: FontSizes.size10, lineHeight: 14, paddingLeft: 2, paddingRight: 2 },
};
interface DevTitleProps {
paths: string[],
useDarkMode: boolean,
setUseDarkMode: (_: boolean) => void;
}
export const DevTitle: React.FunctionComponent<DevTitleProps> = ({
paths,
useDarkMode,
setUseDarkMode
}) => {
let fullPath = "#";
const itemsWithHref = [{ text: "HOME", key: "home", href: "#/" },
...paths.filter(path => !!path).map((path, idx) => {
const retVal: IBreadcrumbItem = { text: path.toUpperCase(), key: "" + idx, href: `${fullPath}/${path}` };
fullPath = `${fullPath}/${path}`;
return retVal;
})];
return <>
<Stack tokens={{ padding: 9, childrenGap: 9 }} >
<Stack horizontal disableShrink horizontalAlign="space-between">
<Stack horizontal tokens={{ childrenGap: 18 }} >
<Stack.Item align="center">
<Link href="#/activities"><Image src="/esp/files/eclwatch/img/hpccsystems.png" /></Link>
</Stack.Item>
<Stack.Item align="center" styles={{ root: { minWidth: 240 } }}>
<Breadcrumb items={itemsWithHref} styles={breadCrumbStyles} />
</Stack.Item>
<Stack.Item align="center">
<SearchBox onSearch={newValue => { window.location.href = `#/search/${newValue.trim()}`; }} placeholder={nlsHPCC.PlaceholderFindText} styles={{ root: { minWidth: 320 } }} />
</Stack.Item>
</Stack>
<Stack horizontal tokens={{ childrenGap: 18 }} >
<Stack.Item align="center">
<Link href="/esp/files/stub.htm">Legacy ECL Watch</Link>
<Toggle
label="Change themes"
onText="Dark Mode"
offText="Light Mode"
onChange={() => setUseDarkMode(!useDarkMode)}
/>
</Stack.Item>
</Stack>
</Stack>
</Stack>
<Stack horizontal styles={{ root: { background: DefaultPalette.themeLighter } }} >
</Stack>
</>;
};
|
gfortil/HPCC-Platform
|
esp/src/src/nls/pt-br/hpcc.ts
|
<reponame>gfortil/HPCC-Platform<filename>esp/src/src/nls/pt-br/hpcc.ts
export = {
Abort: "Abortar",
AbortedBy: "Abortado pelo",
AbortedTime: "Hora de Abortar",
About: "Sobre Plataforma HPCC",
AboutGraphControl: "Sobre Controle de Gráphico",
AboutHPCCSystems: "Sobre HPCC Systems",
AboutHPCCSystemsGraphControl: "Sobre Controle de Gráphico do HPCC Systems®",
AboutToLoseSessionInformation: "Você está prestes a sair e perder todas as informações da sessão. Você deseja continuar?",
Account: "Conta",
Action: "Ação",
Activate: "Ativar",
Activated: "Ativa",
ActivateQuery: "Ativar Consulta",
ActivateQueryDeletePrevious: "Ativar consulta, excluir anterior",
ActivateQuerySuspendPrevious: "Ativar consulta, suspender anterior",
Active: "Ativa",
ActivePackageMap: "Package Map Ativo",
ActiveWorkunit: "Tarefa Ativa",
Activities: "Atividades",
Activity: "Atividade",
ActivityMap: "Mapa de Atividade",
ActualSize: "Tamanho Efectivo",
Add: "Adicionar",
AddAttributes: "Adiciona atributos/valores para seu métedo",
AddAttributes2: "Adiciona atributos",
AddBinding: "Adiciona ligação",
AddFile: "Adicionar Arquivo",
AddGroup: "Adicionar Grupo",
AdditionalResources: "Recursos Adicionais",
AddPart: "Adicionar Parte",
AddProcessMap: "Adicionar Package Map",
AddTheseFilesToDali: "Adicionar esses arquivos a Dali",
AddtionalProcessesToFilter: "Processos adicionais para filtrar",
AddToExistingSuperfile: "Adicionar a um superfile existente",
AddToSuperfile: "Adicionar ao Superarquivo",
AddUser: "Adicionar Usuário",
Advanced: "Avançado",
All: "Todos",
AllowAccess: "Permitir Acesso",
AllowForeignFiles: "Permitir Arquivos Remotos",
AllowFull: "Permissão Total",
AllowRead: "Permissão de Leitura",
AllowWrite: "Permissão de Escrita",
AllQueries: "Todas as Consultas",
AllQueuedItemsCleared: "Todos os itens em fila foram apagados. O trabalho em execução atual continuará a ser rodado",
Analyze: "Analisar",
ANY: "Qualquer",
AnyAdditionalProcessesToFilter: "Quaisquer processos adicionais para filtrar",
Append: "Anexar",
AppendCluster: "Acrescentar o Cluster",
Apply: "Aplicar",
ArchivedOnly: "Apenas Arquivadas",
ArchivedWarning: "Aviso: Por favor especifique intervalos de datas menore. Caso contrário, a operação para buscar workunits pode demorar causando um erro no navegador.",
AreYouSureYouWantToResetTheme: "Tem certeza de que deseja redefinir o tema padrão?",
Attach: "Anexar",
Attribute: "Attributo",
AttributesAreRequired: "Atributos são necessários",
Audience: "Público",
AuditLogs: "Registro de auditoria",
AutoRefresh: "Recarregar Automático",
AutoRefreshEvery: "Atualização automática a cada x minutos",
AutoRefreshIncrement: "Auto Incrementar Atualização",
Back: "voltar",
BannerColor: "Cor da Faixa",
BannerMessage: "Mensagem da Faixa",
BannerScroll: "Faixa de Paginação",
BannerSize: "Tamanho da Faixa",
BinaryInstalls: "Instalação Binária",
Bind: "Ligar",
Binding: "Ligação",
BindingDeleted: "Ligação deletado",
Blob: "BLOB",
BlobPrefix: "Prefixo do BLOB",
Blooms: "Blooms",
Bottom: "fundo",
BoundBy: "vinculado pela:",
BrowserStats: "Estatísticas do navegador",
Busy: "Ocupado",
Cancel: "Cancelar",
CancelAll: "Cancela tudo",
CancelAllMessage: "Abortar trabalhos em execução e limpar a fila. Você deseja continuar?",
Channel: "Canal",
Chart: "Gráfico",
CheckAllNodes: "Verifique Todos os Nós",
CheckFilePermissions: "Verifique Permissão de Arquivo",
CheckSingleNode: "Verifique Nó Singular",
Clear: "Limpar",
ClearPermissionsCache: "Limpar Cache de Permissões",
ClearPermissionsCacheConfirm: "Tem certeza que você quer limpar todos os caches de permissões dos servidores DALI e ESP? Workunits em execução podem ter a performance significantemente prejudicadas até que os caches tenham sido recarregados.",
Client: "Cliente",
Clone: "Clonar",
ClonedWUID: "WUID clonado",
CloneTooltip: "Unidade de Trabalho Duplicado",
Close: "Fechar",
Cluster: "Cluster (Aglomerado)",
ClusterName: "Nome do Aglomerado (Cluster)",
ClusterPlaceholder: "r?x*",
ClusterProcesses: "Processos de Aglomerados",
Code: "Código",
CodeGenerator: "Gerador de Código",
Col: "Col",
CollapseAll: "Recolher Tudo",
Command: "Comando",
Comment: "Comentário",
Compiled: "Compilado",
Compiling: "Compilando",
Completed: "Completo",
ComplexityWarning: "Mais de {limite} atividades ({Contador de atividades}) - suprimir amostragem inicial?",
Component: "Componente",
ComponentLogs: "Log de componentes",
Compress: "Compactar",
Compressed: "Comprimido",
CompressedFileSize: "Tamanho do Arquivo Comprimido",
ComputerUpTime: "Tempo do Computador Ativo",
Condition: "Condição",
Configuration: "Configuração",
ConfigureService: "Configurar serviço",
ConfirmPassword: "<PASSWORD>",
ConfirmRemoval: "Tem certeza que quer fazer isso?",
ContactAdmin: "Se você deseja renomear este grupo, por favor, entre em contato com o administrador do LDAP",
Content: "Conteúdo",
Contents: "Conteúdo",
ContentType: "Tipo de Conteúdo",
ContinueWorking: "Contínua Trabalhando",
Copied: "Copiado!",
Copy: "Copiar",
CopyToClipboard: "Copiar para área de transferência",
CopyURLToClipboard: "Copiar URL para a área de transferência",
CopyWUIDs: "Copiar WUIDs para a área de transferência",
CopyWUIDToClipboard: "Copiar WUID para a área de transferência",
Count: "Conta",
CPULoad: "Carga do CPU ",
Create: "Criar",
CreateANewFile: "Criar um novo superfile",
Created: "Criado",
CreatedBy: "Criado Por",
CreatedByWorkunit: "Criado por workunit",
CreatedTime: "Tempo Criado",
Creating: "Criando",
Critical: "Crítico",
CSV: "CVS",
Dali: "Dali",
DaliIP: "IP do Dali",
DataPatterns: "Padrões de Dados",
DataPatternsNotStarted: "Análise não encontrada. Para começar, pressione o botão Analisar acima.",
DataPatternsStarted: "Analisando. Quando o relatório for completo, vai ser exibido aqui.",
dataset: ":=dataset*",
Date: "Data",
Day: "Dia",
Deactivate: "Desativar",
Debug: "Debug",
DEF: "DEF",
Defaults: "Padrões",
Definition: "Definição",
DefinitionDeleted: "Definição deletada",
DefinitionID: "Identidade de definição",
Definitions: "Definições",
DelayedReplication: "Replicação atrasada",
Delete: "Remover",
DeleteBinding: "Apagar Ligação",
Deleted: "Removido",
DeletedBinding: "Ligação Apagado",
DeleteDirectories: "Remover diretórios vazios. Você deseja continuar?",
DeleteEmptyDirectories: "Excluir diretórios vazios?",
DeletePrevious: "Apagar Anterior",
DeleteSelectedDefinitions: "Deletar definições selecionadas?",
DeleteSelectedFiles: "Apagar Arquivos Selecionados?",
DeleteSelectedGroups: "Remover Grupos Selecionados",
DeleteSelectedPackages: "Excluir pacotes selecionados?",
DeleteSelectedPermissions: "Remover Permissões Selecionadas",
DeleteSelectedQueries: "Apagar Consultas Selecionadas?",
DeleteSelectedUsers: "Remover Usuários Selecionados",
DeleteSelectedWorkunits: "Apagar Tarefas Selecionadas?",
DeleteSuperfile: "Apagar Super Arquivo?",
DeleteSuperfile2: "Remover Super Arquivo",
DeleteThisPackage: "Remover Este Pacote",
Delimited: "Delimitado",
DenyAccess: "Bloquear",
DenyFull: "Bloquear Completamente",
DenyRead: "Bloquear Leitura",
DenyWrite: "Bloquear Escrita",
Depth: "Profundidade",
DepthTooltip: "Profundidade Máxima de Subgrafo",
Deschedule: "Desagendar",
DescheduleSelectedWorkunits: "Desagendar Unidades de Trabalho Selecionadas",
Description: "Descrição",
DESDL: "Dynamic ESDL",
Despray: "Despray (Consolidar Dados dos Nós)",
Details: "Detalhes",
DFUServerName: "Nome do Servidor DFU",
DFUWorkunit: "DFU Unidade de Trabalho",
Directories: "Diretórios",
Directory: "Diretório",
DisableScopeScanConfirm: "Tem certeza que quer desabilitar busca de escopo? Alterações de configuração serão aplicadas quando DALI reiniciar.",
DisableScopeScans: "Desabilitar busca de escopo",
DiskUsage: "Uso de disco",
Distance: "Distancia",
DistanceTooltip: "Distância a vizinhança de máxima atividade",
Dll: "Dll (Biblioteca de Vínculo Dinâmico)",
Documentation: "Documentação",
Domain: "Domínio",
DoNotActivateQuery: "Não ative a consulta",
DoNotRepublish: "Não republicar?",
DOT: "DOT",
DOTAttributes: "Propriedades de DOT",
Down: "Pra baixo",
Download: "Baixar",
Downloads: "Abaixamentos",
DownloadToCSV: "Transferir para o CSV",
DropZone: "Zona de entrada de arquivos",
DueToInctivity: "Você será desconectado de todas as sessões do ECL Watch em 3 minutos devido a inatividade.",
Duration: "Duração",
DynamicNoServicesFound: "Nenhum Serviço Encontrado",
EBCDIC: "EBCDIC",
ECL: "ECL",
ECLWatchRequiresCookies: "O ECL Watch requer cookies habilitados para continuar.",
ECLWatchSessionManagement: "Gerenciamento de sessão do ECL Watch",
ECLWorkunit: "ECL Unidade de Trabalho",
Edges: "Bordas",
Edit: "Alterar",
EditDOT: "Editar DOT",
EditGraphAttributes: "Editar Propriedades do Gráfico",
EditXGMML: "Editar XGMML",
EmailBody: "Corpo do email",
EmailFrom: "Endereço de email (de)",
EmailSubject: "Assunto do email",
EmailTo: "Endereço de email (para)",
EmployeeID: "ID do Empregado",
EmployeeNumber: "Número de empregado",
Empty: "Vazio",
Enable: "Ativar",
EnableBannerText: "Ativar Texto do Ambiente",
EnableScopeScans: "Ativar busca de escopo",
EnableScopeScansConfirm: "Tem certeza que gostaria de ativar busca de escopo? Alterações serão aplicadas quando DALI reiniciar.",
EnglishQ: "Inglês?",
EnterAPercentage: "Digite uma porcentagem",
EnterAPercentageOrMB: "Digite uma porcentagem ou MB",
EraseHistory: "Apagar História",
EraseHistoryQ: "Apagar o histórico para",
Error: "Erro",
Errorparsingserverresult: "Erro interpretando o resultado do servidor",
Errors: "Erros",
ErrorsStatus: "Erros/Estados",
ErrorUploadingFile: "Erro ao carregar arquivos. Tente verificar permissões.",
ErrorWarnings: "Error/Aviso(s)",
Escape: "Escapar",
ESPBindings: "Ligações ESP",
ESPBuildVersion: "Versão do ESP", // jshint ignore:line
ESPNetworkAddress: "Endereço de Rede do ESP",
ESPProcessName: "Nome do Processo ESP",
EventName: "Nome do Evento",
EventNamePH: "Nome do Evento",
EventScheduler: "Gerenciador de Evento",
EventText: "Texto do Evento",
EventTextPH: "Texto do Evento",
Exception: "Exceção",
Executed: "Executado",
Executing: "Executando",
ExpandAll: "Expandir Tudo",
ExpireDays: "Expira em (dias)",
Export: "Exportar",
ExportSelectionsToList: "Exportar Seleções para Lista",
FailIfNoSourceFile: "Falha em caso de arquivo sem fonte",
Fatal: "Fatal",
Fetched: "Buscado",
FetchingData: "Buscando dados...",
fetchingresults: "Buscando Resultados",
FieldNames: "Nomes dos Campos",
File: "Arquivo",
FileCluster: "Arquivos Cluster",
FileCounts: "Número de Arquivos",
FileName: "Nome do Arquivo",
FileParts: "Partes do Arquivo",
FilePath: "Caminho e nome do Arquivo",
FilePermission: "Permissão de Arquivo",
Files: "Arquivos",
FileScopeDefaultPermissions: "Permissão Padrão de Arquivo Escopo",
FileScopes: "Escopo de arquivos",
FileSize: "Tamanho do Arquivo",
FilesNoPackage: "Arquivos sem definição de pacotes.",
FilesPending: "Arquivos pendentes",
FilesWarning: "O número de arquivos retornados é muito grande. Apenas os primeiros 100.000 arquivos classificados por data / hora modificados foram retornados. Se você deseja limitar os resultados, defina um filtro.",
FilesWithUnknownSize: "Arquivos com tamanho desconhecido",
FileType: "Tipo de Arquivo",
FileUploader: "Uploader(Enviador) de Arquivo",
FileUploadStillInProgress: "Carregamento de Arquivo em andamento",
Filter: "Filtro",
FilterDetails: "Detalhes do Filtro",
FilterSet: "Conjunto Filtro",
Find: "Busca",
FindNext: "Próxima Busca",
FindPrevious: "Busca Anterior",
Finished: "Completo",
FirstN: "Primeiro N",
FirstName: "<NAME>",
FirstNRows: "Primeiras N Linhas",
Fixed: "Fixo",
Folder: "Pasta",
Format: "Formato",
Forums: "Bate Papos",
Forward: "Avançar",
FoundFile: "Arquivo Encontrado",
FoundFileMessage: "Um arquivo encontrado tem todas as suas partes no disco que não são referenciadas no servidor Dali. Todas as partes do arquivo são contabilizadas para que possam ser adicionadas de volta ao servidor Dali. Eles também podem ser excluídos do cluster, se for necessário.",
FromDate: "Data Inicial",
FromSizes: "Tamanho Mínimo",
FromTime: "Tempo inicial",
FullName: "Nome Completo",
Generate: "Gerar",
GetPart: "Obter Parte",
GetSoftwareInformation: "Obter Informações de Software",
Graph: "Grafo",
GraphControl: "Controle Gráfico",
Graphs: "Gráficos",
GraphView: "Visão Gráfica",
Group: "Grupo",
GroupBy: "Agrupado por",
GroupDetails: "Detalhe de Grupo",
Grouping: "Agrupar",
GroupName: "Nome do Grupo",
GroupPermissions: "Permissões de Grupo",
Groups: "Grupos",
GZip: "GZip",
help: "Essa area exibi o mapas de arvores (hierarquias) para o gráfico dessa tarefa. O tamanho e cor indicam a duração de cada gráfico (Quanto maior e mais escuro mais tempo levou)",
Helper: "Ajudante",
Helpers: "Ajudantes",
Hex: "Hex",
HexPreview: "Pré-visualização Hex",
HideSpills: "Esconde Derramamentos",
High: "Alto",
History: "História",
HPCCSystems: "HPCCSystems",
Icon: "Ícone",
ID: "Identidade",
Inactive: "Inativo",
IncludeSlaveLogs: "Incluie logs escravos",
Index: "Índice",
Info: "Info",
InfoDialog: "Caixa de Informação",
Informational: "Informativo",
InheritedPermissions: "Permissão Herdada",
Inputs: "Insumos",
InUse: "Em uso",
InvalidResponse: "(resposta inválida)",
InvalidUsernamePassword: "Nome de usuário ou senha inválidos, tente novamente.",
IP: "IP",
IPAddress: "Endereço IP",
IsCompressed: "É Comprimido",
IsLibrary: "Biblioteca?",
IsReplicated: "É Replica?",
IssueReporting: "Reportagem de Problemas",
Jobname: "<NAME>",
JobName: "<NAME>",
jsmi: "jsmi*",
JSmith: "JSilva*",
JSON: "JSON",
KeyFile: "Arquivo Chave",
KeyType: "Tipo de Chave",
Label: "Rótulo de Texto",
LandingZone: "Zona de Entrada de Arquivos",
LandingZones: "Zona de entrada de arquivos",
LanguageFiles: "Arquivo de Línguas",
Largest: "Maior",
LargestFile: "Maior Arquivo",
LargestSize: "Maior Tamanho",
LastEdit: "Última Edição",
LastEditedBy: "Última Edição Por:",
LastEditTime: "Última Hora de Edição",
LastMessage: "Última Mensagem",
LastName: "Sobrenome",
LastNDays: "Ultimos N Dias",
LastNHours: "Últimas N Horas",
LastNRows: "Últimas N Filas",
LastRun: "Última Rodada",
LDAPWarning: "<b>Error do serviço de LDAP</b> ‘Número de usuários excedido’. Por favor use um filtro.",
LearnMore: "Saber Mais",
LegacyForm: "Formato Antigo",
LegacyGraphLayout: "Formato de Gráfico Antigo",
LegacyGraphWidget: "Widget de Gráfico Antigo",
Legend: "Lenda",
LibrariesUsed: "Usa Biblioteca?",
LibraryName: "Nome da biblioteca",
Limit: "Limite",
Line: "Linha",
LineTerminators: "Terminador de linhas",
Links: "Ligações",
Loading: "Carregando",
LoadingCachedLayout: "Carregando diagrama do cache",
LoadingData: "Carragando Dados...",
loadingMessage: "...carregando...",
LoadPackageContentHere: "(Carregue conteúdo de pacote aqui)",
LoadPackageFromFile: "Carregar pacote de arquivo",
Local: "Local",
LocalFileSystemsOnly: "Somente Sistemas de Arquivos Locais",
Location: "Localização",
Lock: "Bloquear",
Log: "Registro",
log_analysis_1: "log_analysis_1*",
LogDirectory: "Diretório de Log",
LogFile: "Arquivo de log",
LoggedInAs: "Entrou no sistema como",
LoggingOut: "Fazendo um Logout",
LogicalFile: "Arquivo Lógico",
LogicalFiles: "Arquivos Lógicos",
LogicalFilesAndSuperfiles: "Arquivos (super e lógicos)",
LogicalFilesOnly: "Somente arquivos lógicos",
LogicalFileType: "Tipo de Arquivo Lógico",
LogicalName: "Nome Lógico",
Login: "Fazer um Login",
Logout: "Fazer um Logout",
Logs: "Registros",
LogVisualization: "Visualização de Log",
LogVisualizationUnconfigured: "Visualização de Registro não está configurado, por favor, verifique as configurações do gerenciador de confguração",
LostFile: "Arquivo perdido",
LostFile2: "Arquivos perdidos",
LostFileMessage: "Um arquivo lógico que está faltando pelo menos uma parte de arquivo em ambos os locais primário e replicado em armazenamento. O arquivo lógico ainda é referenciado no servidor Dali. A exclusão do arquivo remove a referência do servidor Dali e de quaisquer partes restantes no disco.",
Low: "Baixo",
MachineInformation: "Informação da máquina",
Machines: "Máquinas",
Major: "Principal",
ManagedBy: "Gerenciado Por",
ManagedByPlaceholder: "CN=HPCCAdmin,OU=usuários,OU=hpcc,DC=MyCo,DC=local",
ManualCopy: "Pressione Ctrl+C",
ManualOverviewSelection: "(Seleção manual será necessária)",
ManualTreeSelection: "(Seleção manual de árvore será requerida)",
Mappings: "Mapeamento",
Mask: "Mask (bloqueador de caracteres)",
Max: "Max",
MaximizeRestore: "Maximizar/Restaurar",
MaximumNumberOfSlaves: "Numero de esclavo",
MaxNode: "Nó Max",
MaxRecordLength: "Maximo tamanho do registro",
MaxSize: "Tamanho máximo",
MaxSkew: "Viás Max",
MaxSkewPart: "Pedaço Viás Max",
Mean: "Média",
MemberOf: "Membro de",
Members: "Membros",
Message: "Mensagem",
MethodConfiguration: "Configuração do Método",
Methods: "Métodos",
Min: "Min",
Mine: "Meu",
MinNode: "Nó Min",
Minor: "Menor",
MinSize: "Tamanho mínimo",
MinSkew: "Viás Min",
MinSkewPart: "Pedaço Viás Min",
Missing: "Não encontrado",
MixedNodeStates: "Estados de Nós misturados",
Modification: "Modificação",
Modified: "Modificado",
ModifiedUTCGMT: "Modificado (UTC/GMT)",
Modify: "Modificar",
MonitorEventName: "Nome do Evento do Monitorador",
Monitoring: "Monitorador",
MonitorShotLimit: "Limite do Monitorador",
MonitorSub: "Sub do Monitorador",
Month: "Mês",
More: "Mais",
MustContainUppercaseAndSymbol: "Deve conter símbolo e caracteres maiúsculos",
NA: "Não Aplicável",
Name: "Nome",
NameOfEnvironment: "Nome do Ambiente",
NamePrefix: "Prefixo de nome",
NamePrefixPlaceholder: "algum::prefixo",
NetworkAddress: "Endereço de Rede",
Newest: "Mais recente",
NewPassword: "<PASSWORD>",
NoCommon: "Incomum",
NoContent: "(sem conteúdo)",
noDataMessage: "... Zero linhas...",
Node: "Nó (Node)",
NodeGroup: "Grupo de Nós",
NoErrorFound: "Nenhum Erro Encontrado",
NoFilterCriteriaSpecified: "Filtro não especificado",
None: "Nenhum",
NoPublishedSize: "Nenhum tamanho publicado",
NoRecentFiltersFound: "Nenhum filtro recente encontrado.",
Normal: "Normal",
NoScheduledEvents: "Eventos agendados não encontrados",
NoSplit: "Sem Separador",
NotActive: "Inativo",
NothingSelected: "Nada Selecionado",
NotInSuperfiles: "Não encontrado em super arquivo",
NotSuspended: "Não Suspenso",
NotSuspendedbyUser: "Não suspenso por usuário",
NoWarningFound: "Nenhuma Advertência Encontrada",
NumberofParts: "Numero de Partes",
NumberofSlaves: "Número de Escravos",
OK: "Aceitar",
Oldest: "Mais Antigo",
OldPassword: "<PASSWORD>",
OmitSeparator: "Omitir Separador",
Only1PackageFileAllowed: "Somente one arquivo de pacote permitido",
Open: "Abrir",
OpenConfiguration: "Abrir Configuração",
OpenInNewPage: "Abrir em página nova",
OpenInNewPageNoFrame: "Abrir em página nova (sem quadro)",
OpenLegacyECLWatch: "Abrir Antigo ECL Watch",
OpenLegacyMode: "Modo Legado Aberto",
OpenNativeMode: "Modo Nativo Aberto",
OpenSafeMode: "Abrir em Modo de Segurança",
OpenSource: "Código Público",
OpenTreeMode: "Abrir (modo árvore)",
Operation: "Operação",
Operations: "Operações",
Optimize: "Otimizar",
Options: "Opções",
OriginalFile: "Arquivo Originál",
OrphanFile: "Arquivos órfãos",
OrphanFile2: "Arquivo órfão",
OrphanMessage: "Um arquivo órfão tem partes de arquivo parcial no disco. No entanto, um conjunto completo de peças não está disponível para construir um arquivo lógico e completo. Isso não faz referência a essas partes de arquivo no servidor Dali.",
OSStats: "Estatísticas do SO",
Outputs: "Resultados",
Overview: "Visão Geral",
Overwrite: "Sobrescrever",
OverwriteMessage: "Alguns arquivos já existem. Selecione opção de escrever por cima para continuar.",
Owner: "Proprietário",
PackageContent: "Conteúdo de pacote",
PackageContentNotSet: "Conteúdo de pacote não definido",
PackageMap: "Mapa de Pacotes",
PackageMaps: "Mapas do Pacote de Dados",
PackagesNoQuery: "Pacotes sem queries",
ParameterXML: "Parametro XML",
Part: "Parte",
PartMask: "Parte Máscara",
PartName: "Nome da Parte",
Parts: "Partes",
PartsFound: "Pedaços Encontradas",
PartsLost: "Pedaços Perdidas",
Password: "<PASSWORD>ha",
PasswordExpiration: "Validade da Senha",
PasswordExpired: "Sua senha não é mais válida. Por favor altere agora.",
PasswordExpirePostfix: "dia(s). Quer trocar agora?",
PasswordExpirePrefix: "Senha válida até",
PasswordOpenZAP: "Senha para abrir ZAP (opicional)",
PasswordsDoNotMatch: "Senhas não são as mesmas",
Path: "Caminho",
PathMask: "Bloqueador do Caminho",
Pause: "Pausar",
PauseNow: "Pausar agora",
PctComplete: "% Completo",
PercentCompressed: "Percentagem Comprimida",
PercentDone: "Percentual Completo",
PercentUsed: "% Usado",
PerformingLayout: "Executando Layout...",
Permission: "Permissão",
PermissionName: "Nome da Permissão",
Permissions: "Permissões",
PhysicalFiles: "Arquivos Físicos",
PhysicalMemory: "Memória Física",
PlaceholderFindText: "Wuid, Usuário, Mais...", // jshint ignore:line
PlaceholderFirstName: "João",
PlaceholderLastName: "<NAME>",
Platform: "Plataforma",
Playground: "Area de Recreio",
PleaseEnableCookies: "O ECL Watch requer cookies habilitados para continuar.",
PleaseEnterANumber: "Por favor digite o número 1 -",
PleaseLogin: "Por favor, faça o login usando seu nome de usuário e senha",
PleaseLogIntoECLWatch: "Por favor, faça o login no ECL Watch",
PleasePickADefinition: "Por favor, escolha uma definição",
PleaseSelectADynamicESDLService: "Selecione um serviço ESDL dinâmico",
PleaseSelectAGroupToAddUser: "Por favor, selecione um grupo para adicionar o usuário a",
PleaseSelectAServiceToBind: "Por favor, selecione um serviço para ligar",
PleaseSelectATopologyItem: "Selecione um alvo, serviço ou máquina.",
PleaseSelectAUserOrGroup: "Por favor selecione um usário ou grupo junto com um nome de arquivo",
PleaseSelectAUserToAdd: "Por favor, selecione um usuário para adicionar",
Plugins: "Plugins",
Port: "Porta",
Prefix: "Prefixo",
PrefixPlaceholder: "‘nomedoarquivo{:comprimento}, tamanho{:[B|L][1-8]}’",
Preflight: "Pré-vôo",
PreloadAllPackages: "Precarregar Todos os Pacotes",
PreserveCompression: "Manter Arquivo Comprimido",
PressCtrlCToCopy: "Pressione ctrl + c para copiar.",
Preview: "Prévia",
PrimaryLost: "Principal Perdido",
PrimaryMonitoring: "Monitorador Principal",
Priority: "Prioridade",
Probability: "Probabilidade",
Process: "Processo",
Processes: "Processos",
ProcessesDown: "Processos Desativados",
ProcessFilter: "Filtro de Processo",
ProcessorInformation: "Informações do Processador",
ProgressMessage: "Mensagem de Progresso",
Properties: "Propriedades",
Property: "Propriedade",
Protect: "Proteger",
ProtectBy: "Protegida Pela",
Protected: "Protegido",
Protocol: "Protocolo",
Publish: "Publicado",
Published: "Publicado",
PublishedBy: "Publicado por",
PublishedByMe: "Publicado por mim",
PublishedQueries: "Consultas de ECL Publicadas",
PushEvent: "Evento de publicação",
Quarter: "Quarto",
Queries: "Consultas ECL",
QueriesNoPackage: "Queries sem pacote",
Query: "Consulta",
QueryDetailsfor: "Detalhes para",
QueryID: "Identidade de Consulta",
QueryIDPlaceholder: "some?q*ry.1",
QueryName: "Nome da Query",
QueryNamePlaceholder: "Minha?Su?erQ*ry",
QuerySet: "Grupo de Consultas",
Queue: "Fila",
Quote: "Aspas",
QuotedTerminator: "Terminador em Aspas",
RawData: "Dados não Tratados",
RawTextPage: "Texto original (página atual)",
Ready: "Pronto",
ReallyWantToRemove: "Realmente quer remover?",
ReAuthenticate: "Reautenticar para desbloquear",
RecentFilters: "Filtros Recentes",
RecentFiltersTable: "Tabela de Filtros Recentes",
RecordCount: "Numero de Registros",
RecordLength: "Tamanho do Registro",
Records: "Registros",
RecordSize: "Tamanho do Registro",
RecordStructurePresent: "Estrutura de registro disponível",
Recover: "Recuperar",
RecoverTooltip: "Reniciar unidade de trabalho pausado / bloqueado",
RecreateQuery: "Recriar consulta",
Recycling: "Reciclando",
RedBook: "Livro Vermelho",
Refresh: "Recarregar",
ReleaseNotes: "Notas de Versão",
Reload: "Recarregar",
Remaining: "Faltando",
RemoteCopy: "Cópia Remota",
RemoteDali: "Dali Remota",
RemoteDaliIP: "IP Dali Remoto",
Remove: "Remover",
RemoveAttributeQ: "Você está prestes a remover esse atributo. Você tem certeza de que quer fazer isso?",
RemoveAtttributes: "Remover Atributo (s)",
RemovePart: "Remover parte",
RemoveSubfiles: "Remover sub-arquivo(s)",
RemoveSubfiles2: "Remover sub-arquivo(s)?",
RemoveUser: "Você está próximo de remover-se do grupo",
Rename: "Renomear",
RenderedSVG: "Rendered SVG",
RenderSVG: "Renderização SVG",
Replicate: "Replicar",
ReplicatedLost: "Replicado Perdido",
ReplicateOffset: "Replicar o Deslocamento",
Report: "Relatório",
ReportAnError: "Comunicar um Erro",
ReportError: "Reportar Erro",
RepresentsASubset: "Representar un subconjunto de todas los casamientos. Usando un filtro correcto puede reducir el numero de casamientos",
RequestSchema: "Schema da Busca",
RequiredForFixedSpray: "Necessário para spray fixo",
RequiredForXML: "Manditório para spray de dados em XML",
Reschedule: "Reagendar",
Reset: "Limpar",
ResetThisQuery: "Restaurar esta Pesquisa?",
ResetViewToSelection: "Restaurar Visão da seleção",
Resource: "Recurso",
Resources: "Recursos",
ResponseSchema: "Schema da Resposta",
Restart: "Reiniciar",
Restarted: "Recomeçar",
Restore: "Restaurar",
Restricted: "Restrito",
Resubmit: "Resubmeter",
Resubmitted: "Submeter de novo",
ResubmitTooltip: "Submeter unidade de trabalho de novo",
Results: "Resultado(s)",
Resume: "Continue",
RetainSuperfileStructure: "Preservar Estrutura do Super Arquivo",
RetainSuperfileStructureReason: "Reter Estrutura de Superfile deve ser ativado quando existir mais de 1 subarquivo",
RetypePassword: "<PASSWORD>",
Reverse: "Reverter",
RowPath: "linha de acesso",
Rows: "Linhas",
RowTag: "Nome da Linha",
RoxieCluster: "Roxie Cluster (Aglomerado)",
RoxieFileCopy: "Estado de Cópia de Archivos Roxie",
RoxieState: "Estado de Roxie",
RunningServerStrain: "Executar este processo pode demorar muito tempo e vai sobrecarregar os servidores. Você quer continuar?",
Sample: "Amostra",
SampleRequest: "Amostra da Busca",
SampleResponse: "Amostra de Resposta",
Save: "Salvar",
Scope: "Escopo",
SearchResults: "Resultado da Busca",
SecondsRemaining: "Segundos Restantes",
Security: "Segurança",
SelectPackageFile: "Selecione pacote que arquivos",
SendEmail: "Enviar email",
Separators: "Seperadores",
Server: "Servidor",
ServiceName: "Nome do Serviço",
Services: "Serviços",
ServiceType: "Tipo de serviço",
SetBanner: "Fixar Banner",
SetTextError: "Erro para mostrar texto(muito longo?) Use ‘ajuda’ para baixar",
SetToFailed: "Indicar como Falhado",
SetToolbar: "Definir Barra de Ferramentas",
Severity: "Severidade",
ShareWorkunit: "Compartilhar URL do Workunit",
Show: "Exibir",
ShowProcessesUsingFilter: "Mostrar processos usando filtro",
ShowSVG: "Mostrar SVG",
Size: "Tamanho",
Skew: "Distorção",
SkewNegative: "Inclinar (-)",
SkewPositive: "Inclinar (+)",
SLA: "SLA",
SlaveLogs: "Logs escravos",
SlaveNumber: "Numero de esclavo",
Slaves: "Escravos",
Smallest: "Menor",
SmallestFile: "Arquivo Menor",
SmallestSize: "Menor tamanho",
SOAP: "SOAP",
SomeDescription: "Alguma descrição",
somefile: "*::algum_arquivo*",
Source: "Fonte",
SourceCode: "Código Fonte",
SourceLogicalFile: "Nome Lógica do arquivo Fonte",
SourcePath: "fonte de acesso",
SourceProcess: "fonte de processo",
SparkThor: "SparkThor",
Spill: "Regar",
SplitPrefix: "Prefixo de separação",
Spray: "Spray (Distribuir aos Nós)",
Start: "Começar",
Started: "Início",
Starting: "Iniciando",
State: "Estado",
Stats: "Estatísticas",
Status: "estado",
Stopped: "Parado",
Stopping: "Parando",
StorageInformation: "Informações de armazenamento",
Subgraph: "Sugrafo",
Subgraphs: "Subgráfico",
Submit: "Submeter",
Subtype: "Subtipo",
SuccessfullySaved: "Guardado com sucesso",
Summary: "Resumo",
SummaryMessage: "Mensagem de Resumo",
Superfile: "Super Arquivo",
SuperFile: "Super Arquivo",
Superfiles: "Super Arquivos",
SuperFiles: "Super Arquivos",
SuperFilesBelongsTo: "Membro do(s) Super Arquivo(s)",
SuperfilesOnly: "Apenas Super Arquivos",
SuperOwner: "Dono Super",
Suspend: "Suspender",
Suspended: "Suspendido",
SuspendedBy: "Suspendido por",
SuspendedByAnyNode: "Suspenso Por Qualquer Nó",
SuspendedByCluster: "Interrompido pelo Bloco",
SuspendedByFirstNode: "Suspenso Pelo Primeiro Nó",
SuspendedByUser: "Interrompido pelo Usuário",
SuspendedReason: "Razão para interrupção",
SVGSource: "Fonte de SVG",
Sync: "Sync",
SyncSelection: "Sincronizar seleção",
SystemServers: "Servidores do Sistema",
Table: "Tabela",
tag: "tag",
Target: "Destino",
TargetClusters: "Aglomeragos de Destino(Alvos)",
TargetClustersLegacy: "Clusters de Alvo (legacy)",
TargetName: "Nome do Destino",
TargetNamePlaceholder: "algum::lógico::arquivo",
TargetRowTagRequired: "Tag Obrigatório de Registro de Destino",
Targets: "Alvos",
TargetScope: "Escopo de Destino",
TargetWuid: "Unidade de trabalho alvo",
Terminators: "Terminadores",
TestPages: "Páginas de Teste",
Text: "Texto",
TheReturnedResults: "Os Resultados Devolvidos",
ThorMasterAddress: "Endereço de metre thor",
ThorNetworkAddress: "Endereço de Rede do Thor",
ThorProcess: "Processo de Thor",
Time: "Tempo",
Timers: "Controladores de tempo",
TimeSeconds: "Tempo (Segundos)",
TimeStamp: "Timestamp",
TimeStarted: "Início",
TimeStopped: "Fim",
Timings: "Medidas de Tempo",
TimingsMap: "Mapa das Medidas de Tempo",
title_ActiveGroupPermissions: "Permissão de Grupo Ativo",
title_ActivePermissions: "Permissão Ativo",
title_Activity: "Atividate",
title_AvailableGroupPermissions: "Permissão de Grupos Disponiveis",
title_AvailablePermissions: "Permissão Disponiveis",
title_BindingConfiguration: "Configuração de Ligação",
title_BindingDefinition: "Definição de Ligação",
title_Blooms: "Blooms",
title_ClusterInfo: "grupos",
title_Clusters: "Clusters",
title_CodeGeneratorPermissions: "Permissões de Gerador de Código",
title_DefinitionExplorer: "Explorador de definição",
title_Definitions: "Definições",
title_DESDL: "ESDL dinâmica",
title_DFUQuery: "Arquivos Lógicos",
title_DFUWUDetails: "Tarefa DFU",
title_DirectoriesFor: "Diretórios para",
title_DiskUsage: "uso de disco",
title_ECLPlayground: "ECL Playground",
title_ErrorsWarnings: "Erros / Avisos para",
title_EventScheduleWorkunit: "Escalonador de eventos",
title_FileScopeDefaultPermissions: "Permissão Padrão de Arquivos",
title_FilesPendingCopy: "Arquivos pendentes de cópia",
title_FoundFilesFor: "Arquivos encontrados para",
title_GetDFUWorkunits: "Tarefas DFU",
title_Graph: "Gráficos",
title_GraphPage: "Título",
title_Graphs: "Gráficos",
title_GridDetails: "Mude-me",
title_History: "História",
title_HPCCPlatformECL: "ECL Watch - Página Inicial",
title_HPCCPlatformFiles: "ECL Watch - Arquivos",
title_HPCCPlatformMain: "ECL Watch - Página Inicial",
title_HPCCPlatformOps: "ECL Watch - Operações",
title_HPCCPlatformOpsWidget: "ECL Watch - Operações",
title_HPCCPlatformRoxie: "ECL Watch - Roxie",
title_HPCCPlatformServicesPlugin: "ECL Watch - Adaptadores",
title_Inputs: "Entradas",
title_LFDetails: "Detalhes dos Arquivos Lógicos",
title_LibrariesUsed: "Bibliotecas usadas",
title_Log: "arquivo de registro",
title_LostFilesFor: "Arquivos perdidos para",
title_LZBrowse: "Zona de Entrada de Arquivos",
title_MemberOf: "Membros de",
title_Members: "Membros",
title_Methods: "Métodos",
title_OrphanFilesFor: "Arquivos órfãos para",
title_PackageParts: "Pacote de peças",
title_Permissions: "Permissões",
title_Preflight: "Métricas do Sistema",
title_PreflightResults: "Resultados Pré-vôo",
title_ProtectBy: "Protegida Pela",
title_QuerySetDetails: "Detalhes da Consulta ECL",
title_QuerySetErrors: "Erros",
title_QuerySetLogicalFiles: "Arquivos Lógicos",
title_QuerySetQuery: "Consultas ECL",
title_QuerySetSuperFiles: "Super Arquivos",
title_QueryTest: "Super Arquivos",
title_Result: "Resultados",
title_Results: "Atividade",
title_SearchResults: "Resultados de busca",
title_SourceFiles: "Arquivo(s) da Fonte",
title_SystemServers: "Servidores do sistema",
title_SystemServersLegacy: "Servidores do sistema (herdados)",
title_TargetClusters: "Clusters de Alvo",
title_Topology: "Topologia",
title_TpThorStatus: "Estado de Thor",
title_UserPermissions: "Permissões de usuário",
title_UserQuery: "Permissões",
title_WorkunitScopeDefaultPermissions: "Permissão Padrão de Unidades de Trabalho",
title_WUDetails: "Detalhes da Tarefa ECL",
title_WUQuery: "Tarefas de ECL",
To: "Para",
ToDate: "Data Final",
Toenablegraphviews: "Para ativar visão gráfica, por favor instalar o plugin",
Tooltip: "Dica de Ferramenta",
TooManyFiles: "Inumeros Arquivos",
Top: "Topo",
Topology: "Topologia",
ToSizes: "Tamanho Máximo",
Total: "Total",
TotalClusterTime: "Tempo total do bloco",
TotalParts: "Pedaços totais",
TotalSize: "Tamanho total",
TotalThorTime: "Tempo Total do Thor",
TransitionGuide: "Guia de transição",
Tree: "Árvore",
Type: "Tipo",
Unbound: "Desvinculado",
undefined: "Indefinido",
Unknown: "Desconhecido",
Unlock: "Desbloquear",
Unprotect: "Desprotege",
UnsupportedIE9FF: "Não Supportado",
Unsuspend: "Reativar",
Unsuspended: "Reativado",
Up: "Cima",
UpdateCloneFrom: "Atualizar clone de",
UpdateDFs: "Atualizar o DFS",
UpdateSuperFiles: "Actualizar superfile",
Upload: "Enviar",
UpTime: "Tempo de atividade",
URL: "URL",
Usage: "Uso",
Used: "Usado",
UsedByWorkunit: "Usado pela workunit",
User: "Usuário",
UserDetails: "Detalhes do usuário",
UserID: "Identificação do usurario",
UserLogin: "Por favor, faça o login usando apenas o seu nome de usuário",
Username: "Nome do usuário",
UserName: "<NAME> usuário",
UserPermissions: "Permissão do Usuário",
Users: "Usuários",
UseSingleConnection: "Usar Conexão Única",
Validate: "Validar",
ValidateActivePackageMap: "Validar pacote de mapa ativo",
ValidatePackageContent: "Validar pacote de conteúdo",
ValidatePackageMap: "Validar pacote de mapa",
ValidateResult: "=====Validar Resultado=====\n\n",
ValidateResultHere: "Validar resultados",
Validating: "Validando...",
Value: "Valor",
Variable: "Variável",
VariableBigendian: "Variavel Big-edian",
Variables: "Variáveis",
VariableSourceType: "Tipo de fonte",
Version: "Versão",
ViewByScope: "Visão por escopo",
Views: "Visões",
ViewSparkClusterInfo: "Exibir informações do cluster do Spark",
Visualize: "Visualizar",
WarnIfAvailableDiskSpaceIsUnder: "Avisar se o espaço disponível em disco estiver abaixo de",
WarnIfAvailableMemoryIsUnder: "Avisar se a memória disponível está abaixo de",
WarnIfCPUUsageIsOver: "Avisar se o uso da CPU está além",
Warning: "Atenção",
Warnings: "Avisos",
WarnOldGraphControl: "Alerta: Controle de grafico velho",
What: "O que",
Where: "Onde",
Who: "Quem",
Width: "Largura",
Workflows: "Fluxo de Trabalho",
Workunit: "Tarefa",
Workunits: "Tarefas",
WorkUnitScopeDefaultPermissions: "Permisos por defect de alcaces de Workunit",
Wrap: "Embrulho",
WSDL: "WSDL",
WUID: "WUID",
Wuidcannotbeempty: "Wuid não pode estar vazia",
WUSnapShot: "Instantâneo de WU",
XGMML: "XGMML",
XLS: "XLS",
XML: "XML",
XRef: "XRef",
Year: "Ano",
YouAreAboutToBeLoggedOut: "Você está prestes a ser desconectado",
YouAreAboutToDeleteBinding: "Está prestes a eliminar esta ligação. Você tem certeza que quer fazer isso?",
YouAreAboutToDeleteDefinition: "Você está prestes a deletar essa definição. Você tem certeza de que quer fazer isso?",
YouAreAboutToDeleteThisFile: "Você está prestes a excluir este arquivo. Você tem certeza de que quer fazer isso?",
YouAreAboutToDeleteThisPart: "Você está prestes a excluir esta(s) parte(s). Você tem certeza de que quer fazer isso?",
YouAreAboutToDeleteThisQueryset: "Você está prestes a excluir este conjunto de consultas. Você tem certeza de que quer fazer isso?",
YouAreAboutToDeleteThisWorkunit: "Você está prestes a excluir esta workunit. Você tem certeza de que quer fazer isso?",
YouAreAboutToRemoveUserFrom: "Usted esta a punto de quitar un(os) usuario(s) de este grupo. ¿Desea continuar?",
YourBrowserMayNotSupport: "O seu navegador provavelmente não supporta arquivo(s) deste tamanho",
YourScreenWasLocked: "Sua tela foi bloqueada por ESP. Por favor re-busque seus dados, pois pode ser obsoleto.",
ZAP: "Z.A.P",
ZeroLogicalFilesCheckFilter: "Nenhum Arquivo Lógico (verifique filtro)",
Zip: "Zip",
ZippedAnalysisPackage: "Pacote de Análise Zipped",
Zoom: "Ampliar",
Zoom100Pct: "Ampliar 100%",
ZoomAll: "Zoom Completo",
ZoomMinus: "Ampliar -",
ZoomPlus: "Ampliar +",
ZoomWidth: "comprimento do Zoom"
}
|
gfortil/HPCC-Platform
|
esp/src/src/ESPBase.ts
|
<gh_stars>1-10
import * as config from "dojo/_base/config";
import * as declare from "dojo/_base/declare";
declare const dojo;
export class ESPBase {
constructor(args?) {
if (args) {
declare.safeMixin(this, args);
}
}
getParam(key) {
const value = dojo.queryToObject(dojo.doc.location.search.substr((dojo.doc.location.search.substr(0, 1) === "?" ? 1 : 0)))[key];
if (value)
return value;
return config[key];
}
getBaseURL(service) {
if (!service) {
service = "WsWorkunits";
}
const serverIP = this.getParam("serverIP");
if (serverIP)
return "http://" + serverIP + ":8010/" + service;
return "/" + service;
}
getValue(domXml, tagName, knownObjectArrays) {
const retVal = this.getValues(domXml, tagName, knownObjectArrays);
if (retVal.length === 0) {
return null;
} else if (retVal.length !== 1) {
alert("Invalid length: " + retVal.length);
}
return retVal[0];
}
getValues(domXml, tagName, knownObjectArrays) {
const retVal = [];
const items = domXml.getElementsByTagName(tagName);
const parentNode = items.length ? items[0].parentNode : null; // Prevent <Dataset><row><field><row> scenario
for (let i = 0; i < items.length; ++i) {
if (items[i].parentNode === parentNode)
retVal.push(this.flattenXml(items[i], knownObjectArrays));
}
return retVal;
}
flattenXml(domXml, knownObjectArrays) {
const retValArr = [];
let retValStr = "";
const retVal = {};
for (let i = 0; i < domXml.childNodes.length; ++i) {
const childNode = domXml.childNodes[i];
if (childNode.childNodes) {
if (childNode.nodeName && knownObjectArrays != null && dojo.indexOf(knownObjectArrays, childNode.nodeName) >= 0) {
retValArr.push(this.flattenXml(childNode, knownObjectArrays));
} else if (childNode.nodeName === "#text") {
retValStr += childNode.nodeValue;
} else if (childNode.childNodes.length === 0) {
retVal[childNode.nodeName] = null;
} else {
const value = this.flattenXml(childNode, knownObjectArrays);
if (retVal[childNode.nodeName] == null) {
retVal[childNode.nodeName] = value;
} else if (dojo.isArray(retVal[childNode.nodeName])) {
retVal[childNode.nodeName].push(value);
} else if (dojo.isObject(retVal[childNode.nodeName])) {
const tmp = retVal[childNode.nodeName];
retVal[childNode.nodeName] = [];
retVal[childNode.nodeName].push(tmp);
retVal[childNode.nodeName].push(value);
}
}
}
}
if (retValArr.length)
return retValArr;
else if (retValStr.length)
return retValStr;
return retVal;
}
}
|
gfortil/HPCC-Platform
|
esp/src/src-react/components/Common.tsx
|
<gh_stars>1-10
import * as React from "react";
import { VerticalDivider } from "@fluentui/react";
export const ShortVerticalDivider = () => <VerticalDivider styles={{ divider: { paddingTop: "20%", height: "60%" } }} />;
|
gfortil/HPCC-Platform
|
esp/src/src-react/components/Frame.tsx
|
<filename>esp/src/src-react/components/Frame.tsx
import * as React from "react";
import { ThemeProvider } from "@fluentui/react";
import { HolyGrail } from "../layouts/HolyGrail";
import { hashHistory } from "../util/history";
import { router } from "../routes";
import { darkTheme, lightTheme } from "../themes";
import { DevTitle } from "./Title";
import { DevMenu } from "./Menu";
interface DevFrameProps {
}
export const DevFrame: React.FunctionComponent<DevFrameProps> = () => {
const [location, setLocation] = React.useState<string>("");
const [paths, setPaths] = React.useState<string[]>([]);
const [body, setBody] = React.useState(<h1>...loading...</h1>);
const [showMenu] = React.useState(true);
const [useDarkMode, setUseDarkMode] = React.useState(false);
React.useEffect(() => {
const unlisten = hashHistory.listen(async (location, action) => {
setLocation(location.pathname);
setPaths(location.pathname.split("/"));
document.title = `ECL Watch${location.pathname.split("/").join(" | ")}`;
setBody(await router.resolve(location));
});
router.resolve(hashHistory.location).then(setBody);
return () => unlisten();
}, []);
return <ThemeProvider theme={useDarkMode ? darkTheme : lightTheme} style={{ height: "100%" }}>
<HolyGrail
header={<DevTitle paths={paths} useDarkMode={useDarkMode} setUseDarkMode={setUseDarkMode} />}
left={showMenu ? <DevMenu location={location} /> : undefined}
main={<>
{body}
</>}
/>
</ThemeProvider >;
};
|
gfortil/HPCC-Platform
|
esp/src/src/react/hooks/useWsStore.ts
|
<filename>esp/src/src/react/hooks/useWsStore.ts
import { useEffect, useState } from "react";
import {getRecentFilters} from "../../KeyValStore";
export const useGet = (key: string, filter?: object) => {
const [responseState, setResponseState] = useState({ data: null, loading: true });
useEffect(() => {
setResponseState({ data: null, loading: true });
getRecentFilters(key).then(response => {
setResponseState({ data: response, loading: false });
});
}, [filter]);
return responseState;
};
|
gfortil/HPCC-Platform
|
esp/src/src-react/hooks/Workunit.ts
|
<reponame>gfortil/HPCC-Platform<gh_stars>0
import * as React from "react";
import { Workunit, Result, WUStateID, WUInfo } from "@hpcc-js/comms";
import nlsHPCC from "src/nlsHPCC";
export function useWorkunit(wuid: string, full: boolean = false): [Workunit, WUStateID] {
const [workunit, setWorkunit] = React.useState<Workunit>();
const [state, setState] = React.useState<WUStateID>();
React.useEffect(() => {
const wu = Workunit.attach({ baseUrl: "" }, wuid);
const handle = wu.watch(() => {
if (full) {
wu.refresh(true).then(() => {
setState(wu.StateID);
});
} else {
setState(wu.StateID);
}
});
setWorkunit(wu);
return () => {
handle.release();
};
}, [wuid, full]);
return [workunit, state];
}
export function useWorkunitResults(wuid: string): [Result[], Workunit, WUStateID] {
const [workunit, state] = useWorkunit(wuid);
const [results, setResults] = React.useState<Result[]>([]);
React.useEffect(() => {
workunit?.fetchResults().then(results => {
setResults(results);
});
}, [workunit, state]);
return [results, workunit, state];
}
export interface Variable {
Type: string;
Name: string;
Value: string;
}
export function useWorkunitVariables(wuid: string): [Variable[], Workunit, WUStateID] {
const [workunit, state] = useWorkunit(wuid);
const [variables, setVariables] = React.useState<Variable[]>([]);
React.useEffect(() => {
workunit?.fetchInfo({
IncludeVariables: true,
IncludeApplicationValues: true,
IncludeDebugValues: true
}).then(response => {
const vars: Variable[] = response?.Workunit?.Variables?.ECLResult?.map(row => {
return {
Type: nlsHPCC.ECL,
Name: row.Name,
Value: row.Value
};
}) || [];
const appData: Variable[] = response?.Workunit?.ApplicationValues?.ApplicationValue.map(row => {
return {
Type: row.Application,
Name: row.Name,
Value: row.Value
};
}) || [];
const debugData: Variable[] = response?.Workunit?.DebugValues?.DebugValue.map(row => {
return {
Type: nlsHPCC.Debug,
Name: row.Name,
Value: row.Value
};
}) || [];
setVariables([...vars, ...appData, ...debugData]);
});
}, [workunit, state]);
return [variables, workunit, state];
}
export interface SourceFile extends WUInfo.ECLSourceFile {
__hpcc_parentName: string;
}
export function useWorkunitSourceFiles(wuid: string): [SourceFile[], Workunit, WUStateID] {
const [workunit, state] = useWorkunit(wuid);
const [sourceFiles, setSourceFiles] = React.useState<SourceFile[]>([]);
React.useEffect(() => {
workunit?.fetchInfo({
IncludeSourceFiles: true
}).then(response => {
const sourceFiles: SourceFile[] = [];
response?.Workunit?.SourceFiles?.ECLSourceFile.forEach(sourceFile => {
sourceFiles.push({
__hpcc_parentName: "",
...sourceFile
});
sourceFile?.ECLSourceFiles?.ECLSourceFile.forEach(childSourceFile => {
sourceFiles.push({
__hpcc_parentName: sourceFile.Name,
...childSourceFile
});
});
});
setSourceFiles(sourceFiles);
});
}, [workunit, state]);
return [sourceFiles, workunit, state];
}
|
gfortil/HPCC-Platform
|
esp/src/src-react/components/Variables.tsx
|
import * as React from "react";
import { CommandBar, ContextualMenuItemType, ICommandBarItemProps } from "@fluentui/react";
import { useConst } from "@fluentui/react-hooks";
import * as Observable from "dojo/store/Observable";
import { AlphaNumSortMemory } from "src/Memory";
import * as Utility from "src/Utility";
import nlsHPCC from "src/nlsHPCC";
import { useWorkunitVariables } from "../hooks/Workunit";
import { HolyGrail } from "../layouts/HolyGrail";
import { ShortVerticalDivider } from "./Common";
import { DojoGrid } from "./DojoGrid";
const defaultUIState = {
hasSelection: false
};
interface VariablesProps {
wuid: string;
}
export const Variables: React.FunctionComponent<VariablesProps> = ({
wuid
}) => {
const [grid, setGrid] = React.useState<any>(undefined);
const [selection, setSelection] = React.useState([]);
const [uiState, setUIState] = React.useState({ ...defaultUIState });
const [variables] = useWorkunitVariables(wuid);
// Command Bar ---
const buttons: ICommandBarItemProps[] = [
{
key: "refresh", text: nlsHPCC.Refresh, iconProps: { iconName: "Refresh" },
onClick: () => refreshTable()
},
{ key: "divider_1", itemType: ContextualMenuItemType.Divider, onRender: () => <ShortVerticalDivider /> },
];
const rightButtons: ICommandBarItemProps[] = [
{
key: "copy", text: nlsHPCC.CopyWUIDs, disabled: !uiState.hasSelection || !navigator?.clipboard?.writeText, iconOnly: true, iconProps: { iconName: "Copy" },
onClick: () => {
const wuids = selection.map(s => s.Wuid);
navigator?.clipboard?.writeText(wuids.join("\n"));
}
},
{
key: "download", text: nlsHPCC.DownloadToCSV, disabled: !uiState.hasSelection, iconOnly: true, iconProps: { iconName: "Download" },
onClick: () => {
Utility.downloadToCSV(grid, selection.map(row => ([row.Protected, row.Wuid, row.Owner, row.Jobname, row.Cluster, row.RoxieCluster, row.State, row.TotalClusterTime])), "workunits.csv");
}
}
];
// Grid ---
const gridStore = useConst(new Observable(new AlphaNumSortMemory("__hpcc_id", { Name: true, Value: true })));
const gridSort = useConst([{ attribute: "Wuid", "descending": true }]);
const gridColumns = useConst({
Type: { label: nlsHPCC.Type, width: 180 },
Name: { label: nlsHPCC.Name, width: 360 },
Value: { label: nlsHPCC.Value }
});
const refreshTable = (clearSelection = false) => {
grid?.set("query", {});
if (clearSelection) {
grid?.clearSelection();
}
};
// Selection ---
React.useEffect(() => {
const state = { ...defaultUIState };
for (let i = 0; i < selection.length; ++i) {
state.hasSelection = true;
break;
}
setUIState(state);
}, [selection]);
React.useEffect(() => {
gridStore.setData(variables.map((row, idx) => {
return {
__hpcc_id: idx,
...row
};
}));
refreshTable();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [gridStore, variables]);
return <HolyGrail
header={<CommandBar items={buttons} overflowButtonProps={{}} farItems={rightButtons} />}
main={
<DojoGrid store={gridStore} query={{}} sort={gridSort} columns={gridColumns} setGrid={setGrid} setSelection={setSelection} />
}
/>;
};
|
gfortil/HPCC-Platform
|
esp/src/src-react/components/Filter.tsx
|
<gh_stars>1-10
import * as React from "react";
import { getTheme, mergeStyleSets, FontWeights, IDragOptions, IIconProps, ContextualMenu, DefaultButton, PrimaryButton, IconButton, Checkbox, Dropdown, IStackStyles, Modal, Stack, TextField, IDropdownProps, IDropdownOption } from "@fluentui/react";
import { useId } from "@fluentui/react-hooks";
import { TextField as MaterialUITextField } from "@material-ui/core";
import { Topology, TpLogicalClusterQuery } from "@hpcc-js/comms";
import { TpGroupQuery } from "src/WsTopology";
import { States } from "src/WsWorkunits";
import { States as DFUStates } from "src/FileSpray";
import nlsHPCC from "src/nlsHPCC";
type FieldType = "string" | "checkbox" | "datetime" |
"workunit-state" |
"file-type" | "file-sortby" |
"queries-suspend-state" | "queries-active-state" |
"target-cluster" | "target-group" |
"logicalfile-type" | "dfuworkunit-state";
const states = Object.keys(States).map(s => States[s]);
const dfustates = Object.keys(DFUStates).map(s => DFUStates[s]);
interface BaseField {
type: FieldType;
label: string;
disabled?: (params) => boolean;
placeholder?: string;
}
interface StringField extends BaseField {
type: "string";
value?: string;
}
interface DateTimeField extends BaseField {
type: "datetime";
value?: string;
}
interface CheckboxField extends BaseField {
type: "checkbox";
value?: boolean;
}
interface WorkunitStateField extends BaseField {
type: "workunit-state";
value?: string;
}
interface FileTypeField extends BaseField {
type: "file-type";
value?: string;
}
interface FileSortByField extends BaseField {
type: "file-sortby";
value?: string;
}
interface QueriesSuspendStateField extends BaseField {
type: "queries-suspend-state";
value?: string;
}
interface QueriesActiveStateField extends BaseField {
type: "queries-active-state";
value?: string;
}
interface TargetClusterField extends BaseField {
type: "target-cluster";
value?: string;
}
interface TargetGroupField extends BaseField {
type: "target-group";
value?: string;
}
interface LogicalFileType extends BaseField {
type: "logicalfile-type";
value?: string;
}
interface DFUWorkunitStateField extends BaseField {
type: "dfuworkunit-state";
value?: string;
}
type Field = StringField | CheckboxField | DateTimeField |
WorkunitStateField |
FileTypeField | FileSortByField |
QueriesSuspendStateField | QueriesActiveStateField |
TargetClusterField | TargetGroupField |
LogicalFileType | DFUWorkunitStateField;
export type Fields = { [name: string]: Field };
export type Values = { [name: string]: string | number | boolean | (string | number | boolean)[] };
const fieldsToRequest = (fields: Fields) => {
const retVal: Values = {};
for (const name in fields) {
if (!fields[name].disabled(fields)) {
retVal[name] = fields[name].value;
}
}
return retVal;
};
const TargetClusterTextField: React.FunctionComponent<IDropdownProps> = (props) => {
const [targetClusters, setTargetClusters] = React.useState<IDropdownOption[]>([]);
React.useEffect(() => {
const topology = new Topology({ baseUrl: "" });
topology.fetchLogicalClusters().then((response: TpLogicalClusterQuery.TpLogicalCluster[]) => {
setTargetClusters(
[
{ Name: "", Type: "", LanguageVersion: "", Process: "", Queue: "" },
...response
]
.map(n => {
return {
key: n.Name,
text: n.Name + (n.Name !== n.Type ? ` (${n.Type})` : "")
};
})
);
});
}, []);
return <Dropdown
{...props}
options={targetClusters}
/>;
};
export const TargetGroupTextField: React.FunctionComponent<IDropdownProps> = (props) => {
const [targetGroups, setTargetGroups] = React.useState<IDropdownOption[]>([]);
React.useEffect(() => {
TpGroupQuery({}).then(({ TpGroupQueryResponse }) => {
setTargetGroups(
TpGroupQueryResponse.TpGroups.TpGroup.map(n => {
return {
key: n.Name,
text: n.Name + (n.Name !== n.Kind ? ` (${n.Kind})` : "")
};
})
);
});
}, []);
return <Dropdown
{...props}
options={targetGroups}
/>;
};
interface FormContentProps {
fields: Fields;
doSubmit: boolean;
doReset: boolean;
onSubmit: (fields: Values) => void;
onReset: (fields: Values) => void;
}
export const FormContent: React.FunctionComponent<FormContentProps> = ({
fields,
doSubmit,
doReset,
onSubmit,
onReset
}) => {
const [localFields, setLocalFields] = React.useState<Fields>({ ...fields });
React.useEffect(() => {
if (doSubmit === false) return;
onSubmit(fieldsToRequest(localFields));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [doSubmit]);
React.useEffect(() => {
if (doReset === false) return;
for (const key in localFields) {
delete localFields[key].value;
}
setLocalFields(localFields);
onReset(fieldsToRequest(localFields));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [doReset]);
const handleChange = ev => {
const field = localFields[ev.target.name];
switch (field.type) {
case "checkbox":
field.value = ev.target.checked;
setLocalFields({ ...localFields });
break;
default:
field.value = ev.target.value;
setLocalFields({ ...localFields });
break;
}
};
const formFields = [];
for (const fieldID in localFields) {
const field: Field = localFields[fieldID];
if (!field.disabled) {
field.disabled = () => false;
}
switch (field.type) {
case "string":
field.value = field.value || "";
formFields.push(
<TextField
key={fieldID}
label={field.label}
type="string"
name={fieldID}
value={field.value}
placeholder={field.placeholder}
onChange={handleChange}
/>
);
break;
case "checkbox":
field.value = field.value || false;
formFields.push(
<Checkbox
key={fieldID}
label={field.label}
name={fieldID}
checked={field.value === true ? true : false}
onChange={handleChange}
/>
);
break;
case "datetime":
field.value = field.value || "";
formFields.push(
<MaterialUITextField
key={fieldID}
label={field.label}
type="datetime-local"
name={fieldID}
value={field.value}
placeholder={field.placeholder}
onChange={handleChange}
InputLabelProps={{ shrink: true }}
/>
);
break;
case "workunit-state":
field.value = field.value || "";
formFields.push(
<Dropdown
key={fieldID}
label={field.label}
defaultSelectedKey={field.value}
options={states.map(state => {
return {
key: state,
text: state
};
})}
onChange={(ev, row) => {
localFields[fieldID].value = row.key as string;
setLocalFields({ ...localFields });
}}
placeholder={field.placeholder}
/>
);
break;
case "file-type":
field.value = field.value || "";
formFields.push(
<Dropdown
key={fieldID}
label={field.label}
defaultSelectedKey={field.value}
options={[
{ key: "", text: nlsHPCC.LogicalFilesAndSuperfiles },
{ key: "Logical Files Only", text: nlsHPCC.LogicalFilesOnly },
{ key: "Superfiles Only", text: nlsHPCC.SuperfilesOnly },
{ key: "Not in Superfiles", text: nlsHPCC.NotInSuperfiles },
]}
onChange={(ev, row) => {
localFields[fieldID].value = row.key as string;
setLocalFields({ ...localFields });
}}
placeholder={field.placeholder}
/>
);
break;
case "file-sortby":
field.value = field.value || "";
formFields.push(
<Dropdown
key={fieldID}
label={field.label}
defaultSelectedKey={field.value}
options={[
{ key: "", text: "" },
{ key: "Newest", text: nlsHPCC.Newest },
{ key: "Oldest", text: nlsHPCC.Oldest },
{ key: "Smallest", text: nlsHPCC.Smallest },
{ key: "Largest", text: nlsHPCC.Largest }
]}
onChange={(ev, row) => {
localFields[fieldID].value = row.key as string;
setLocalFields({ ...localFields });
}}
placeholder={field.placeholder}
/>
);
break;
case "queries-suspend-state":
field.value = field.value || "";
formFields.push(
<Dropdown
key={fieldID}
label={field.label}
defaultSelectedKey={field.value}
options={[
{ key: "", text: "" },
{ key: "Not suspended", text: nlsHPCC.NotSuspended },
{ key: "Suspended", text: nlsHPCC.Suspended },
{ key: "Suspended by user", text: nlsHPCC.SuspendedByUser },
{ key: "Suspended by first node", text: nlsHPCC.SuspendedByFirstNode },
{ key: "Suspended by any node", text: nlsHPCC.SuspendedByAnyNode },
]}
onChange={(ev, row) => {
localFields[fieldID].value = row.key as string;
setLocalFields({ ...localFields });
}}
placeholder={field.placeholder}
/>
);
break;
case "queries-active-state":
field.value = field.value || "";
formFields.push(
<Dropdown
key={fieldID}
label={field.label}
defaultSelectedKey={field.value}
options={[
{ key: "", text: "" },
{ key: "1", text: nlsHPCC.Active },
{ key: "0", text: nlsHPCC.NotActive }
]}
onChange={(ev, row) => {
localFields[fieldID].value = row.key as string;
setLocalFields({ ...localFields });
}}
placeholder={field.placeholder}
/>
);
break;
case "target-cluster":
field.value = field.value || "";
formFields.push(
<TargetClusterTextField
key={fieldID}
label={field.label}
defaultSelectedKey={field.value}
onChange={(ev, row) => {
localFields[fieldID].value = row.key as string;
setLocalFields({ ...localFields });
}}
placeholder={field.placeholder}
options={[]}
/>
);
break;
case "target-group":
field.value = field.value || "";
formFields.push(
<TargetGroupTextField
key={fieldID}
label={field.label}
defaultSelectedKey=""
onChange={(ev, row) => {
localFields[fieldID].value = row.key as string;
setLocalFields({ ...localFields });
}}
placeholder={field.placeholder}
options={[]}
/>
);
break;
case "dfuworkunit-state":
field.value = field.value || "";
formFields.push(
<Dropdown
key={fieldID}
label={field.label}
defaultSelectedKey=""
options={dfustates.map(state => {
return {
key: state,
text: state
};
})}
onChange={(ev, row) => {
localFields[fieldID].value = row.key as string;
setLocalFields({ ...localFields });
}}
placeholder={field.placeholder}
/>
);
break;
case "logicalfile-type":
field.value = field.value || "Created";
formFields.push(
<Dropdown
key={fieldID}
label={field.label}
defaultSelectedKey=""
options={[
{ key: "Created", text: nlsHPCC.CreatedByWorkunit },
{ key: "Used", text: nlsHPCC.UsedByWorkunit }
]}
onChange={(ev, row) => {
localFields[fieldID].value = row.key as string;
setLocalFields({ ...localFields });
}}
placeholder={field.placeholder}
/>
);
break;
}
}
return <>
{...formFields}
</>;
};
interface FilterProps {
filterFields: Fields;
onApply: (values: Values) => void;
showFilter: boolean;
setShowFilter: (_: boolean) => void;
}
export const Filter: React.FunctionComponent<FilterProps> = ({
filterFields,
onApply,
showFilter,
setShowFilter
}) => {
const [doSubmit, setDoSubmit] = React.useState(false);
const [doReset, setDoReset] = React.useState(false);
const closeFilter = () => setShowFilter(false);
const titleId = useId("title");
const dragOptions: IDragOptions = {
moveMenuItemText: "Move",
closeMenuItemText: "Close",
menu: ContextualMenu,
};
const theme = getTheme();
const contentStyles = mergeStyleSets({
container: {
display: "flex",
flexFlow: "column nowrap",
alignItems: "stretch",
},
header: [
{
flex: "1 1 auto",
borderTop: `4px solid ${theme.palette.themePrimary}`,
color: theme.palette.neutralPrimary,
display: "flex",
alignItems: "center",
fontWeight: FontWeights.semibold,
padding: "12px 12px 14px 24px",
},
],
body: {
flex: "4 4 auto",
padding: "0 24px 24px 24px",
overflowY: "hidden",
selectors: {
p: { margin: "14px 0" },
"p:first-child": { marginTop: 0 },
"p:last-child": { marginBottom: 0 },
},
},
});
const cancelIcon: IIconProps = { iconName: "Cancel" };
const iconButtonStyles = {
root: {
color: theme.palette.neutralPrimary,
marginLeft: "auto",
marginTop: "4px",
marginRight: "2px",
},
rootHovered: {
color: theme.palette.neutralDark,
},
};
const buttonStackStyles: IStackStyles = {
root: {
height: "56px",
},
};
return <Modal
titleAriaId={titleId}
isOpen={showFilter}
onDismiss={closeFilter}
isBlocking={false}
containerClassName={contentStyles.container}
dragOptions={dragOptions}
>
<div className={contentStyles.header}>
<span id={titleId}>Filter</span>
<IconButton
styles={iconButtonStyles}
iconProps={cancelIcon}
ariaLabel="Close popup modal"
onClick={closeFilter}
/>
</div>
<div className={contentStyles.body}>
<Stack>
<FormContent
fields={filterFields}
doSubmit={doSubmit}
doReset={doReset}
onSubmit={fields => {
setDoSubmit(false);
onApply(fields);
}}
onReset={() => {
setDoReset(false);
}}
/>
</Stack>
<Stack
horizontal
horizontalAlign="space-between"
verticalAlign="end"
styles={buttonStackStyles}
>
<DefaultButton
text={nlsHPCC.Clear}
onClick={() => {
setDoReset(true);
}}
/>
<PrimaryButton
text={nlsHPCC.Apply}
onClick={() => {
setDoSubmit(true);
closeFilter();
}}
/>
</Stack>
</div>
</Modal>;
};
|
gfortil/HPCC-Platform
|
esp/src/src-react/components/WorkunitsDashboard.tsx
|
import * as React from "react";
import { Dropdown, IStackItemStyles, IStackStyles, IStackTokens, Overlay, Spinner, SpinnerSize, Stack, Text } from "@fluentui/react";
import { Card } from "@fluentui/react-cards";
import * as Observable from "dojo/store/Observable";
import * as ESPWorkunit from "src/ESPWorkunit";
import { WorkunitsService, WUQuery } from "@hpcc-js/comms";
import { Area, Column, Pie, Bar } from "@hpcc-js/chart";
import { chain, filter, group, map, sort } from "@hpcc-js/dataflow";
import Chip from "@material-ui/core/Chip";
import nlsHPCC from "src/nlsHPCC";
import { Memory } from "src/Memory";
import { pushParamExact } from "../util/history";
import { AutosizeHpccJSComponent } from "../layouts/HpccJSAdapter";
import { Workunits } from "./Workunits";
import { useConst } from "@fluentui/react-hooks";
const service = new WorkunitsService({ baseUrl: "" });
const wuidToDate = (wuid: string) => `${wuid.substr(1, 4)}-${wuid.substr(5, 2)}-${wuid.substr(7, 2)}`;
interface WorkunitEx extends WUQuery.ECLWorkunit {
Day: string;
}
export interface WorkunitsDashboardFilter {
lastNDays?: number;
cluster?: string;
owner?: string;
state?: string;
protected?: boolean;
day?: string;
}
export interface WorkunitsDashboardProps {
filterProps?: WorkunitsDashboardFilter;
}
export const WorkunitsDashboard: React.FunctionComponent<WorkunitsDashboardProps> = ({
filterProps
}) => {
filterProps = {
lastNDays: 7,
...filterProps
};
const [loading, setLoading] = React.useState(false);
const [workunits, setWorkunits] = React.useState<WorkunitEx[]>([]);
React.useEffect(() => {
setLoading(true);
setWorkunits([]);
const end = new Date();
const start = new Date();
start.setDate(start.getDate() - filterProps.lastNDays);
service.WUQuery({
StartDate: start.toISOString(),
EndDate: end.toISOString(),
PageSize: 999999
}).then(response => {
setWorkunits([...map(response.Workunits.ECLWorkunit, (row: WUQuery.ECLWorkunit) => ({ ...row, Day: wuidToDate(row.Wuid) }))]);
setLoading(false);
});
}, [filterProps.lastNDays]);
// Cluster Chart ---
const clusterChart = React.useRef(
new Bar()
.columns(["Cluster", "Count"])
.on("click", (row, col, sel) => pushParamExact("cluster", sel ? row.Cluster : undefined))
).current;
const clusterPipeline = chain(
filter<WorkunitEx>(row => filterProps.state === undefined || row.State === filterProps.state),
filter(row => filterProps.owner === undefined || row.Owner === filterProps.owner),
filter(row => filterProps.day === undefined || row.Day === filterProps.day),
filter(row => filterProps.protected === undefined || row.Protected === filterProps.protected),
group(row => row.Cluster),
map(row => [row.key, row.value.length] as [string, number]),
sort((l, r) => l[0].localeCompare(r[0])),
);
clusterChart
.data([...clusterPipeline(workunits)])
;
// Owner Chart ---
const ownerChart = React.useRef(
new Column()
.columns(["Owner", "Count"])
.on("click", (row, col, sel) => pushParamExact("owner", sel ? row.Owner : undefined))
).current;
const ownerPipeline = chain(
filter<WorkunitEx>(row => filterProps.cluster === undefined || row.Cluster === filterProps.cluster),
filter(row => filterProps.state === undefined || row.State === filterProps.state),
filter(row => filterProps.day === undefined || row.Day === filterProps.day),
filter(row => filterProps.protected === undefined || row.Protected === filterProps.protected),
group(row => row.Owner),
map(row => [row.key, row.value.length] as [string, number]),
sort((l, r) => l[0].localeCompare(r[0])),
);
ownerChart
.data([...ownerPipeline(workunits)])
;
// State Chart ---
const stateChart = React.useRef(
new Pie()
.columns(["State", "Count"])
.on("click", (row, col, sel) => pushParamExact("state", sel ? row.State : undefined))
).current;
const statePipeline = chain(
filter<WorkunitEx>(row => filterProps.cluster === undefined || row.Cluster === filterProps.cluster),
filter(row => filterProps.owner === undefined || row.Owner === filterProps.owner),
filter(row => filterProps.day === undefined || row.Day === filterProps.day),
filter(row => filterProps.protected === undefined || row.Protected === filterProps.protected),
group(row => row.State),
map(row => [row.key, row.value.length])
);
stateChart
.data([...statePipeline(workunits)])
;
// Protected Chart ---
const protectedChart = React.useRef(
new Pie()
.columns(["Protected", "Count"])
.on("click", (row, col, sel) => pushParamExact("protected", sel ? row.Protected === "true" : undefined))
).current;
const protectedPipeline = chain(
filter<WorkunitEx>(row => filterProps.cluster === undefined || row.Cluster === filterProps.cluster),
filter(row => filterProps.owner === undefined || row.Owner === filterProps.owner),
filter(row => filterProps.day === undefined || row.Day === filterProps.day),
group(row => "" + row.Protected),
map(row => [row.key, row.value.length])
);
protectedChart
.data([...protectedPipeline(workunits)])
;
// Day Chart ---
const dayChart = React.useRef(
new Area()
.columns(["Day", "Count"])
.xAxisType("time")
.interpolate("cardinal")
// .xAxisTypeTimePattern("")
.on("click", (row, col, sel) => pushParamExact("day", sel ? row.Day : undefined))
).current;
const dayPipeline = chain(
filter<WorkunitEx>(row => filterProps.cluster === undefined || row.Cluster === filterProps.cluster),
filter(row => filterProps.owner === undefined || row.Owner === filterProps.owner),
filter(row => filterProps.state === undefined || row.State === filterProps.state),
filter(row => filterProps.protected === undefined || row.Protected === filterProps.protected),
group(row => row.Day),
map(row => [row.key, row.value.length] as [string, number]),
sort((l, r) => l[0].localeCompare(r[0])),
);
dayChart
.data([...dayPipeline(workunits)])
;
// Table ---
const workunitsStore = useConst(new Observable(new Memory("Wuid")));
const tablePipeline = chain(
filter<WorkunitEx>(row => filterProps.cluster === undefined || row.Cluster === filterProps.cluster),
filter(row => filterProps.owner === undefined || row.Owner === filterProps.owner),
filter(row => filterProps.state === undefined || row.State === filterProps.state),
filter(row => filterProps.protected === undefined || row.Protected === filterProps.protected),
filter(row => filterProps.day === undefined || row.Day === filterProps.day),
map(row => ESPWorkunit.Get(row.Wuid, row))
);
workunitsStore.setData([...tablePipeline(workunits)]);
// --- --- ---
const stackStyles: IStackStyles = {
root: {
height: "100%",
},
};
const stackItemStyles: IStackItemStyles = {
root: {
minHeight: 240
},
};
const outerStackTokens: IStackTokens = { childrenGap: 5 };
const innerStackTokens: IStackTokens = {
childrenGap: 5,
padding: 10,
};
return <>
<Stack tokens={outerStackTokens} styles={{ root: { height: "100%" } }}>
<Stack styles={stackStyles} tokens={innerStackTokens}>
<Stack.Item styles={stackItemStyles}>
<Stack horizontal tokens={{ childrenGap: 16 }} >
<Stack.Item align="start" styles={{ root: { width: "25%", height: "100%" } }}>
<Card tokens={{ childrenMargin: 12, minWidth: "100%", minHeight: "100%" }}>
<Card.Item>
<Stack horizontal horizontalAlign="space-between">
<Text variant="large" nowrap block styles={{ root: { fontWeight: "bold" } }}>{nlsHPCC.State}</Text>
{filterProps.state !== undefined && <Chip label={filterProps.state} clickable color="primary" onDelete={() => pushParamExact("state", undefined)} />}
</Stack>
</Card.Item>
<Card.Item>
<AutosizeHpccJSComponent widget={stateChart} fixedHeight="240px" />
</Card.Item>
</Card>
</Stack.Item>
<Stack.Item align="center" styles={{ root: { width: "50%" } }}>
<Card tokens={{ childrenMargin: 12, minWidth: "100%" }} >
<Card.Item>
<Stack horizontal horizontalAlign="space-between">
<Text variant="large" nowrap block styles={{ root: { fontWeight: "bold" } }}>{nlsHPCC.Day}</Text>
{filterProps.day !== undefined && <Chip label={filterProps.day} clickable color="primary" onDelete={() => pushParamExact("day", undefined)} />}
<Dropdown onChange={(evt, opt, idx) => { pushParamExact("lastNDays", opt.key); }}
options={[
{ key: 1, text: "1 Day", selected: filterProps.lastNDays === 1 },
{ key: 2, text: "2 Days", selected: filterProps.lastNDays === 2 },
{ key: 3, text: "3 Days", selected: filterProps.lastNDays === 3 },
{ key: 7, text: "1 Week", selected: filterProps.lastNDays === 7 },
{ key: 14, text: "2 Weeks", selected: filterProps.lastNDays === 14 },
{ key: 21, text: "3 Weeks", selected: filterProps.lastNDays === 21 },
{ key: 31, text: "1 Month", selected: filterProps.lastNDays === 31 }
]}
/>
</Stack>
</Card.Item>
<Card.Item>
<AutosizeHpccJSComponent widget={dayChart} fixedHeight="240px" />
</Card.Item>
</Card>
</Stack.Item>
<Stack.Item align="end" styles={{ root: { width: "25%" } }}>
<Card tokens={{ childrenMargin: 12, minWidth: "100%" }}>
<Card.Item>
<Stack horizontal horizontalAlign="space-between">
<Text variant="large" nowrap block styles={{ root: { fontWeight: "bold" } }}>{nlsHPCC.Protected}</Text>
{filterProps.protected !== undefined && <Chip label={"" + filterProps.protected} clickable color="primary" onDelete={() => pushParamExact("protected", undefined)} />}
</Stack>
</Card.Item>
<Card.Item>
<AutosizeHpccJSComponent widget={protectedChart} fixedHeight="240px" />
</Card.Item>
</Card>
</Stack.Item>
</Stack>
</Stack.Item>
<Stack.Item styles={stackItemStyles}>
<Stack horizontal tokens={{ childrenGap: 16 }} >
<Stack.Item align="start" styles={{ root: { width: "66%" } }}>
<Card tokens={{ childrenMargin: 12, minWidth: "100%" }}>
<Card.Item>
<Stack horizontal horizontalAlign="space-between">
<Text variant="large" nowrap block styles={{ root: { fontWeight: "bold" } }}>{nlsHPCC.Owner}</Text>
{filterProps.owner !== undefined && <Chip label={filterProps.owner} clickable color="primary" onDelete={() => pushParamExact("owner", undefined)} />}
</Stack>
</Card.Item>
<Card.Item>
<AutosizeHpccJSComponent widget={ownerChart} fixedHeight="240px" />
</Card.Item>
</Card>
</Stack.Item>
<Stack.Item align="center" styles={{ root: { width: "34%" } }}>
<Card tokens={{ childrenMargin: 12, minWidth: "100%" }} >
<Card.Item>
<Stack horizontal horizontalAlign="space-between">
<Text variant="large" nowrap block styles={{ root: { fontWeight: "bold" } }}>{nlsHPCC.Cluster}</Text>
{filterProps.cluster !== undefined && <Chip label={filterProps.cluster} clickable color="primary" onDelete={() => pushParamExact("cluster", undefined)} />}
</Stack>
</Card.Item>
<Card.Item>
<AutosizeHpccJSComponent widget={clusterChart} fixedHeight="240px" />
</Card.Item>
</Card>
</Stack.Item>
</Stack>
</Stack.Item>
<Stack.Item grow={5} styles={stackItemStyles}>
<Card tokens={{ childrenMargin: 4, minWidth: "100%", height: "100%" }}>
<Card.Section tokens={{}} styles={{ root: { height: "100%" } }}>
<Workunits store={workunitsStore} />
</Card.Section>
</Card>
</Stack.Item>
</Stack>
</Stack>
{loading && <Overlay styles={{ root: { display: "flex", justifyContent: "center" } }}>
<Spinner label={nlsHPCC.Loading} size={SpinnerSize.large} />
</Overlay>}
</>;
};
|
gfortil/HPCC-Platform
|
esp/src/src/react/aboutDialog.tsx
|
import * as React from "react";
import { MuiThemeProvider } from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";
import Dialog from "@material-ui/core/Dialog";
import DialogActions from "@material-ui/core/DialogActions";
import DialogContent from "@material-ui/core/DialogContent";
import DialogTitle from "@material-ui/core/DialogTitle";
import ToggleButton from "@material-ui/lab/ToggleButton";
import Typography from "@material-ui/core/Typography";
import Box from "@material-ui/core/Box";
import { Bar } from "@hpcc-js/chart";
import { fetchStats } from "../KeyValStore";
import nlsHPCC from "../nlsHPCC";
import { theme } from "./theme";
import { VisualizationComponent } from "./vizComponent";
interface BarChart {
columns: string[];
data: (string | number)[][];
}
export const BarChart: React.FunctionComponent<BarChart> = ({
columns,
data
}) => {
return <VisualizationComponent widget={Bar} widgetProps={{ columns, data }} >
</VisualizationComponent>;
};
function TabPanel(props) {
const { children, value, index, ...other } = props;
return (
<div
role="tabpanel"
hidden={value !== index}
id={`simple-tabpanel-${index}`}
aria-labelledby={`simple-tab-${index}`}
{...other}
>
{value === index && (
<Box p={3}>
{children}
</Box>
)}
</div>
);
}
interface AboutDialog {
version: string;
handleClose: () => void;
}
export const AboutDialog: React.FunctionComponent<AboutDialog> = ({
version,
handleClose
}) => {
const [page, setPage] = React.useState(0);
const [columns] = React.useState([nlsHPCC.Client, nlsHPCC.Count]);
const [browser, setBrowser] = React.useState([]);
const [os, setOS] = React.useState([]);
React.useEffect(() => {
fetchStats().then(response => {
setBrowser(response.browser);
setOS(response.os);
});
}, []);
return (
<MuiThemeProvider theme={theme}>
<Dialog
open={true}
onClose={handleClose}
maxWidth="sm"
fullWidth={true}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
<DialogTitle id="alert-dialog-title">{nlsHPCC.AboutHPCCSystems}</DialogTitle>
<DialogContent>
<TabPanel value={page} index={0}>
<Typography align="center" >
<b>{nlsHPCC.Version}: </b>{version}
</Typography>
</TabPanel>
<TabPanel value={page} index={1}>
<BarChart columns={columns} data={browser}>
</BarChart>
</TabPanel>
<TabPanel value={page} index={2}>
<BarChart columns={columns} data={os}>
</BarChart>
</TabPanel>
</DialogContent>
<DialogActions>
<ToggleButton selected={page === 1} value="check" onChange={() => {
setPage(page === 1 ? 0 : 1);
}}>{nlsHPCC.BrowserStats}</ToggleButton>
<ToggleButton selected={page === 2} value="check" onChange={() => {
setPage(page === 2 ? 0 : 2);
}}>{nlsHPCC.OSStats}</ToggleButton>
<Button onClick={handleClose} color="primary" autoFocus>Close</Button>
</DialogActions>
</Dialog>
</MuiThemeProvider >
);
};
|
gfortil/HPCC-Platform
|
esp/src/src-react/hooks/Grid.ts
|
<reponame>gfortil/HPCC-Platform<gh_stars>1-10
export function useGrid(store, filter, sort, columns) {
return {
store,
filter,
sort,
columns
};
}
|
gfortil/HPCC-Platform
|
esp/src/src-react/layouts/HpccJSAdapter.tsx
|
<gh_stars>1-10
import * as React from "react";
import { useId } from "@fluentui/react-hooks";
import { SizeMe } from "react-sizeme";
import { Widget } from "@hpcc-js/common";
import "srcReact/layouts/HpccJSAdapter.css";
export interface HpccJSComponentProps {
widget: Widget;
width: number;
height: number;
debounce?: boolean;
}
export const HpccJSComponent: React.FunctionComponent<HpccJSComponentProps> = ({
widget,
width,
height,
debounce = true
}) => {
const divID = useId("viz-component-");
React.useEffect(() => {
widget
.target(divID)
.render()
;
return () => {
widget.target(null);
};
}, [divID, widget]);
if (widget.target()) {
widget.resize({ width, height });
if (debounce) {
widget.lazyRender();
} else {
widget.render();
}
}
return <div id={divID} className="hpcc-js-component" style={{ width, height }}>
</div>;
};
export interface AutosizeHpccJSComponentProps {
widget: Widget;
fixedHeight?: string;
debounce?: boolean;
}
export const AutosizeHpccJSComponent: React.FunctionComponent<AutosizeHpccJSComponentProps> = ({
widget,
fixedHeight = "100%",
debounce = true
}) => {
return <SizeMe monitorHeight>{({ size }) =>
<div style={{ width: "100%", height: fixedHeight, position: "relative" }}>
<div style={{ position: "absolute" }}>
<HpccJSComponent widget={widget} debounce={debounce} width={size.width} height={size.height} />
</div>
</div>
}
</SizeMe>;
};
|
freight-chain/besu-dev-kit
|
eth-sdk-master/packages/eth-sdk-key/src/Key.ts
|
<reponame>freight-chain/besu-dev-kit
import HDNode from 'hdkey';
import {
mnemonicToSeedSync,
} from 'bip39';
import {
IQuery,
WithQuery,
queryProviders,
queryModules,
} from '@eth-sdk/query';
import {
toHex,
randomPrivateKey,
verifyPrivateKey,
publicKeyToAddress,
privateToPublicKey,
signPersonalMessage,
TData,
TQuantity,
toChecksumAddress, toBuffer, toNumber,
} from '@eth-sdk/utils';
import { Transaction } from 'ethereumjs-tx';
import Common from 'ethereumjs-common';
export class Key extends WithQuery implements queryProviders.IProviderExtension {
private static DEFAULT_HD_PATH = 'm/44\'/60\'/0\'/0';
private nonce: number = null;
public static createRandom(query: IQuery = null): Key {
return new Key(
randomPrivateKey(),
query,
);
}
public static createLocalKeyFromMnemonic(mnemonic: string, query: IQuery = null, options: Key.IFromMnemonicOptionsSingle = {}): Key {
options = {
hdPath: this.DEFAULT_HD_PATH,
index: 0,
...options,
};
const {
hdPath,
password,
index,
} = options;
const [result] = this.createLocalKeysFromMnemonic(mnemonic, query, {
hdPath,
password,
fromIndex: index,
toIndex: index,
});
return result || null;
}
public static createLocalKeysFromMnemonic(mnemonic: string, query: IQuery = null, options: Key.IFromMnemonicOptionsMany = {}): Key[] {
const result: Key[] = [];
options = {
hdPath: this.DEFAULT_HD_PATH,
fromIndex: 0,
toIndex: 9,
...options,
};
const {
hdPath,
password,
fromIndex,
toIndex,
} = options;
const seed = mnemonicToSeedSync(mnemonic, password);
const rootHdNode = HDNode.fromMasterSeed(seed);
for (let index = fromIndex; index <= toIndex; index += 1) {
const hdNode = rootHdNode.derive(`${hdPath}/${index}`);
const privateKey = toHex(hdNode.privateKey);
result.push(
new Key(privateKey, query),
);
}
return result;
}
public readonly type: Key.Types = null;
private currentAddress: string;
constructor(public privateKey: string = null, query: IQuery = null) {
super(query);
if (privateKey) {
if (!verifyPrivateKey(privateKey)) {
throw new Error('invalid private key');
}
this.currentAddress = publicKeyToAddress(
privateToPublicKey(privateKey),
);
this.type = Key.Types.Local;
} else if (query) {
this.type = Key.Types.Network;
}
}
public get address(): string {
return this.currentAddress;
}
public async fetchAddress(index: number = 0): Promise<void> {
if (this.type === Key.Types.Network) {
const addresses = await this.query.eth.accounts;
const address = toChecksumAddress(addresses[index]);
this.currentAddress = address;
}
}
public async signPersonalMessage(message: TData): Promise<string> {
let result: string = null;
switch (this.type) {
case Key.Types.Local:
result = signPersonalMessage(
message,
this.privateKey,
);
break;
case Key.Types.Network:
result = await this.query.eth.sign(
this.address,
toHex(message),
);
break;
default:
throw new Error('invalid private key');
}
return result;
}
public async signTransaction(options: Key.ISignTransactionOptions): Promise<string> {
let result: string = null;
if (this.type === Key.Types.Local) {
const {
to,
value,
data,
} = options;
let {
nonce,
gasPrice,
gas,
} = options;
if (!nonce) {
nonce = await this.query.eth.getTransactionCount(this.address, 'pending');
if (this.nonce !== null && this.nonce >= nonce) {
nonce = this.nonce + 1;
}
this.nonce = nonce;
} else {
this.nonce = toNumber(nonce);
}
if (!gasPrice) {
gasPrice = await this.query.eth.gasPrice;
}
if (!gas) {
gas = 21000;
}
const chainId = await this.query.eth.chainId;
const networkId = await this.query.net.version;
let common: Common = null;
try {
common = new Common(chainId, 'istanbul');
} catch (err) {
common = Common.forCustomChain(1, {
chainId,
networkId,
comment: 'Custom chain',
}, 'istanbul');
}
const transaction = new Transaction({
to,
nonce: toHex(nonce, '0x00', true),
gasLimit: toHex(gas, '0x00', true),
gasPrice: toHex(gasPrice, '0x00', true),
value: toHex(value, '0x00', true),
data: toHex(data, '0x'),
}, {
common,
});
transaction.sign(toBuffer(this.privateKey));
result = toHex(transaction.serialize());
} else {
throw new Error('invalid key');
}
return result;
}
public async extendProvider(method: string, params: any[]): Promise<any> {
let result: any = null;
if (this.type === Key.Types.Local) {
switch (method) {
case queryModules.Eth.Methods.Accounts: {
result = [this.address];
break;
}
case queryModules.Eth.Methods.Sign: {
let address: string;
let data: string;
([address, data] = params);
address = toChecksumAddress(address);
if (address === this.address) {
result = await this.signPersonalMessage(data);
}
break;
}
case queryModules.Eth.Methods.SendTransaction: {
let options: queryModules.Eth.ISendTransactionOptions;
([options] = params);
const {
from,
to,
data,
value,
nonce,
gas,
gasPrice,
} = options;
if (from === this.address) {
const raw = await this.signTransaction({
to,
nonce,
data,
value,
gas,
gasPrice,
});
result = await this.query.eth.sendRawTransaction(raw);
}
break;
}
}
}
return result;
}
}
export namespace Key {
export enum Types {
Network = 'Network',
Local = 'Local',
}
export interface IFromMnemonicOptions {
hdPath?: string;
password?: string;
}
export interface IFromMnemonicOptionsSingle extends IFromMnemonicOptions {
index?: number;
}
export interface IFromMnemonicOptionsMany extends IFromMnemonicOptions {
fromIndex?: number;
toIndex?: number;
}
export interface ISignTransactionOptions {
nonce?: TQuantity;
gas?: TQuantity;
gasPrice?: TQuantity;
to: string;
value?: TQuantity;
data?: TData;
}
}
|
netfarma/openapi-generator
|
samples/client/petstore-security-test/typescript-node/api/apis.ts
|
<filename>samples/client/petstore-security-test/typescript-node/api/apis.ts
export * from './fakeApi';
import { FakeApi } from './fakeApi';
export const APIS = [FakeApi];
|
netfarma/openapi-generator
|
samples/client/petstore/typescript-jquery/default/api/UserApi.ts
|
<gh_stars>1-10
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import * as $ from 'jquery';
import * as models from '../model/models';
import { COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
/* tslint:disable:no-unused-variable member-ordering */
export class UserApi {
protected basePath = 'http://petstore.swagger.io/v2';
public defaultHeaders: Array<string> = [];
public defaultExtraJQueryAjaxSettings?: JQueryAjaxSettings = null;
public configuration: Configuration = new Configuration();
constructor(basePath?: string, configuration?: Configuration, defaultExtraJQueryAjaxSettings?: JQueryAjaxSettings) {
if (basePath) {
this.basePath = basePath;
}
if (configuration) {
this.configuration = configuration;
}
if (defaultExtraJQueryAjaxSettings) {
this.defaultExtraJQueryAjaxSettings = defaultExtraJQueryAjaxSettings;
}
}
private extendObj<T1, T2 extends T1>(objA: T2, objB: T2): T1|T2 {
for (let key in objB) {
if (objB.hasOwnProperty(key)) {
objA[key] = objB[key];
}
}
return objA;
}
/**
* This can only be done by the logged in user.
* @summary Create user
* @param user Created user object
*/
public createUser(user: models.User, extraJQueryAjaxSettings?: JQueryAjaxSettings): JQuery.Promise<
{ response: JQueryXHR; body?: any; },
{ response: JQueryXHR; errorThrown: string }
> {
let localVarPath = this.basePath + '/user';
let queryParameters: any = {};
let headerParams: any = {};
// verify required parameter 'user' is not null or undefined
if (user === null || user === undefined) {
throw new Error('Required parameter user was null or undefined when calling createUser.');
}
localVarPath = localVarPath + "?" + $.param(queryParameters);
// to determine the Content-Type header
let consumes: string[] = [
];
// to determine the Accept header
let produces: string[] = [
];
headerParams['Content-Type'] = 'application/json';
let requestOptions: JQueryAjaxSettings = {
url: localVarPath,
type: 'POST',
headers: headerParams,
processData: false
};
requestOptions.data = JSON.stringify(user);
if (headerParams['Content-Type']) {
requestOptions.contentType = headerParams['Content-Type'];
}
if (extraJQueryAjaxSettings) {
requestOptions = (<any>Object).assign(requestOptions, extraJQueryAjaxSettings);
}
if (this.defaultExtraJQueryAjaxSettings) {
requestOptions = (<any>Object).assign(requestOptions, this.defaultExtraJQueryAjaxSettings);
}
let dfd = $.Deferred<
{ response: JQueryXHR; body?: any; },
{ response: JQueryXHR; errorThrown: string }
>();
$.ajax(requestOptions).then(
(data: any, textStatus: string, jqXHR: JQueryXHR) =>
dfd.resolve({response: jqXHR, body: data}),
(xhr: JQueryXHR, textStatus: string, errorThrown: string) =>
dfd.reject({response: xhr, errorThrown: errorThrown})
);
return dfd.promise();
}
/**
*
* @summary Creates list of users with given input array
* @param modelsUser List of user object
*/
public createUsersWithArrayInput(modelsUser: Array<models.User>, extraJQueryAjaxSettings?: JQueryAjaxSettings): JQuery.Promise<
{ response: JQueryXHR; body?: any; },
{ response: JQueryXHR; errorThrown: string }
> {
let localVarPath = this.basePath + '/user/createWithArray';
let queryParameters: any = {};
let headerParams: any = {};
// verify required parameter 'modelsUser' is not null or undefined
if (modelsUser === null || modelsUser === undefined) {
throw new Error('Required parameter modelsUser was null or undefined when calling createUsersWithArrayInput.');
}
localVarPath = localVarPath + "?" + $.param(queryParameters);
// to determine the Content-Type header
let consumes: string[] = [
];
// to determine the Accept header
let produces: string[] = [
];
headerParams['Content-Type'] = 'application/json';
let requestOptions: JQueryAjaxSettings = {
url: localVarPath,
type: 'POST',
headers: headerParams,
processData: false
};
requestOptions.data = JSON.stringify(modelsUser);
if (headerParams['Content-Type']) {
requestOptions.contentType = headerParams['Content-Type'];
}
if (extraJQueryAjaxSettings) {
requestOptions = (<any>Object).assign(requestOptions, extraJQueryAjaxSettings);
}
if (this.defaultExtraJQueryAjaxSettings) {
requestOptions = (<any>Object).assign(requestOptions, this.defaultExtraJQueryAjaxSettings);
}
let dfd = $.Deferred<
{ response: JQueryXHR; body?: any; },
{ response: JQueryXHR; errorThrown: string }
>();
$.ajax(requestOptions).then(
(data: any, textStatus: string, jqXHR: JQueryXHR) =>
dfd.resolve({response: jqXHR, body: data}),
(xhr: JQueryXHR, textStatus: string, errorThrown: string) =>
dfd.reject({response: xhr, errorThrown: errorThrown})
);
return dfd.promise();
}
/**
*
* @summary Creates list of users with given input array
* @param modelsUser List of user object
*/
public createUsersWithListInput(modelsUser: Array<models.User>, extraJQueryAjaxSettings?: JQueryAjaxSettings): JQuery.Promise<
{ response: JQueryXHR; body?: any; },
{ response: JQueryXHR; errorThrown: string }
> {
let localVarPath = this.basePath + '/user/createWithList';
let queryParameters: any = {};
let headerParams: any = {};
// verify required parameter 'modelsUser' is not null or undefined
if (modelsUser === null || modelsUser === undefined) {
throw new Error('Required parameter modelsUser was null or undefined when calling createUsersWithListInput.');
}
localVarPath = localVarPath + "?" + $.param(queryParameters);
// to determine the Content-Type header
let consumes: string[] = [
];
// to determine the Accept header
let produces: string[] = [
];
headerParams['Content-Type'] = 'application/json';
let requestOptions: JQueryAjaxSettings = {
url: localVarPath,
type: 'POST',
headers: headerParams,
processData: false
};
requestOptions.data = JSON.stringify(modelsUser);
if (headerParams['Content-Type']) {
requestOptions.contentType = headerParams['Content-Type'];
}
if (extraJQueryAjaxSettings) {
requestOptions = (<any>Object).assign(requestOptions, extraJQueryAjaxSettings);
}
if (this.defaultExtraJQueryAjaxSettings) {
requestOptions = (<any>Object).assign(requestOptions, this.defaultExtraJQueryAjaxSettings);
}
let dfd = $.Deferred<
{ response: JQueryXHR; body?: any; },
{ response: JQueryXHR; errorThrown: string }
>();
$.ajax(requestOptions).then(
(data: any, textStatus: string, jqXHR: JQueryXHR) =>
dfd.resolve({response: jqXHR, body: data}),
(xhr: JQueryXHR, textStatus: string, errorThrown: string) =>
dfd.reject({response: xhr, errorThrown: errorThrown})
);
return dfd.promise();
}
/**
* This can only be done by the logged in user.
* @summary Delete user
* @param username The name that needs to be deleted
*/
public deleteUser(username: string, extraJQueryAjaxSettings?: JQueryAjaxSettings): JQuery.Promise<
{ response: JQueryXHR; body?: any; },
{ response: JQueryXHR; errorThrown: string }
> {
let localVarPath = this.basePath + '/user/{username}'.replace('{' + 'username' + '}', encodeURIComponent(String(username)));
let queryParameters: any = {};
let headerParams: any = {};
// verify required parameter 'username' is not null or undefined
if (username === null || username === undefined) {
throw new Error('Required parameter username was null or undefined when calling deleteUser.');
}
localVarPath = localVarPath + "?" + $.param(queryParameters);
// to determine the Content-Type header
let consumes: string[] = [
];
// to determine the Accept header
let produces: string[] = [
];
let requestOptions: JQueryAjaxSettings = {
url: localVarPath,
type: 'DELETE',
headers: headerParams,
processData: false
};
if (headerParams['Content-Type']) {
requestOptions.contentType = headerParams['Content-Type'];
}
if (extraJQueryAjaxSettings) {
requestOptions = (<any>Object).assign(requestOptions, extraJQueryAjaxSettings);
}
if (this.defaultExtraJQueryAjaxSettings) {
requestOptions = (<any>Object).assign(requestOptions, this.defaultExtraJQueryAjaxSettings);
}
let dfd = $.Deferred<
{ response: JQueryXHR; body?: any; },
{ response: JQueryXHR; errorThrown: string }
>();
$.ajax(requestOptions).then(
(data: any, textStatus: string, jqXHR: JQueryXHR) =>
dfd.resolve({response: jqXHR, body: data}),
(xhr: JQueryXHR, textStatus: string, errorThrown: string) =>
dfd.reject({response: xhr, errorThrown: errorThrown})
);
return dfd.promise();
}
/**
*
* @summary Get user by user name
* @param username The name that needs to be fetched. Use user1 for testing.
*/
public getUserByName(username: string, extraJQueryAjaxSettings?: JQueryAjaxSettings): JQuery.Promise<
{ response: JQueryXHR; body: models.User; },
{ response: JQueryXHR; errorThrown: string }
> {
let localVarPath = this.basePath + '/user/{username}'.replace('{' + 'username' + '}', encodeURIComponent(String(username)));
let queryParameters: any = {};
let headerParams: any = {};
// verify required parameter 'username' is not null or undefined
if (username === null || username === undefined) {
throw new Error('Required parameter username was null or undefined when calling getUserByName.');
}
localVarPath = localVarPath + "?" + $.param(queryParameters);
// to determine the Content-Type header
let consumes: string[] = [
];
// to determine the Accept header
let produces: string[] = [
'application/xml',
'application/json'
];
let requestOptions: JQueryAjaxSettings = {
url: localVarPath,
type: 'GET',
headers: headerParams,
processData: false
};
if (headerParams['Content-Type']) {
requestOptions.contentType = headerParams['Content-Type'];
}
if (extraJQueryAjaxSettings) {
requestOptions = (<any>Object).assign(requestOptions, extraJQueryAjaxSettings);
}
if (this.defaultExtraJQueryAjaxSettings) {
requestOptions = (<any>Object).assign(requestOptions, this.defaultExtraJQueryAjaxSettings);
}
let dfd = $.Deferred<
{ response: JQueryXHR; body: models.User; },
{ response: JQueryXHR; errorThrown: string }
>();
$.ajax(requestOptions).then(
(data: models.User, textStatus: string, jqXHR: JQueryXHR) =>
dfd.resolve({response: jqXHR, body: data}),
(xhr: JQueryXHR, textStatus: string, errorThrown: string) =>
dfd.reject({response: xhr, errorThrown: errorThrown})
);
return dfd.promise();
}
/**
*
* @summary Logs user into the system
* @param username The user name for login
* @param password The password for login in clear text
*/
public loginUser(username: string, password: string, extraJQueryAjaxSettings?: JQueryAjaxSettings): JQuery.Promise<
{ response: JQueryXHR; body: string; },
{ response: JQueryXHR; errorThrown: string }
> {
let localVarPath = this.basePath + '/user/login';
let queryParameters: any = {};
let headerParams: any = {};
// verify required parameter 'username' is not null or undefined
if (username === null || username === undefined) {
throw new Error('Required parameter username was null or undefined when calling loginUser.');
}
// verify required parameter 'password' is not null or undefined
if (password === null || password === undefined) {
throw new Error('Required parameter password was null or undefined when calling loginUser.');
}
if (username !== null && username !== undefined) {
queryParameters['username'] = <string><any>username;
}
if (password !== null && password !== undefined) {
queryParameters['password'] = <string><any>password;
}
localVarPath = localVarPath + "?" + $.param(queryParameters);
// to determine the Content-Type header
let consumes: string[] = [
];
// to determine the Accept header
let produces: string[] = [
'application/xml',
'application/json'
];
let requestOptions: JQueryAjaxSettings = {
url: localVarPath,
type: 'GET',
headers: headerParams,
processData: false
};
if (headerParams['Content-Type']) {
requestOptions.contentType = headerParams['Content-Type'];
}
if (extraJQueryAjaxSettings) {
requestOptions = (<any>Object).assign(requestOptions, extraJQueryAjaxSettings);
}
if (this.defaultExtraJQueryAjaxSettings) {
requestOptions = (<any>Object).assign(requestOptions, this.defaultExtraJQueryAjaxSettings);
}
let dfd = $.Deferred<
{ response: JQueryXHR; body: string; },
{ response: JQueryXHR; errorThrown: string }
>();
$.ajax(requestOptions).then(
(data: string, textStatus: string, jqXHR: JQueryXHR) =>
dfd.resolve({response: jqXHR, body: data}),
(xhr: JQueryXHR, textStatus: string, errorThrown: string) =>
dfd.reject({response: xhr, errorThrown: errorThrown})
);
return dfd.promise();
}
/**
*
* @summary Logs out current logged in user session
*/
public logoutUser(extraJQueryAjaxSettings?: JQueryAjaxSettings): JQuery.Promise<
{ response: JQueryXHR; body?: any; },
{ response: JQueryXHR; errorThrown: string }
> {
let localVarPath = this.basePath + '/user/logout';
let queryParameters: any = {};
let headerParams: any = {};
localVarPath = localVarPath + "?" + $.param(queryParameters);
// to determine the Content-Type header
let consumes: string[] = [
];
// to determine the Accept header
let produces: string[] = [
];
let requestOptions: JQueryAjaxSettings = {
url: localVarPath,
type: 'GET',
headers: headerParams,
processData: false
};
if (headerParams['Content-Type']) {
requestOptions.contentType = headerParams['Content-Type'];
}
if (extraJQueryAjaxSettings) {
requestOptions = (<any>Object).assign(requestOptions, extraJQueryAjaxSettings);
}
if (this.defaultExtraJQueryAjaxSettings) {
requestOptions = (<any>Object).assign(requestOptions, this.defaultExtraJQueryAjaxSettings);
}
let dfd = $.Deferred<
{ response: JQueryXHR; body?: any; },
{ response: JQueryXHR; errorThrown: string }
>();
$.ajax(requestOptions).then(
(data: any, textStatus: string, jqXHR: JQueryXHR) =>
dfd.resolve({response: jqXHR, body: data}),
(xhr: JQueryXHR, textStatus: string, errorThrown: string) =>
dfd.reject({response: xhr, errorThrown: errorThrown})
);
return dfd.promise();
}
/**
* This can only be done by the logged in user.
* @summary Updated user
* @param username name that need to be deleted
* @param user Updated user object
*/
public updateUser(username: string, user: models.User, extraJQueryAjaxSettings?: JQueryAjaxSettings): JQuery.Promise<
{ response: JQueryXHR; body?: any; },
{ response: JQueryXHR; errorThrown: string }
> {
let localVarPath = this.basePath + '/user/{username}'.replace('{' + 'username' + '}', encodeURIComponent(String(username)));
let queryParameters: any = {};
let headerParams: any = {};
// verify required parameter 'username' is not null or undefined
if (username === null || username === undefined) {
throw new Error('Required parameter username was null or undefined when calling updateUser.');
}
// verify required parameter 'user' is not null or undefined
if (user === null || user === undefined) {
throw new Error('Required parameter user was null or undefined when calling updateUser.');
}
localVarPath = localVarPath + "?" + $.param(queryParameters);
// to determine the Content-Type header
let consumes: string[] = [
];
// to determine the Accept header
let produces: string[] = [
];
headerParams['Content-Type'] = 'application/json';
let requestOptions: JQueryAjaxSettings = {
url: localVarPath,
type: 'PUT',
headers: headerParams,
processData: false
};
requestOptions.data = JSON.stringify(user);
if (headerParams['Content-Type']) {
requestOptions.contentType = headerParams['Content-Type'];
}
if (extraJQueryAjaxSettings) {
requestOptions = (<any>Object).assign(requestOptions, extraJQueryAjaxSettings);
}
if (this.defaultExtraJQueryAjaxSettings) {
requestOptions = (<any>Object).assign(requestOptions, this.defaultExtraJQueryAjaxSettings);
}
let dfd = $.Deferred<
{ response: JQueryXHR; body?: any; },
{ response: JQueryXHR; errorThrown: string }
>();
$.ajax(requestOptions).then(
(data: any, textStatus: string, jqXHR: JQueryXHR) =>
dfd.resolve({response: jqXHR, body: data}),
(xhr: JQueryXHR, textStatus: string, errorThrown: string) =>
dfd.reject({response: xhr, errorThrown: errorThrown})
);
return dfd.promise();
}
}
|
netfarma/openapi-generator
|
samples/client/petstore/typescript-axios/tests/default/test/PetApiFactory.ts
|
<reponame>netfarma/openapi-generator
import { expect } from "chai";
import {
PetApiFactory,
Pet,
Category
} from "@swagger/typescript-axios-petstore";
import { Configuration } from "@swagger/typescript-axios-petstore";
import axios, {AxiosInstance, AxiosResponse} from "axios";
let config: Configuration;
before(function() {
config = new Configuration();
config.accessToken = "foobar";
config.apiKey = (securityName: string) => {
// for multiple apiKey security
if (securityName === "api_key") {
return "foobar";
}
return;
};
config.username = "foo";
config.password = "<PASSWORD>";
});
describe("PetApiFactory", () => {
function runSuite(description: string, requestOptions?: any, customAxiosInstance?: AxiosInstance): void {
describe(description, () => {
const fixture: Pet = createTestFixture();
it("should add and delete Pet", () => {
return PetApiFactory(config, undefined, customAxiosInstance)
.addPet(fixture, requestOptions)
.then(() => {});
});
it("should get Pet by ID", () => {
return PetApiFactory(config, undefined, customAxiosInstance)
.getPetById(fixture.id, requestOptions)
.then((result: AxiosResponse<Pet>) => {
return expect(result.data).to.deep.equal(fixture);
});
});
it("should update Pet by ID", () => {
return PetApiFactory(config, undefined, customAxiosInstance)
.getPetById(fixture.id, requestOptions)
.then((result: AxiosResponse<Pet>) => {
result.data.name = "newname";
return PetApiFactory(config)
.updatePet(result.data, requestOptions)
.then(() => {
return PetApiFactory(config)
.getPetById(fixture.id, requestOptions)
.then((result: AxiosResponse<Pet>) => {
return expect(result.data.name).to.deep.equal("newname");
});
});
});
});
it("should delete Pet", () => {
return PetApiFactory(config, undefined, customAxiosInstance).deletePet(fixture.id, requestOptions);
});
it("should not contain deleted Pet", () => {
return PetApiFactory(config, undefined, customAxiosInstance)
.getPetById(fixture.id, requestOptions)
.then(
(result: AxiosResponse<Pet>) => {
return expect(result.data).to.not.exist;
},
(err: any) => {
return expect(err).to.exist;
}
);
});
});
}
runSuite("without custom request options");
runSuite("with custom request options", {
credentials: "include",
mode: "cors"
});
runSuite("without custom axios instance");
runSuite("with custom axios instance",{}, axios);
runSuite("with custom request options and custom axios instance",{
credentials: "include",
mode: "cors"
}, axios);
});
function createTestFixture(ts = Date.now()) {
const category: Category = {
id: ts,
name: `category${ts}`
};
const pet: Pet = {
id: ts,
name: `pet${ts}`,
category: category,
photoUrls: ["http://foo.bar.com/1", "http://foo.bar.com/2"],
status: Pet.StatusEnum.Available,
tags: []
};
return pet;
}
|
netfarma/openapi-generator
|
samples/client/petstore/typescript-node/npm/api/apis.ts
|
<gh_stars>1-10
export * from './petApi';
import { PetApi } from './petApi';
export * from './storeApi';
import { StoreApi } from './storeApi';
export * from './userApi';
import { UserApi } from './userApi';
export const APIS = [PetApi, StoreApi, UserApi];
|
netfarma/openapi-generator
|
samples/client/petstore-security-test/typescript-fetch/index.ts
|
// tslint:disable
/**
* OpenAPI Petstore *_/ ' \" =end -- \\r\\n \\n \\r
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end --
*
* OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r
* Contact: <EMAIL> *_/ ' \" =end -- \\r\\n \\n \\r
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export * from "./api";
export * from "./configuration";
|
netfarma/openapi-generator
|
samples/client/petstore/typescript-aurelia/default/AuthStorage.ts
|
<filename>samples/client/petstore/typescript-aurelia/default/AuthStorage.ts
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* Class to storage authentication data
*/
export class AuthStorage {
private storage: Map<string, string>;
constructor() {
this.storage = new Map();
}
/**
* Sets the api_key auth method value.
*
* @param value The new value to set for api_key.
*/
setapi_key(value: string): this {
this.storage.set('api_key', value);
return this;
}
/**
* Removes the api_key auth method value.
*/
removeapi_key(): this {
this.storage.delete('api_key');
return this;
}
/**
* Gets the api_key auth method value.
*/
getapi_key(): null | string {
return this.storage.get('api_key') || null;
}
/**
* Sets the petstore_auth auth method value.
*
* @param value The new value to set for petstore_auth.
*/
setpetstore_auth(value: string): this {
this.storage.set('petstore_auth', value);
return this;
}
/**
* Removes the petstore_auth auth method value.
*/
removepetstore_auth(): this {
this.storage.delete('petstore_auth');
return this;
}
/**
* Gets the petstore_auth auth method value.
*/
getpetstore_auth(): null | string {
return this.storage.get('petstore_auth') || null;
}
}
|
izetmolla/react-theme-ui
|
src/index.tsx
|
<filename>src/index.tsx
import { NativeModules } from 'react-native';
type ReactThemeUiType = {
multiply(a: number, b: number): Promise<number>;
};
const { ReactThemeUi } = NativeModules;
export default ReactThemeUi as ReactThemeUiType;
|
hypercodex/vizkite
|
src/vizkite.tsx
|
import React, { useRef, useLayoutEffect } from 'react'
export type TargetRef = React.MutableRefObject<HTMLDivElement>
export interface D3CallbackSignature<D, O> {
(
ref: TargetRef,
data: D,
options?: O
): void;
}
export interface D3Callback {
<D, O>(
ref: TargetRef,
data: D,
options?: O
): void;
}
export interface D3HookFunction {
<D, O>(
d3Callback: D3CallbackSignature<D, O>,
data: D,
options?: O
): TargetRef;
}
export const useD3: D3HookFunction = (d3Callback, data, options) => {
const ref = useRef(null) as TargetRef;
useLayoutEffect(() => {
d3Callback(ref, data, options);
return () => {
if (ref.current && ref.current.firstChild) {
ref.current.firstChild.remove();
}
}
}, [data, ref, options]);
return ref
}
// Target (root of DOM manipulations)
export interface D3TargetBaseProps {
id: string;
className?: string;
}
export interface D3TargetProps extends D3TargetBaseProps {
forwardRef: TargetRef;
}
export const D3Target = (props: D3TargetProps): JSX.Element => (
<div id={props.id} className={props.className} ref={props.forwardRef} ></div>
);
interface D3ContainerProps<D, O> extends D3TargetBaseProps {
d3Callback: D3CallbackSignature<D, O>;
data: D;
options?: O;
}
export const D3Container = <T, O, P extends D3ContainerProps<T, O>>(props: P): JSX.Element => {
const {
d3Callback,
data,
options
} = props;
const forwardRef = useD3(d3Callback, data, options);
return (
<D3Target {...{...props as P, forwardRef: forwardRef}} />
);
};
|
hypercodex/vizkite
|
src/__tests__/vizkite.spec.tsx
|
import * as React from 'react';
import { renderHook } from '@testing-library/react-hooks';
import { render } from '@testing-library/react';
import { mount } from 'enzyme';
import { useD3, D3Container, D3Target } from '../index';
describe('Test units of custom hook', () => {
// This rudimentary callback mutates the DOM
const d3Callback = (ref, data) => {
const xmlns = 'http://ww3.w3.org/2000/svg';
if (ref !== null) {
const childNode = document.createElementNS(xmlns, 'circle')
ref.current.appendChild(childNode);
}
};
it('returns a undefined current node when called', () => {
const { result } = renderHook(() => useD3(() => '', [])); // Call our hook.
expect(result.current.current).toBe(null);
});
it('calls the callback', () => {
const mockD3Callback = jest.fn((ref, data) => {return null;});
const { result } = renderHook(() => useD3(mockD3Callback, [])); // Call our hook.
const svg = mount(
<D3Target id='test' className='test' forwardRef={result.current[0]} />);
expect(svg.text()).toBe('')
expect(mockD3Callback).toBeCalled()
});
it('calls the effect cleanup', () => {
const TestComponent = () => {
const ref = useD3(d3Callback, []); // Call our hook.
return <D3Target id='test' className='test' forwardRef={ref} />;
}
const { container, unmount } = render(
<TestComponent />
);
expect(container.querySelector('div')).toBeInTheDocument();
expect(container.querySelectorAll('circle')).toHaveLength(1);
unmount();
expect(container.querySelectorAll('circle')).toHaveLength(0);
});
it('it renders a circle from fake callback', () => {
const svg = mount(
<D3Container
id='test'
className='test'
d3Callback={d3Callback}
data={[]}
/>
);
expect(svg.html()).toContain('circle')
});
});
|
hypercodex/vizkite
|
src/index.ts
|
export * from './vizkite'
|
yannzido/new
|
src/proxy-ui-api/frontend/src/store/modules/client.ts
|
<reponame>yannzido/new
import axios from 'axios';
import _ from 'lodash';
import { ActionTree, GetterTree, Module, MutationTree } from 'vuex';
import { RootState } from '../types';
export interface Client {
id: string;
name: string;
type?: string;
status?: string;
subsystem?: Client[];
connection_type?: string;
}
export interface ClientState {
client: Client | null;
signCertificates: any[];
loading: boolean;
connection_type: string | null;
tlsCertificates: any[];
ssCertificate: any;
}
export const clientState: ClientState = {
client: null,
loading: false,
signCertificates: [],
connection_type: null,
tlsCertificates: [],
ssCertificate: null,
};
export const getters: GetterTree<ClientState, RootState> = {
client(state): Client | null {
return state.client;
},
signCertificates(state): any[] {
return state.signCertificates;
},
connectionType(state): string | null | undefined {
if (state.client) {
return state.client.connection_type;
}
return null;
},
tlsCertificates(state): any[] {
return state.tlsCertificates;
},
ssCertificate(state): any {
return state.ssCertificate;
},
};
export const mutations: MutationTree<ClientState> = {
storeClient(state, client: Client | null) {
state.client = client;
},
storeSsCertificate(state, certificate: any) {
state.ssCertificate = certificate;
},
storeTlsCertificates(state, certificates: any[]) {
state.tlsCertificates = certificates;
},
storeSignCertificates(state, certificates: any[]) {
state.signCertificates = certificates;
},
setLoading(state, loading: boolean) {
state.loading = loading;
},
clearAll(state) {
state.client = null;
state.ssCertificate = null;
state.tlsCertificates = [];
state.signCertificates = [];
},
};
export const actions: ActionTree<ClientState, RootState> = {
fetchClient({ commit, rootGetters }, id: string) {
if (!id) {
throw new Error('Missing client id');
}
commit('setLoading', true);
return axios.get(`/clients/${id}`)
.then((res) => {
commit('storeClient', res.data);
})
.catch((error) => {
throw error;
})
.finally(() => {
commit('setLoading', false);
});
},
fetchSignCertificates({ commit, rootGetters }, id: string) {
commit('setLoading', true);
if (!id) {
throw new Error('Missing id');
}
return axios.get(`/clients/${id}/sign-certificates`)
.then((res) => {
commit('storeSignCertificates', res.data);
})
.catch((error) => {
throw error;
})
.finally(() => {
commit('setLoading', false);
});
},
fetchTlsCertificates({ commit, rootGetters }, id: string) {
commit('setLoading', true);
if (!id) {
throw new Error('Missing id');
}
return axios.get(`/clients/${id}/tls-certificates`)
.then((res) => {
commit('storeTlsCertificates', res.data);
})
.catch((error) => {
throw error;
})
.finally(() => {
commit('setLoading', false);
});
},
fetchSSCertificate({ commit, rootGetters }, id: string) {
if (!id) {
throw new Error('Missing id');
}
return axios.get(`/system/certificate`)
.then((res) => {
commit('storeSsCertificate', res.data);
})
.catch((error) => {
throw error;
})
.finally(() => {
commit('setLoading', false);
});
},
fetchTlsCertificate({ commit, rootGetters }, { clientId, hash }) {
if (!clientId) {
throw new Error('Missing id');
}
if (!hash) {
throw new Error('Missing certificate hash');
}
return axios.get(`/clients/${clientId}/tls-certificates/${hash}`);
},
deleteTlsCertificate({ commit, state }, { clientId, hash }) {
return axios.delete(`/clients/${clientId}/tls-certificates/${hash}`);
},
downloadSSCertificate({ commit, state }, { hash }) {
axios.get(`/system/certificate/export`, { responseType: 'arraybuffer' }).then((response) => {
let suggestedFileName;
const disposition = response.headers['content-disposition'];
if (disposition && disposition.indexOf('attachment') !== -1) {
const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
const matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) {
suggestedFileName = matches[1].replace(/['"]/g, '');
}
}
const effectiveFileName = (suggestedFileName === undefined ? 'certs.tar.gz' : suggestedFileName);
const blob = new Blob([response.data]);
// Create a link to DOM and click it. This will trigger the browser to start file download.
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.setAttribute('download', effectiveFileName);
document.body.appendChild(link);
link.click();
});
},
uploadTlsCertificate({ commit, state }, data) {
return axios.post(`/clients/${data.clientId}/tls-certificates/`, data.fileData, {
headers: {
'Content-Type': 'application/octet-stream',
},
});
},
saveConnectionType({ commit, state }, { clientId, connType }) {
return axios.patch(`/clients/${clientId}`, {
connection_type: connType,
})
.then((res) => {
if (res.data) {
commit('storeClient', res.data);
} else {
console.error('no data');
}
})
.catch((error) => {
console.error(error);
throw error;
})
.finally(() => {
commit('setLoading', false);
});
},
clearData({ commit, rootGetters }) {
commit('storeClient', null);
},
};
export const clientModule: Module<ClientState, RootState> = {
namespaced: false,
state: clientState,
getters,
actions,
mutations,
};
|
yannzido/new
|
src/proxy-ui-api/frontend/src/shims-vue-types.d.ts
|
<gh_stars>1-10
import Vue from 'vue';
declare module 'vue/types/vue' {
interface Vue {
$bus: Vue;
}
}
|
yannzido/new
|
src/proxy-ui-api/frontend/src/filters.ts
|
import Vue from 'vue';
import i18n from './i18n';
Vue.filter('capitalize', (value: string): string => {
if (!value) { return ''; }
value = value.toString();
return value.charAt(0).toUpperCase() + value.slice(1);
});
// Add colon for every two characters. xxxxxx -> xx:xx:xx
Vue.filter('colonize', (value: string): string => {
if (!value) { return ''; }
const colonized = value.replace(/(.{2})/g, '$1:');
if (colonized[colonized.length - 1] === ':') {
return colonized.slice(0, -1);
}
return colonized;
});
// Upper case every word
Vue.filter('upperCaseWords', (value: string): string => {
if (!value) { return ''; }
return value
.toLowerCase()
.split(' ')
.map((s) => s.charAt(0).toUpperCase() + s.substring(1))
.join(' ');
});
// Format date string. Result YYYY-MM-DD.
Vue.filter('formatDate', (value: string): string => {
const timestamp = Date.parse(value);
if (isNaN(timestamp)) {
return '-';
}
const date = new Date(value);
return date.toISOString().substring(0, 10);
});
// Format date string. Result YYYY-MM-DD HH:MM.
Vue.filter('formatDateTime', (value: string): string => {
const timestamp = Date.parse(value);
if (isNaN(timestamp)) {
return '-';
}
const date = new Date(value);
return date.toISOString().substring(0, 10) + ' ' + date.toISOString().substring(11, 16);
});
// Return readable string from OCSP status code
Vue.filter('ocspStatus', (value: string): string => {
if (!value) {
return '-';
}
switch (value) {
case 'DISABLED':
return i18n.t('keys.ocspStatus.disabled') as string;
break;
case 'EXPIRED':
return i18n.t('keys.ocspStatus.expired') as string;
break;
case 'OCSP_RESPONSE_UNKNOWN':
return i18n.t('keys.ocspStatus.unknown') as string;
break;
case 'OCSP_RESPONSE_GOOD':
return i18n.t('keys.ocspStatus.good') as string;
break;
case 'OCSP_RESPONSE_SUSPENDED':
return i18n.t('keys.ocspStatus.suspended') as string;
break;
case 'OCSP_RESPONSE_REVOKED':
return i18n.t('keys.ocspStatus.revoked') as string;
break;
default:
return '-';
break;
}
});
|
yannzido/new
|
src/proxy-ui-api/frontend/src/store/modules/mockData.ts
|
<gh_stars>1-10
import axios from 'axios';
import _ from 'lodash';
import { ActionTree, GetterTree, Module, MutationTree } from 'vuex';
import { RootState } from '../types';
// import mockJson from './mock';
// import mockJson from './fi-all';
// import mockJson from './ee-all';
export interface Client {
id: string;
name?: string | null;
sortName?: string | null;
descName?: string | null;
member_name: string | null;
member_class: string;
member_code: string;
subsystem_code: string | null;
created?: string | null;
type?: string;
status?: string;
subsystems?: Client[];
}
export interface ClientsArray extends Array<Client> { }
export interface DataState {
clients: ClientsArray;
loading: boolean;
}
export const dataState: DataState = {
// clients: mockJson,
clients: [],
loading: false,
};
export const getters: GetterTree<DataState, RootState> = {
mockClients(state): ClientsArray {
return state.clients;
},
mockClientsFlat(state): object[] {
// New arrays to separate members and subsystems
const members: object[] = [];
const subsystems: object[] = [];
const UNKNOWN_NAME: string = 'unknown member';
// Find the owner member (there is only one) it has member_name, but no subsystem_code
state.clients.forEach((element, index) => {
if (!element.subsystem_code) {
const clone = _.cloneDeep(element);
clone.type = 'owner';
clone.subsystem_code = null;
clone.name = clone.member_name;
clone.sortName = createMemberAscSortId(clone, clone.member_name); // clone.member_name + clone.member_class + clone.member_code;
clone.descName = createMemberDescSortId(clone, clone.member_name); // clone.member_name + clone.member_class + clone.member_code + '!';
members.push(clone);
return;
}
});
// Pick out the members
state.clients.forEach((element) => {
// Check if the member is already in the members array
const memberAlreadyExists = members.find((value, index) => {
const cli = value as Client;
// TODO: check the full id ?
if (cli.member_class === element.member_class && cli.member_code === element.member_code) {
return true;
}
return false;
});
if (!memberAlreadyExists) {
// If member is not in members array, create and add it
const clone = _.cloneDeep(element);
clone.type = 'client';
// Create member id
const idArray = clone.id.split(':');
idArray.pop();
clone.id = idArray.join(':');
clone.subsystem_code = null;
// Create a name from member_name
if (clone.member_name) {
clone.name = clone.member_name;
clone.sortName = createMemberAscSortId(clone, clone.member_name);
clone.descName = createMemberDescSortId(clone, clone.member_name);
} else {
clone.name = UNKNOWN_NAME;
clone.sortName = createMemberAscSortId(clone, UNKNOWN_NAME);
clone.descName = createMemberDescSortId(clone, UNKNOWN_NAME);
}
clone.status = undefined;
members.push(clone);
}
// Push subsystems to an array
if (element.subsystem_code) {
const clone = _.cloneDeep(element);
clone.name = clone.subsystem_code;
if (element.member_name) {
clone.sortName = createSortId(clone, element.member_name);
clone.descName = createSortId(clone, element.member_name);
} else {
clone.sortName = createSortId(clone, UNKNOWN_NAME);
clone.descName = createSortId(clone, UNKNOWN_NAME);
}
subsystems.push(clone);
}
});
// Combine the arrays
return [...new Set([...subsystems, ...members])];
},
loadings(state): boolean {
return state.loading;
},
};
function createSortId(client: Client, sortName: string): any {
// Create a sort id for client in form "ACMEGOV:1234 MANAGEMENT"
return sortName + client.member_class + client.member_code + ' ' + client.subsystem_code;
}
function createMemberAscSortId(client: Client, sortName: string | null): any {
// Create a sort id for member in form "ACMEGOV:1234"
return sortName + client.member_class + client.member_code;
}
function createMemberDescSortId(client: Client, sortName: any): any {
// Create a sort id for member in form "ACMEGOV:1234!"
return sortName + client.member_class + client.member_code + '!';
}
export const mutations: MutationTree<DataState> = {
setLoading(state, loading: boolean) {
state.loading = loading;
},
};
export const actions: ActionTree<DataState, RootState> = {
fetchData({ commit, rootGetters }) {
commit('setLoading', true);
return axios.get('/clients')
.then((res) => {
console.log(res);
})
.catch((error) => {
throw error;
})
.finally(() => {
commit('setLoading', false);
});
},
};
export const mockDataModule: Module<DataState, RootState> = {
namespaced: false,
state: dataState,
getters,
actions,
mutations,
};
|
yannzido/new
|
src/proxy-ui-api/frontend/src/store/index.ts
|
import Vue from 'vue';
import Vuex, { StoreOptions } from 'vuex';
import VuexPersistence from 'vuex-persist';
import { RootState } from './types';
import { generalModule } from './modules/general';
import { mockDataModule } from './modules/mockData';
import { clientsModule } from './modules/clients';
import { clientModule } from './modules/client';
import { keysModule } from './modules/keys';
import { servicesModule } from './modules/services';
import { user } from './modules/user';
Vue.use(Vuex);
const vuexLocal = new VuexPersistence({
storage: window.localStorage,
modules: ['user'],
});
const store: StoreOptions<RootState> = {
state: {
version: '1.0.0', // a simple property
},
modules: {
user,
generalModule,
mockDataModule,
clientsModule,
clientModule,
keysModule,
servicesModule,
},
// @ts-ignore
plugins: [vuexLocal.plugin],
};
export default new Vuex.Store<RootState>(store);
|
yannzido/new
|
src/proxy-ui-api/frontend/src/store/modules/services.ts
|
<reponame>yannzido/new<gh_stars>1-10
import { ActionTree, GetterTree, Module, MutationTree } from 'vuex';
import { RootState } from '../types';
export interface ServicesState {
expandedServiceDescriptions: string[];
}
export const servicesState: ServicesState = {
expandedServiceDescriptions: [],
};
export const getters: GetterTree<ServicesState, RootState> = {
descExpanded: (state) => (id: string) => {
return state.expandedServiceDescriptions.includes(id);
},
};
export const mutations: MutationTree<ServicesState> = {
setHidden(state, id: string) {
const index = state.expandedServiceDescriptions.findIndex((element: any) => {
return element === id;
});
if (index >= 0) {
state.expandedServiceDescriptions.splice(index, 1);
}
},
setExpanded(state, id: string) {
const index = state.expandedServiceDescriptions.findIndex((element: any) => {
return element === id;
});
if (index === -1) {
state.expandedServiceDescriptions.push(id);
}
},
};
export const actions: ActionTree<ServicesState, RootState> = {
expandDesc({ commit, rootGetters }, id: string) {
commit('setExpanded', id);
},
hideDesc({ commit, rootGetters }, id: string) {
commit('setHidden', id);
},
};
export const servicesModule: Module<ServicesState, RootState> = {
namespaced: false,
state: servicesState,
getters,
actions,
mutations,
};
|
yannzido/new
|
src/proxy-ui-api/frontend/src/util/api.ts
|
<filename>src/proxy-ui-api/frontend/src/util/api.ts
import axios from 'axios';
/*
* Wraps axios and post method calls with data
*/
export function post(uri: string, data: any) {
return axios.post(uri, data);
}
/*
* Wraps axios patch method calls with data
*/
export function patch(uri: string, data: any) {
return axios.patch(uri, data);
}
/*
* Wraps axios put method calls with data
*/
export function put(uri: string, data: any) {
return axios.put(uri, data);
}
/*
* Wraps axios delete method
*/
export function remove(uri: string) {
return axios.delete(uri);
}
/*
* Wraps axios get method calls
*/
export function get(uri: string) {
return axios.get(uri);
}
|
yannzido/new
|
src/proxy-ui-api/frontend/tests/unit/helpers.spec.ts
|
import * as Helpers from '@/util/helpers';
describe('helper functions', () => {
// REST URL can be http or https
it('REST URL validation', () => {
expect(Helpers.isValidRestURL('')).toEqual(false);
expect(Helpers.isValidRestURL('xx://foo.bar')).toEqual(false);
expect(Helpers.isValidWsdlURL('https://localhost:0009')).toEqual(true);
expect(Helpers.isValidRestURL('https://foo.bar')).toEqual(true);
expect(Helpers.isValidRestURL('http://foo.bar')).toEqual(true);
expect(Helpers.isValidRestURL('ftp://foo.bar')).toEqual(false);
expect(Helpers.isValidRestURL('file:///foo.bar')).toEqual(false);
});
// WSDL URL can be http or https
it('WSDL URL validation', () => {
expect(Helpers.isValidWsdlURL('')).toEqual(false);
expect(Helpers.isValidWsdlURL('xx://foo.bar')).toEqual(false);
expect(Helpers.isValidWsdlURL('https://localhost:0009')).toEqual(true);
expect(Helpers.isValidWsdlURL('https://foo.bar')).toEqual(true);
expect(Helpers.isValidWsdlURL('http://foo.bar')).toEqual(true);
expect(Helpers.isValidWsdlURL('ftp://foo.bar')).toEqual(false);
expect(Helpers.isValidWsdlURL('file:///foo.bar')).toEqual(false);
});
});
|
yannzido/new
|
src/proxy-ui-api/frontend/src/store/modules/keys.ts
|
<reponame>yannzido/new
import { ActionTree, GetterTree, Module, MutationTree } from 'vuex';
import { RootState } from '../types';
export interface KeysState {
expandedTokens: string[];
}
export const tokensState: KeysState = {
expandedTokens: [],
};
export const getters: GetterTree<KeysState, RootState> = {
tokenExpanded: (state) => (id: string) => {
return state.expandedTokens.includes(id);
},
};
export const mutations: MutationTree<KeysState> = {
setTokenHidden(state, id: string) {
const index = state.expandedTokens.findIndex((element: any) => {
return element === id;
});
if (index >= 0) {
state.expandedTokens.splice(index, 1);
}
},
setTokenExpanded(state, id: string) {
const index = state.expandedTokens.findIndex((element: any) => {
return element === id;
});
if (index === -1) {
state.expandedTokens.push(id);
}
},
};
export const actions: ActionTree<KeysState, RootState> = {
expandToken({ commit, rootGetters }, id: string) {
commit('setTokenExpanded', id);
},
hideToken({ commit, rootGetters }, id: string) {
commit('setTokenHidden', id);
},
};
export const keysModule: Module<KeysState, RootState> = {
namespaced: false,
state: tokensState,
getters,
actions,
mutations,
};
|
yannzido/new
|
src/proxy-ui-api/frontend/src/types.ts
|
<reponame>yannzido/new<gh_stars>0
export interface Service {
id: string;
service_code: string;
code: string;
timeout: number;
ssl_auth: boolean;
security_category: string;
url: string;
}
export interface ServiceDescription {
id: number;
url: string;
type: string;
disabled: boolean;
disabled_notice: string;
refreshed_date: string;
services: Service[];
client_id: string;
}
export interface AccessRightSubject {
rights_given_at: string;
subject: {
id: string;
member_name_group_description: string;
subject_type: string;
};
}
export interface Token {
id: string;
name: string;
type: string;
keys: Key[];
status: string;
logged_in: boolean;
available: boolean;
saved_to_configuration: boolean;
read_only: boolean;
token_infos: TokenInfo[];
}
export interface TokenInfo {
key: string;
value: string;
}
export interface Key {
id: string;
name: string;
label: string;
certificates: Certificate[];
certificate_signing_requests: TokenCertificateSigningRequest[];
usage: string;
available: boolean;
saved_to_configuration: boolean;
}
export interface TokenCertificateSigningRequest {
id: string;
owner_id: string;
}
export interface Certificate {
ocsp_status: string;
owner_id: string;
active: boolean;
saved_to_configuration: boolean;
certificate_details: CertificateDetails;
status: string;
}
export interface CertificateDetails {
issuer_distinguished_name: string;
issuer_common_name: string;
subject_distinguished_name: string;
subject_common_name: string;
not_before: string;
not_after: string;
serial: string;
version: number;
signature_algorithm: string;
signature: string;
public_key_algorithm: string;
rsa_public_key_modulus: string;
rsa_public_key_exponent: number;
hash: string;
key_usages: string[];
}
|
yannzido/new
|
src/proxy-ui-api/frontend/src/store/modules/general.ts
|
import { ActionTree, GetterTree, Module, MutationTree } from 'vuex';
import * as api from '@/util/api';
import { RootState } from '../types';
export interface State {
xroadInstances: string[];
memberClasses: string[];
}
export const generalState: State = {
xroadInstances: [],
memberClasses: [],
};
export const getters: GetterTree<State, RootState> = {
xroadInstances: (state) => {
return state.xroadInstances;
},
memberClasses: (state) => {
return state.memberClasses;
},
};
export const mutations: MutationTree<State> = {
storeInstances(state, instances: string[]) {
state.xroadInstances = instances;
},
storeMemberClasses(state, memberClasses: string[]) {
state.memberClasses = memberClasses;
},
};
export const actions: ActionTree<State, RootState> = {
fetchXroadInstances({ commit, rootGetters }) {
return api
.get(`/xroad-instances`)
.then((res) => {
commit('storeInstances', res.data);
})
.catch((error) => {
throw error;
});
},
fetchMemberClasses({ commit, rootGetters }) {
return api
.get(`/member-classes`)
.then((res) => {
commit('storeMemberClasses', res.data);
})
.catch((error) => {
throw error;
});
},
};
export const generalModule: Module<State, RootState> = {
namespaced: false,
state: generalState,
getters,
actions,
mutations,
};
|
yannzido/new
|
src/proxy-ui-api/frontend/src/util/helpers.ts
|
<reponame>yannzido/new
// Filters an array of objects excluding specified object key
export function selectedFilter(arr: any[], search: string, excluded?: string): any[] {
// Clean the search string
const mysearch = search.toString().toLowerCase();
if (mysearch.trim() === '') {
return arr;
}
const filtered = arr.filter((g: any) => {
let filteredKeys = Object.keys(g);
// If there is an excluded key remove it from the keys
if (excluded) {
filteredKeys = filteredKeys.filter((value) => {
return value !== 'id';
});
}
return filteredKeys.find((key: string) => {
return g[key]
.toString()
.toLowerCase()
.includes(mysearch);
});
});
return filtered;
}
// Checks if the given WSDL URL valid
export function isValidWsdlURL(str: string) {
const pattern = new RegExp('(^(https?):\/\/\/?)[-a-zA-Z0-9]');
return !!pattern.test(str);
}
// Checks if the given REST URL is valid
export function isValidRestURL(str: string) {
return isValidWsdlURL(str);
}
|
benaubin/blastoff-panel
|
index.ts
|
import logUpdate from "log-update";
export interface TaskStatus {
name: string;
status: "complete" | "starting" | "pending";
}
export interface StatusProps {
serviceName: string;
readyMessage?: string;
}
export interface StatusMessages {
withStatus<T>(name: string, f: (() => Promise<T>)): () => Promise<T>;
}
export default function statusMessages({serviceName, readyMessage}: StatusProps): StatusMessages {
let statuses: TaskStatus[] = [];
let statusUpdateInterval: NodeJS.Timeout | undefined;
function startStatusUpdates(): void {
if(statusUpdateInterval) return;
let frameN = 0;
const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
statusUpdateInterval = setInterval(() => {
const frame = frames[++frameN % frames.length];
let allComplete: boolean | null = null;
const statusLog = statuses.map((status) => {
switch (status.status) {
case "complete":
if(allComplete !== false) allComplete = true;
return ` ✅ ${status.name} ready!`;
case "starting":
allComplete = false;
return ` ${frame} ${status.name} starting...`;
case "pending":
allComplete = false;
return ` ◯ ${status.name}`;
}
}).join("\n");
if(allComplete) {
clearInterval(statusUpdateInterval!); //eslint-disable-line
statusUpdateInterval = undefined;
logUpdate(`🚀 ${serviceName} ${readyMessage}\n${statusLog}`);
logUpdate.done();
statuses = [];
} else {
logUpdate(`
${serviceName} starting up...
${statusLog}`);
}
}, 80);
}
function withStatus<T>(name: string, f: (() => Promise<T>)): () => Promise<T> {
let status: TaskStatus = {name, status: "pending"};
statuses.push(status);
startStatusUpdates();
return async () => {
if(statuses.indexOf(status) == -1) {
statuses.push(status);
startStatusUpdates();
}
status.status = "starting";
const result = await f();
status.status = "complete";
return result;
};
};
return {withStatus};
};
|
caikaijie/generator-ts-repo
|
generators/app/index.d.ts
|
<reponame>caikaijie/generator-ts-repo
import Generator, { Answers } from 'yeoman-generator';
export default class extends Generator {
answers: Answers;
constructor(args: string | string[], options: {});
prompting(): Promise<void>;
writing(): void;
install(): void;
}
|
caikaijie/generator-ts-repo
|
src/app/package.ts
|
import askName from 'inquirer-npm-name'
import { Answers } from 'yeoman-generator'
import path from 'path'
export function _getModuleNameParts(name: string): string {
if (name.startsWith('@')) {
const nameParts = name.slice(1).split('/')
return nameParts[1]
} else {
return name
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export async function askForPackageName(i: any): Promise<Answers> {
const anwsers = await askName(
{
name: 'repoName',
default: path.basename(process.cwd()),
},
i
)
anwsers.repoName = _getModuleNameParts(anwsers.repoName)
return anwsers
}
|
caikaijie/generator-ts-repo
|
generators/app/package.d.ts
|
<filename>generators/app/package.d.ts
import { Answers } from 'yeoman-generator';
export declare function _getModuleNameParts(name: string): string;
export declare function askForPackageName(i: any): Promise<Answers>;
|
caikaijie/generator-ts-repo
|
templates/src/example.spec.ts
|
<filename>templates/src/example.spec.ts
import { sum, slowHello } from './example'
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3)
})
test('another test case', async (): Promise<void> => {
try {
await slowHello('example')
} catch(e) {
expect(e).toMatchObject(new Error('slow error'))
}
})
|
caikaijie/generator-ts-repo
|
src/app/index.ts
|
<reponame>caikaijie/generator-ts-repo
import Generator, { Answers } from 'yeoman-generator'
import chalk from 'chalk'
import yosay from 'yosay'
import path from 'path'
import sortPackageJSON from 'sort-package-json'
import { askForPackageName } from './package'
import fse from 'fs-extra'
export default class extends Generator {
answers: Answers
constructor(args: string | string[], options: {}) {
// Calling the super constructor is important so our generator is correctly set up
super(args, options)
this.answers = {}
}
async prompting(): Promise<void> {
// Have Yeoman greet the user.
this.log(
yosay(`Welcome to the ${chalk.red('generator-ts-repo')} generator!`)
)
// const prompts = [
// {
// type: 'input',
// name: 'repoName',
// message: 'Repo name?',
// },
// ]
// this.answers = await this.prompt(prompts)
this.answers = await askForPackageName(this)
this.log(`I don't have more questions, thanks. Let's Go!\n`)
}
writing(): void {
// Relocate Root Dirs.
const sourceRoot = path.join(this.sourceRoot(), '../../../')
this.sourceRoot(sourceRoot)
const destinationRoot = path.join(
this.destinationRoot(),
this.answers.repoName
)
fse.ensureDirSync(destinationRoot)
this.destinationRoot(destinationRoot)
// Copy configs, dotfiles and LICENSE.
const files = [
'.editorconfig',
'.eslintignore',
'.eslintrc.js',
'.gitattributes',
'.gitignore',
'.prettierrc',
'.travis.yml',
'.vscode',
'commitlint.config.js',
'jest.config.js',
'LICENSE',
'tsconfig.json',
]
files.forEach(file => {
this.fs.copy(this.templatePath(file), this.destinationPath(file))
})
// Copy static files.
this.fs.copy(
this.templatePath('templates/src'),
this.destinationPath('./src')
)
// Render README.md.
this.fs.copyTpl(
this.templatePath('templates/README.md'),
this.destinationPath('README.md'),
{ repoName: this.answers.repoName }
)
// Render package.json
const pkg: { name: string } = this.fs.readJSON(
this.templatePath('templates/package.json')
)
pkg.name = this.answers.repoName
const json = JSON.stringify(sortPackageJSON(pkg), null, 2)
this.fs.write(this.destinationPath('package.json'), json)
}
install(): void {
// Try to init git repo.
const r = this.spawnCommandSync('git', ['init', '--quiet'], {
cwd: this.destinationPath(),
})
if (r.error != undefined) {
this.log(
`${chalk.red(chalk.bold('Tip: '))} "git" not found, skipped.\n`
)
}
const message = `Please install dependencies in your favorite way, thanks.`
const hints = `(running "yarn" or "npm install")`
this.log(
yosay(message + '\n' + hints, {
maxLength: message.length,
})
)
}
}
|
caikaijie/generator-ts-repo
|
templates/src/example.ts
|
<gh_stars>1-10
function sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms))
}
export function sum(a: number, b: number): number {
return a + b
}
export async function slowHello(message: string): Promise<void> {
await sleep(1000)
console.log(`hello, ${message}`)
throw new Error('slow error')
}
|
caikaijie/generator-ts-repo
|
__tests__/app.ts
|
<gh_stars>1-10
'use strict'
import path from 'path'
import helpers from 'yeoman-test'
import dirTree, { DirectoryTree } from 'directory-tree'
import treeify from 'treeify'
import fs from 'fs'
function treeify_(t: DirectoryTree): string {
const convert = (
p: treeify.TreeObject,
node: DirectoryTree
): treeify.TreeObject => {
if (node) {
let c: treeify.TreeObject = {}
if (node.children) {
node.children.forEach(v => {
c = convert(c, v)
})
}
p[node.name] = c
return p
}
return {}
}
const tj = convert({}, t)
return treeify.asTree(tj, true, false)
}
describe('generator-ts-repo:app', () => {
let tmpDir = ''
const repoName = 'e2e-test0000'
beforeAll(() => {
return helpers
.run(path.join(__dirname, '../generators/app'))
.withPrompts({ repoName })
.inTmpDir(dir => {
tmpDir = dir
})
})
it('creates structure', () => {
expect(
treeify_(
dirTree(path.join(tmpDir, repoName), {
normalizePath: true,
exclude: /.git\/.*/,
})
)
).toMatchSnapshot('directory structure')
})
it('creates packages.json', () => {
const content: string = fs
.readFileSync(path.join(tmpDir, repoName, 'package.json'))
.toString()
expect(content).toMatchSnapshot('package.json content')
})
})
|
kant/electron-wix-msi
|
__tests__/mocks/mock-fs.ts
|
import * as fs from 'fs-extra';
import * as path from 'path';
export const drive = process.platform === 'win32' ? 'C:' : '/';
export const root = path.join(drive, 'Users', 'tester', 'Code', 'app');
export const numberOfFiles = 15;
const staticDir = path.join(__dirname, '../../static');
const staticContent: Record<string, Record<string, any>> = {};
staticContent[staticDir] = {};
fs.readdirSync(staticDir)
.forEach((file) => {
staticContent[staticDir][file] = fs.readFileSync(path.join(staticDir, file), 'utf-8');
});
export function getMockFileSystem() {
const mockFiles = {
'locales': {
'am.pak': '',
'en-GB.pak': '',
'de.pak': ''
},
'resources': {
'app.asar.unpacked': {
node_modules: {
'@nodert-win10': {
'windows.foundation': {
build: {
Release: {
'binding.node': 'hi'
}
}
},
'windows.data.xml.dom': {
build: {
Release: {
'binding.node': 'hi'
}
}
}
}
},
src: {
static: {
'ssb-interop.js': 'hi'
}
}
},
'app.asar': 'hi',
'electron.asar': 'hi'
},
'api-ms-win-core-console-l1-1-0.dll': 'hi',
'ffmpeg.dll': 'hi',
'content_shell.pck': 'hi',
'slack.exe': 'hi',
'LICENSE': 'hi',
'node.dll': 'hi'
};
const system: Record<string, any> = {};
system[root] = mockFiles;
// Add files needed by this module:
return { ...system, ...staticContent };
}
|
kant/electron-wix-msi
|
__tests__/test-utils.ts
|
const oldPlatform = process.platform;
export function resetPlatform() {
overridePlatform(oldPlatform);
}
export function overridePlatform(platform: string) {
Object.defineProperty(process, 'platform', {
value: platform
});
}
|
kant/electron-wix-msi
|
__tests__/utils/separator-spec.ts
|
import { overridePlatform, resetPlatform } from '../test-utils';
afterEach(() => {
jest.resetModules();
});
afterAll(() => {
resetPlatform();
});
test('separator returns the correct separator for win32', () => {
let separator;
overridePlatform('win32');
separator = require('../../src/utils/separator').separator;
expect(separator).toBe('\\');
});
test('separator returns the correct separator for unix', () => {
let separator;
overridePlatform('linux');
separator = require('../../src/utils/separator').separator;
expect(separator).toBe('/');
});
|
kant/electron-wix-msi
|
__tests__/mocks/mock-spawn.ts
|
<filename>__tests__/mocks/mock-spawn.ts
import { EventEmitter } from 'events';
import * as path from 'path';
export class MockSpawn extends EventEmitter {
public stdout = new EventEmitter();
public stderr = new EventEmitter();
constructor(name: string, private readonly args: Array<string> = [], options: any = {}, public readonly fs: any) {
super();
if (name === 'candle.exe' && args && options && !this.contains('fail-candle')) {
this.beCandle();
}
if (name === 'light.exe' && args && options && !this.contains('fail-light')) {
this.beLight();
}
setImmediate(() => {
this.stderr.emit('data', 'A bit of error');
this.stdout.emit('data', 'A bit of data');
setImmediate(() => {
const code = this.contains(`fail-code-${path.basename(name, '.exe')}`) ? 1 : 0;
this.emit('close', code);
});
});
}
private beCandle() {
const filepath = this.args[this.args.length - 1];
const target = path.join(path.dirname(filepath), `${path.basename(filepath, '.wxs')}.wixobj`);
this.fs.writeFileSync(target, 'hi', 'utf-8');
}
private beLight() {
const filepath = this.args[this.args.length - 1];
const target = path.join(path.dirname(filepath), `${path.basename(filepath, '.wixobj')}.msi`);
this.fs.writeFileSync(target, 'hi', 'utf-8');
}
private contains(name: string): boolean {
return !!this.args.find((e) => e && e.includes && e.includes(name));
}
}
|
financialforcedev/orizuru-auth
|
src/index/client/oauth2.ts
|
/*
* Copyright (c) 2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @module client/oauth2
*/
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import formUrlencoded from 'form-urlencoded';
import { Environment } from './cache';
import { JwtGrantParams } from './oauth2Jwt';
import { UserInfoResponse } from './salesforce/identity';
/**
* The return formats when requesting a grant.
*/
export enum ResponseFormat {
JSON = 'application/json',
URL_ENCODED = 'application/x-www-form-urlencoded',
XML = 'application/xml'
}
/**
* The [Access Token Response](https://tools.ietf.org/html/rfc6749#section-5.1).
*
* @example
*
* ```json
*
* {
* "access_token":"<KEY>",
* "token_type":"example",
* "expires_in":3600,
* "refresh_token":"<PASSWORD>"
* }
*
* ```
*/
export interface AccessTokenResponse {
/**
* The access token issued by the authorization server.
*/
access_token: string;
/**
* The lifetime in seconds of the access token.
*/
expires_in?: number;
/**
* Token that can be used in the future to obtain new access tokens (sessions).
* This value is a secret. Treat it like the user’s password, and use appropriate measures to protect it.
*/
refresh_token?: string;
/**
* This parameter is returned if the scope parameter includes openid.
*/
scope?: string;
/**
* The [access token type](https://tools.ietf.org/html/rfc6749#section-7.1).
*/
token_type: string;
}
/**
* Parameters required for the auth grant type.
*/
export interface AuthCodeGrantParams extends TokenGrantorParams {
/**
* Authorization code that the consumer must use to obtain the access and refresh tokens.
*/
code: string;
/**
* Defines this grant type.
*/
grantType: 'authorization_code';
}
/**
* Optional parameters used when generating authorization URLs.
*/
export interface AuthOptions {
/**
* Changes the display type of the login and authorization pages.
*/
display?: 'page' | 'popup' | 'touch' | 'mobile';
/**
* If true and the user is logged in and has previously approved the clientId,
* Salesforce skips the approval step.
*
* If true and the user isn’t logged in or has not previously approved the client,
* Salesforce immediately terminates with the immediate_unsuccessful error code.
*/
immediate?: boolean;
/**
* Specifies how the authorization server prompts the user for reauthentication and
* reapproval.
*
* Defined in the [OpenID specification](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest).
*/
prompt?: 'none' | 'login' | 'consent' | 'select_account';
/**
* Opaque value used to maintain state between the request and the callback.
*/
state?: string;
}
/**
* The required parameters required for an [authorization request](https://tools.ietf.org/html/rfc6749#section-4.1.1).
*/
export interface AuthUrlParams extends HasClientId {
/**
* A space-delimited list of scopes that identify the resources that your application
* could access on the user's behalf.
*
* The scopes can be omitted in accordance with the [specification](https://tools.ietf.org/html/rfc6749#section-3.3).
*/
scope?: string;
/**
* Determines where the API server redirects the user after the user completes the
* authorization flow.
*/
redirectUri: string;
}
/**
* The [Error Response](https://tools.ietf.org/html/rfc6749#section-4.1.2.1) parameters.
*/
export interface ErrorResponse {
/**
* Returns the error code.
*/
error: string;
/**
* Returns the description of the error with additional information.
*/
error_description?: string;
}
/**
* Simple interface to include the client ID.
*/
export interface HasClientId {
/**
* The client ID for your application.
*/
clientId: string;
}
/**
* The base interface for all authentication clients.
*/
export interface AuthClient {
/**
* Creates the authorization URL.
*
* @param params The authentication URL parameters.
* @param [opts] The authentication options to be used when generating the URL.
* @returns The authorization URL.
*/
createAuthorizationUrl(params: AuthUrlParams, opts?: AuthOptions): string;
/**
* Returns the client type.
*/
getType(): string;
/**
* Obtain a grant with the specified parameters.
*
* This makes the [Access Token Request](https://tools.ietf.org/html/rfc6749#section-4.1.3) as per the OAuth 2.0 specification.
*
* @param params The grant parameters.
* @param [opts] The grant options to be used.
* @returns The [Access Token Response](https://tools.ietf.org/html/rfc6749#section-4.1.4).
*/
grant(params: GrantParams, opts?: OAuth2GrantOptions): Promise<AccessTokenResponse>;
/**
* Initalize the client by defining the endpoints.
*/
init(): Promise<void>;
/**
* Introspect a token.
*/
introspect(token: string, params: IntrospectionParams, opts?: IntrospectionOptions): Promise<IntrospectionResponse>;
/**
* Revoke a token.
*
* This makes a [Revocation Request](https://tools.ietf.org/html/rfc7009#section-2.1) as per the OAuth 2.0 specification.
*
* @param token The token to be revoked.
* @param [opts] The revocation options to be used.
* @returns If true the token has been revoked successfully.
*/
revoke(token: string, opts?: RevocationOptions): Promise<boolean>;
}
export interface AuthClientGrantParams {
/**
* The assertion for the JWT Bearer flow.
*/
assertion?: string;
/**
* The type of the client assertion.
*
* This is always *urn:ietf:params:oauth:client-assertion-type:jwt-bearer*.
*/
client_assertion_type?: string;
/**
* The client assertion.
*/
client_assertion?: string;
/**
* The client ID for your application.
*/
client_id?: string;
/**
* The client secret for your application.
*/
client_secret?: string;
/**
* Authorization code that the consumer must use to obtain the access and refresh tokens.
*/
code?: string;
/**
* The grant type.
*/
grant_type?: string;
/**
* Determines where the API server redirects the user after the user completes the
* authorization flow.
*/
redirect_uri?: string;
/**
* The refresh token.
*/
refresh_token?: string;
}
/**
* Optional parameters used when requesting grants.
*/
export interface OAuth2GrantOptions {
/**
* The client secret for your application.
*
* Either this value or the signingSecret should be set for the authorization code or refresh flows.
*/
clientSecret?: string;
/**
* Determines where the API server redirects the user after the user completes the
* authorization flow.
*
* It must be the same value sent by the initial redirect.
*/
redirectUri?: string;
/**
* Returns the response format, either JSON, XML or URL_ENCODED.
*/
responseFormat?: ResponseFormat;
}
/**
* Required parameters whrn introspecting tokens.
*/
export interface IntrospectionParams extends HasClientId {
/**
* The client secret for your application.
*/
clientSecret?: string;
}
/**
* Optional parameters used when introspecting tokens.
*/
export interface IntrospectionOptions {
/**
* Returns the response format, either JSON, XML or URL_ENCODED.
*/
responseFormat?: ResponseFormat;
}
/**
* [Introspection Response](https://tools.ietf.org/html/rfc7662#section-2.2)
*/
export interface IntrospectionResponse extends UserInfoResponse {
/**
* Boolean indicator of whether or not the presented token is currently active. The
* specifics of a token's "active" state will vary depending on the implementation of the
* authorization server and the information it keeps about its tokens, but a "true" value
* return for the "active" property will generally indicate that a given token has been
* issued by this authorization server, has not been revoked by the resource owner, and
* is within its given time window of validity (e.g., after its issuance time and before its
* expiration time).
*/
active: boolean;
/**
* Service-specific string identifier or list of string identifiers representing the intended
* audience for this token, as defined in JWT.
*/
aud?: string;
/**
* Client identifier for the OAuth 2.0 client that requested this token.
*/
client_id?: string;
/**
* Integer timestamp, measured in the number of seconds since January 1 1970 UTC,
* indicating when this token will expire, as defined in JWT.
*/
exp?: number;
/**
* Integer timestamp, measured in the number of seconds since January 1 1970 UTC,
* indicating when this token was originally issued, as defined in JWT.
*/
iat?: number;
/**
* String representing the issuer of this token, as defined in JWT.
*/
iss?: string;
/**
* String identifier for the token, as defined in JWT.
*/
jti?: string;
/**
* Integer timestamp, measured in the number of seconds since January 1 1970 UTC,
* indicating when this token is not to be used before, as defined in JWT.
*/
nbf?: number;
/**
* A JSON string containing a space-separated list of scopes associated with this token.
*/
scope?: string;
/**
* Subject of the token, as defined in JWT. Usually a machine-readable identifier of the
* resource owner who authorized this token.
*/
sub?: string;
/**
* Type of the token.
*/
token_type?: string;
/**
* Human-readable identifier for the resource owner who authorized this token.
*/
username?: string;
}
/**
* Parameters required for the [Refresh request](https://openid.net/specs/openid-connect-core-1_0.html#RefreshingAccessToken).
*/
export interface RefreshGrantParams extends RefreshTokenGrantorParams {
/**
* Defines this grant type.
*/
grantType: 'refresh_token';
}
export interface RefreshTokenGrantorParams extends TokenGrantorParams {
/**
* The refresh token.
*/
refreshToken: string;
}
export interface RevocationOptions {
/**
* If true, uses a GET rather than POST request to revoke an access token.
*/
useGet?: boolean;
}
export interface TokenGrantorParams extends HasClientId {
/**
* The client secret for your application.
*/
clientSecret?: string;
}
export type GrantParams = AuthCodeGrantParams | JwtGrantParams | RefreshGrantParams;
const DEFAULT_GRANT_OPTIONS = Object.freeze({
decodeIdToken: true,
parseUserInfo: true,
responseFormat: 'application/json',
verifyIdToken: true,
verifySignature: true
});
/**
* An OAuth 2.0 client that implements the [OAuth 2.0 Authorization Framework](https://tools.ietf.org/html/rfc6749) specification.
*/
export class OAuth2Client implements AuthClient {
/**
* The default configuration for an Axios request.
*/
public static readonly DEFAULT_REQUEST_CONFIG: AxiosRequestConfig = Object.freeze({
validateStatus: () => true
});
/**
* The client name.
*/
protected clientType: string;
/**
* [Authorization Endpoint](https://tools.ietf.org/html/rfc6749#section-3.1)
*/
protected authorizationEndpoint?: string;
/**
* [Introspection Endpoint](https://tools.ietf.org/html/rfc7662#section-2)
*/
protected introspectionEndpoint?: string | null;
/**
* [Revocation Endpoint](https://tools.ietf.org/html/rfc7009#section-2)
*/
protected tokenEndpoint?: string;
/**
* [Revocation Endpoint](https://tools.ietf.org/html/rfc7009#section-2)
*/
protected revocationEndpoint?: string;
/**
* The environment parameters used for this client.
*/
protected readonly env: Readonly<Environment>;
/**
* Creates a new OAuth2 client with the given environment.
*
* @param env The OAuth2 environment parameters.
*/
constructor(env: Environment) {
this.clientType = 'OAuth2';
this.env = Object.freeze(Object.assign({}, env));
}
/**
* @inheritdoc
*/
public async init() {
if (!this.env.authorizationEndpoint) {
throw new Error('Missing required string parameter: env[authorizationEndpoint]');
}
if (!this.env.revocationEndpoint) {
throw new Error('Missing required string parameter: env[revocationEndpoint]');
}
if (!this.env.tokenEndpoint) {
throw new Error('Missing required string parameter: env[tokenEndpoint]');
}
this.authorizationEndpoint = this.env.authorizationEndpoint;
this.introspectionEndpoint = this.env.introspectionEndpoint || null;
this.revocationEndpoint = this.env.revocationEndpoint;
this.tokenEndpoint = this.env.tokenEndpoint;
}
/**
* @inheritdoc
*/
public createAuthorizationUrl(params: AuthUrlParams, opts?: AuthOptions) {
if (!this.authorizationEndpoint) {
throw new Error(`${this.clientType} client has not been initialized`);
}
// To avoid any inadvertent parameter leaks, create a new object from which to generate the request.
const internalOpts: AuthOptions = {
display: opts && opts.display,
immediate: opts && opts.immediate,
prompt: opts && opts.prompt,
state: opts && opts.state
};
const internalParams = {
client_id: params.clientId,
redirect_uri: params.redirectUri,
response_type: 'code',
scope: params.scope
};
const data = Object.assign({}, internalParams, internalOpts);
if (!data.client_id) {
throw new Error('Missing required string parameter: clientId');
}
if (!data.redirect_uri) {
throw new Error('Missing required string parameter: redirectUri');
}
// Encode the parameters and then replace any encoded spaces (+)
// with the url version (%20)
const query = formUrlencoded(data, { sorted: true }).replace('+', '%20');
return `${this.authorizationEndpoint}?${query}`;
}
/**
* @inheritdoc
*/
public async grant(params: GrantParams, opts?: OAuth2GrantOptions): Promise<AccessTokenResponse> {
this.validateGrantParameters(params);
// To avoid any inadvertent parameter leaks, create a new object to generate the request from.
const internalOpts = Object.assign({}, DEFAULT_GRANT_OPTIONS, opts);
const internalParams = await this.createGrantInternalParameters(params, internalOpts);
const body = formUrlencoded(internalParams, { sorted: true });
const config = Object.assign({}, OAuth2Client.DEFAULT_REQUEST_CONFIG, {
headers: {
'Accept': internalOpts.responseFormat,
'Content-Type': 'application/x-www-form-urlencoded'
}
});
const response = await axios.post<AccessTokenResponse | ErrorResponse>(this.tokenEndpoint!, body, config);
if (response.status !== 200) {
const error = response.data as ErrorResponse;
throw new Error(`Failed to obtain grant: ${error.error} (${error.error_description}).`);
}
const accessTokenResponse = response.data as AccessTokenResponse;
return this.handleAccessTokenResponse(accessTokenResponse, internalOpts);
}
/**
* @inheritdoc
*/
public async introspect(token: string, params: IntrospectionParams, opts?: IntrospectionOptions) {
if (this.introspectionEndpoint === undefined) {
throw new Error(`${this.clientType} client has not been initialized`);
}
if (this.introspectionEndpoint === null) {
throw new Error(`${this.clientType} client does not support token introspection`);
}
if (!params.clientId) {
throw new Error('Missing required string parameter: clientId');
}
if (!params.clientSecret) {
throw new Error('Missing required string parameter: clientSecret');
}
const config = Object.assign({}, OAuth2Client.DEFAULT_REQUEST_CONFIG, {
headers: {
'Accept': (opts && opts.responseFormat) || ResponseFormat.JSON,
'Content-Type': 'application/x-www-form-urlencoded'
}
});
const internalOpts = Object.assign({}, {
parseUserInfo: true
}, opts);
const body = formUrlencoded({
client_id: params.clientId,
client_secret: params.clientSecret,
token
});
const response = await axios.post<IntrospectionResponse | ErrorResponse>(this.introspectionEndpoint, body, config);
if (response.status !== 200) {
const error = response.data as ErrorResponse;
throw new Error(`Failed to introspect token: ${error.error} (${error.error_description}).`);
}
const introspectionResponse = response.data as IntrospectionResponse;
return this.handleIntrospectionResponse(introspectionResponse, internalOpts);
}
/**
* @inheritdoc
*/
public async revoke(token: string, opts?: RevocationOptions) {
if (!this.revocationEndpoint) {
throw new Error(`${this.clientType} client has not been initialized`);
}
const internalOpts = Object.assign({
useGet: false
}, opts);
let response: AxiosResponse;
let revocationUri = this.revocationEndpoint;
if (internalOpts.useGet) {
revocationUri += `?token=${token}`;
response = await axios.get(revocationUri, OAuth2Client.DEFAULT_REQUEST_CONFIG);
} else {
const config = Object.assign({}, OAuth2Client.DEFAULT_REQUEST_CONFIG, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
const body = formUrlencoded({ token });
response = await axios.post(revocationUri, body, config);
}
return response.status === 200;
}
/**
* @inheritdoc
*/
public getType() {
return this.clientType;
}
/**
* Handle the access token response, performing validation and parsing as defined in the grant options.
*
* @param accessTokenResponse The access token response.
* @param internalOpts: The internal options.
*/
protected handleAccessTokenResponse(accessTokenResponse: AccessTokenResponse, internalOpts: OAuth2GrantOptions) {
return accessTokenResponse;
}
/**
* Handle the introspection response, performing validation and parsing as defined in the grant options.
*
* @param introspectionResponse The access token response.
* @param internalOpts: The internal options.
*/
protected handleIntrospectionResponse(introspectionResponse: IntrospectionResponse, internalOpts: IntrospectionOptions) {
return introspectionResponse;
}
/**
* Update the internal grant parameters is accordance with the selected [client authentication](https://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication)
* mechanism.
*
* @param params The grant parameters.
* @param internalParams The internal grant parameters.
* @param internalOpts: The internal options.
*/
protected async handleClientAuthentication(params: GrantParams, internalParams: AuthClientGrantParams, internalOpts: OAuth2GrantOptions) {
if (!params.clientId) {
throw new Error('Missing required string parameter: clientId');
}
if (!internalOpts.clientSecret) {
throw new Error('Missing required string parameter: clientSecret');
}
internalParams.client_id = params.clientId;
internalParams.client_secret = internalOpts.clientSecret;
}
/**
* Validate the grant parameters.
*
* @param params The grant parameters.
*/
protected validateGrantParameters(params: GrantParams) {
if (!this.tokenEndpoint) {
throw new Error(`${this.clientType} client has not been initialized`);
}
if (params.grantType === 'authorization_code') {
if (!params.code) {
throw new Error('Missing required string parameter: code');
}
} else if (params.grantType === 'refresh_token') {
if (!params.refreshToken) {
throw new Error('Missing required string parameter: refreshToken');
}
}
}
/**
* To avoid any inadvertent parameter leaks, create a new object from which to generate the grant request.
*
* @param params The grant parameters.
* @param internalOpts: The internal options.
* @returns The internal grant parameters.
*/
private async createGrantInternalParameters(params: GrantParams, internalOpts: OAuth2GrantOptions) {
const internalParams: AuthClientGrantParams = {};
if (params.grantType === 'authorization_code') {
internalParams.code = params.code;
internalParams.grant_type = 'authorization_code';
internalParams.redirect_uri = internalOpts.redirectUri;
}
if (params.grantType === 'refresh_token') {
internalParams.grant_type = 'refresh_token';
internalParams.refresh_token = params.refreshToken;
}
await this.handleClientAuthentication(params, internalParams, internalOpts);
return internalParams;
}
}
|
financialforcedev/orizuru-auth
|
src/index/client/openid/jwk.ts
|
/*
* Copyright (c) 2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @module client/openid/jwk
*/
import axios, { AxiosRequestConfig } from 'axios';
import { jsbn, pki, util } from 'node-forge';
/**
* [JSON Web Key (JWK)](https://tools.ietf.org/html/rfc7517)
*/
export interface JsonWebKey {
/**
* [Algorithm Parameter](https://tools.ietf.org/html/rfc7517#section-4.4)
*
* The algorithm parameter identifies the algorithm intended for use with the key.
*/
alg: string;
/**
* Base64 URL encoded string representing the public exponent of the RSA Key.
*/
e: string;
/**
* [Key ID Parameter](https://tools.ietf.org/html/rfc7517#section-4.5)
*
* The key ID parameter is used to match a specific key.
*/
kid: string;
/**
* [Key Type Parameter](https://tools.ietf.org/html/rfc7517#section-4.1)
*
* The key type parameter identifies the cryptographic algorithm family used with the
* key, such as "RSA" or "EC".
*/
kty: string;
/**
* Base64 URL encoded string representing the modulus of the RSA Key.
*/
n: string;
/**
* [Public Key Use Parameter](https://tools.ietf.org/html/rfc7517#section-4.2)
*/
use: string;
}
/**
* Map of JSON Web Keys, keyed by the Key ID Parameter.
*/
export interface JsonWebKeyMap {
[index: string]: JsonWebKey;
}
/**
* Map of JSON Web Keys, keyed by the Key ID Parameter, in PEM format.
*/
export interface JsonWebKeyPemFormatMap {
[index: string]: string;
}
/**
* Retrieves the JSON web keys and converts them to PEM format.
*/
export async function retrieveJsonWebKeysInPemFormat(jwksUri: string, config: AxiosRequestConfig) {
const keyMap = await retrieveJsonWebKeys(jwksUri, config);
return Object.entries(keyMap).reduce((result, [key, value]) => {
result[key] = convertJwkToPem(value);
return result;
}, {} as JsonWebKeyPemFormatMap);
}
/**
* Retrieves the JSON web keys.
*/
async function retrieveJsonWebKeys(jwksUri: string, config: AxiosRequestConfig) {
const response = await axios.get(jwksUri, config);
if (response.status !== 200) {
throw new Error('Failed to retrieve JWKs');
}
const keys: JsonWebKey[] = response.data.keys;
return keys.reduce((result, key) => {
result[key.kid] = key;
return result;
}, {} as JsonWebKeyMap);
}
/**
* Converts a JWK to PEM format.
*/
function convertJwkToPem(key: JsonWebKey) {
const publicKey = pki.rsa.setPublicKey(
base64urlToBigInteger(key.n),
base64urlToBigInteger(key.e)
);
return pki.publicKeyToPem(publicKey).replace(/\r\n/g, '\n');
}
/**
* Converts a base64 encoded string to a node forge big integer.
* @param encodedStr The string to convert.
*/
function base64urlToBigInteger(encodedStr: string) {
let decodeStr = encodedStr + '==='.slice((encodedStr.length + 3) % 4);
decodeStr = decodeStr.replace(/\-/g, '+').replace(/_/g, '/');
const bytes = util.decode64(decodeStr);
const hexData = util.binary.hex.encode(bytes);
// @ts-ignore-next-line
return new jsbn.BigInteger(hexData, 16);
}
|
financialforcedev/orizuru-auth
|
src/index/flow/webServer.ts
|
<gh_stars>1-10
/*
* Copyright (c) 2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @module flow/webServer
*/
import { AuthCodeAccessTokenGrantor, AuthCodeGrantParams, AuthOptions, AuthUrlGenerator, AuthUrlParams, Environment, GrantOptions, TokenGrantorParams } from '..';
import { findOrCreateClient } from '../client/cache';
import { validate } from '../client/validator/environment';
/**
* Creates the authorization endpoint to initialise the [OAuth 2.0 Web Server Authentication Flow](https://help.salesforce.com/articleView?id=remoteaccess_oauth_web_server_flow.htm).
*
* @param env The auth environment parameters.
* @returns A function that generates the authorization URL with the given state and options.
*/
export function authorizationUrlGenerator(env: Environment): AuthUrlGenerator {
const validatedEnvironment = validate(env);
return async function generateAuthorizationUrl(params: AuthUrlParams, opts?: AuthOptions) {
const openidClient = await findOrCreateClient(validatedEnvironment);
return openidClient.createAuthorizationUrl(params, opts);
};
}
/**
* [Exchanges a verification code for an access token](https://help.salesforce.com/articleView?id=remoteaccess_oauth_web_server_flow.htm#vc_for_at).
*
* Defaults to using a signed JWT bearer assertion to validate the user rather than the
* using the client secret. However, this is configurable via the GrantOptions.
*
* @param env The auth environment parameters.
* @returns A function that exchanges a verification code for an access token.
*/
export function createTokenGrantor(env: Environment): AuthCodeAccessTokenGrantor {
const validatedEnvironment = validate(env);
return async function requestAccessToken(params: TokenGrantorParams, opts?: GrantOptions) {
// The GrantCheckerMiddlewareParameters type excludes the grant_type
// so that it doesn't have to be set by the caller. Make sure it is set here.
const internalParams: Partial<AuthCodeGrantParams> = Object.assign({}, params);
internalParams.grantType = 'authorization_code';
const client = await findOrCreateClient(validatedEnvironment);
return client.grant(internalParams as AuthCodeGrantParams, opts);
};
}
|
financialforcedev/orizuru-auth
|
src/index/client/oauth2Jwt.ts
|
/*
* Copyright (c) 2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @module client/oauth2Jwt
*/
import { Secret } from 'jsonwebtoken';
import { Environment } from './cache';
import { AccessTokenResponse, AuthClientGrantParams, GrantParams, OAuth2Client, OAuth2GrantOptions, TokenGrantorParams } from './oauth2';
import { createJwtBearerClientAssertion, createJwtBearerGrantAssertion } from './oauth2Jwt/jwt';
/**
* A [JSON Web Token](https://tools.ietf.org/html/rfc7519) that fulfils the requirements of the
* [JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants](https://tools.ietf.org/html/rfc7523) specification.
*
* All fields are marked as optional/required according to the [JWT requirements](https://tools.ietf.org/html/rfc7523#section-3).
*/
export interface JWT {
/**
* The JWT may contain [other claims](https://tools.ietf.org/html/rfc7523#section-3).
*/
[index: string]: boolean | number | object | string | null | undefined;
/**
* [Audience Claim](https://tools.ietf.org/html/rfc7519#section-4.1.3)
*
* The audience claim identifies the recipients that the JWT is intended for.
*/
aud?: string;
/**
* [Expiration Time Claim](https://tools.ietf.org/html/rfc7519#section-4.1.4)
*
* The expiration time claim identifies the expiration time on or after which the JWT
* must not be accepted for processing.
*/
exp?: number;
/**
* [Issued At Claim](https://tools.ietf.org/html/rfc7519#section-4.1.6)
*
* The issued at claim identifies the time at which the JWT was issued.
*/
iat?: number;
/**
* [Issuer Claim](https://tools.ietf.org/html/rfc7519#section-4.1.1)
*
* The issuer claim identifies the principal that issued the JWT.
*/
iss: string;
/**
* [JWT ID Claim](https://tools.ietf.org/html/rfc7519#section-4.1.7)
*
* The JWT ID claim provides a unique identifier for the JWT.
*/
jti?: string;
/**
* [Not Before Claim](https://tools.ietf.org/html/rfc7519#section-4.1.5)
*
* The not before claim identifies the time before which the JWT must not be accepted
* for processing.
*/
nbf?: string;
/**
* [Subject Claim](https://tools.ietf.org/html/rfc7519#section-4.1.2)
*
* The subject claim identifies the principal that is the subject of the JWT.
*/
sub?: string;
}
/**
* Optional parameters used when requesting grants.
*/
export interface JwtGrantOptions extends OAuth2GrantOptions {
/**
* The private key used for signing grant assertions as part of the [OAuth 2.0 JWT Bearer Token Flow](https://help.salesforce.com/articleView?id=remoteaccess_oauth_jwt_flow.htm).
*
* Either this value or the signingSecret should be set for the authorization code or refresh flows.
*/
signingSecret?: Secret;
}
/**
* Parameters required for the JWT grant type.
*/
export interface JwtGrantParams extends UserTokenGrantorParams {
/**
* Defines this grant type.
*/
grantType: 'urn:ietf:params:oauth:grant-type:jwt-bearer';
}
export interface JwtTokenGrantorParams extends TokenGrantorParams {
/**
* The private key used for signing grant assertions as part of the [OAuth 2.0 JWT Bearer Token Flow](https://help.salesforce.com/articleView?id=remoteaccess_oauth_jwt_flow.htm).
*/
signingSecret: Secret;
}
/**
* The User credentials required to initialise the JWT flow.
*/
export interface User {
/**
* The user name.
*/
username: string;
}
export interface UserTokenGrantorParams extends JwtTokenGrantorParams {
/**
* The user that is requesting access.
*/
user: User;
}
/**
* An OAuth 2.0 client that implements the [JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants](https://tools.ietf.org/html/rfc7523)
* specification.
*/
export class OAuth2JWTClient extends OAuth2Client {
/**
* Creates a new OpenID client with the given environment.
*
* @param env The OAuth2 environment parameters.
*/
constructor(env: Environment) {
super(env);
this.clientType = 'OAuth2JWT';
}
/**
* @inheritdoc
*/
public async grant(params: GrantParams, opts?: JwtGrantOptions): Promise<AccessTokenResponse> {
return super.grant(params, opts);
}
/**
* @inheritdoc
*/
protected async handleClientAuthentication(params: GrantParams, internalParams: AuthClientGrantParams, internalOpts: JwtGrantOptions) {
if (params.grantType === 'urn:ietf:params:oauth:grant-type:jwt-bearer') {
const assertion = await createJwtBearerGrantAssertion(this.env, params);
internalParams.assertion = assertion;
internalParams.grant_type = 'urn:ietf:params:oauth:grant-type:jwt-bearer';
} else {
if (!params.clientId) {
throw new Error('Missing required string parameter: clientId');
}
internalParams.client_id = params.clientId;
if (internalOpts.signingSecret) {
internalParams.client_assertion_type = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer';
internalParams.client_assertion = await createJwtBearerClientAssertion(params, internalOpts.signingSecret, this.tokenEndpoint!);
} else {
if (!internalOpts.clientSecret) {
throw new Error('Missing required string parameter: clientSecret');
}
internalParams.client_secret = internalOpts.clientSecret;
}
}
}
/**
* @inheritdoc
*/
protected validateGrantParameters(params: GrantParams) {
super.validateGrantParameters(params);
if (params.grantType === 'urn:ietf:params:oauth:grant-type:jwt-bearer') {
if (!params.signingSecret) {
throw new Error('Missing required object parameter: signingSecret.');
}
if (!params.user) {
throw new Error('Missing required object parameter: user.');
}
}
}
}
|
financialforcedev/orizuru-auth
|
systemtests/server/salesforce.ts
|
<filename>systemtests/server/salesforce.ts
/*
* Copyright (c) 2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import { json, Request, Response, Server, urlencoded } from '@financialforcedev/orizuru';
import { flow, middleware, revocation } from '../../src';
import { TestServer } from './common';
export async function createServer() {
const server = new TestServer(['salesforceConnection', 'salesforceIdentity']);
addAuthRoute(server);
addAuthCallbackRoute(server);
addTokenIntrospectionRoute(server);
addTokenValidationRoute(server);
addGrantCheckRoute(server);
addRevokeTokenRoute(server);
return server;
}
function addAuthRoute(server: Server) {
const generateAuthorizationUrl = flow.webServer.authorizationUrlGenerator(server.options.authProvider.salesforceIdentity);
server.addRoute({
method: 'get',
middleware: [
json()
],
responseWriter: () => async (err, req, res) => {
const opts = Object.assign({}, server.options.openid.salesforceIdentity, { state: 'test' });
const url = await generateAuthorizationUrl(server.options.openid.salesforceIdentity, opts);
res.redirect(url);
},
schema: {
fields: [],
name: 'login',
namespace: 'api.auth.v1_0',
type: 'record'
},
synchronous: true
});
}
function addAuthCallbackRoute(server: Server) {
server.addRoute({
method: 'get',
middleware: [
urlencoded({
extended: true
}),
middleware.authCallback(server, 'salesforceIdentity', server.options.openid.salesforceIdentity, server.options.openid.salesforceIdentity),
(error, req, res, next) => {
if (error) {
res.sendStatus(401);
return;
}
}
],
responseWriter: (app) => async (error, req, res) => {
res.set('Content-Type', 'application/json');
res.send(req.headers);
},
schema: {
fields: [],
name: 'callback',
namespace: 'api.auth.v1_0',
type: 'record'
},
synchronous: true
});
}
function addTokenIntrospectionRoute(server: Server) {
server.addRoute({
method: 'get',
middleware: [
middleware.tokenIntrospection(server, 'salesforceIdentity', server.options.openid.salesforceIdentity)
],
responseWriter: (app) => async (error, req, res) => {
res.json(req.orizuru);
},
schema: {
fields: [],
name: 'introspectToken',
namespace: 'api.auth.v1_0',
type: 'record'
},
synchronous: true
});
}
function addTokenValidationRoute(server: Server) {
server.addRoute({
method: 'get',
middleware: [
middleware.tokenValidator(server, 'salesforceConnection')
],
responseWriter: (app) => async (error, req, res) => {
res.json(req.orizuru);
},
schema: {
fields: [],
name: 'validateToken',
namespace: 'api.auth.v1_0',
type: 'record'
},
synchronous: true
});
}
function addGrantCheckRoute(server: Server) {
server.addRoute({
method: 'get',
middleware: [
middleware.tokenValidator(server, 'salesforceConnection'),
middleware.grantChecker(server, 'salesforceConnection', server.options.openid.salesforceConnection, {
verifySignature: false
})
],
responseWriter: (app) => async (error, req, res) => {
res.json(req.orizuru);
},
schema: {
fields: [],
name: 'checkGrant',
namespace: 'api.auth.v1_0',
type: 'record'
},
synchronous: true
});
}
function addRevokeTokenRoute(server: Server) {
const tokenRevoker = revocation.createTokenRevoker(server.options.authProvider.salesforceConnection);
server.addRoute({
method: 'get',
responseWriter: (app) => async (error: Error | undefined, req: Request, res: Response) => {
let tokenRevoked = false;
if (req.headers.authorization) {
const accessToken = req.headers.authorization.replace('Bearer ', '');
tokenRevoked = await tokenRevoker(accessToken);
}
res.json({ tokenRevoked });
},
schema: {
fields: [],
name: 'revokeToken',
namespace: 'api.auth.v1_0',
type: 'record'
},
synchronous: true
});
}
|
financialforcedev/orizuru-auth
|
src/index/client/salesforce/identity.ts
|
/*
* Copyright (c) 2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @module client/salesforce/identity
*/
import crypto from 'crypto';
import { AccessTokenResponse, IntrospectionResponse } from '../oauth2';
import { OpenIDAccessTokenResponse } from '../openid';
import { SalesforceAccessTokenResponse, SalesforceIntrospectionResponse } from '../salesforce';
/**
* The Salesforce User Identity Information.
*
* This information is found in the [Identity URL](https://help.salesforce.com/articleView?id=remoteaccess_using_openid.htm#response) response.
*/
export interface SalesforceIdentity {
/**
* Returns true if the user is active.
*/
active: boolean;
/**
* Returns the city specified in the address of the user’s settings.
*/
addr_city: string | null;
/**
* Returns the country specified in the address of the user’s settings.
*/
addr_country: string;
/**
* Returns the state specified in the address of the user’s setting.
*/
addr_state: string | null;
/**
* Returns the street specified in the address of the user’s settings.
*/
addr_street: string | null;
/**
* Returns the zip or postal code specified in the address of the user’s settings.
*/
addr_zip: string | null;
/**
* Returns true if the specified access token was issued for this identity.
*/
asserted_user: boolean;
/**
* Returns the display name (full name) of the queried user.
*/
display_name: string;
/**
* Returns the user's preferred e-mail address.
*/
email: string;
/**
* Returns true if the End-User's e-mail address has been verified; otherwise false.
*/
email_verified: boolean;
/**
* Return the user's first name.
*/
first_name: string;
/**
* Returns the Identity URL (the same URL that was queried).
*/
id: string;
/**
* Returns true if the user is a lightning login user;
*/
is_lightning_login_user?: boolean;
/**
* Returns the user's language.
*/
language: string;
/**
* Returns the last modification of the user record.
*/
last_modified_date: string;
/**
* Returns the user's last name.
*/
last_name: string;
/**
* Returns the mobile phone number specified in the user’s settings.
*/
mobile_phone: string | null;
/**
* Returns true if the user has verified the mobile phone number.
*/
mobile_phone_verified: boolean;
/**
* Returns the user's Community nickname.
*/
nick_name: string;
/**
* Returns the user's organization ID.
*/
organization_id: string;
/**
* Returns the user's profile pictures.
*/
photos: {
[index: string]: string | null;
};
/**
* Returns the user’s current Chatter status.
*/
status: {
[index: string]: string | null;
};
/**
* Returns the time zone specified in the user’s settings.
*/
timezone: string;
/**
* Map containing various API endpoints that can be used with the specified user.
*/
urls: {
[index: string]: string | null;
};
/**
* Returns the user's id.
*/
user_id: string;
/**
* Returns the user's user type.
*/
user_type: string;
/**
* Returns the Salesforce user name.
*/
username: string;
/**
* Returns the offset from UTC of the time zone for the user, in milliseconds.
*/
utcOffset: number;
}
/**
* The user information generated when parsing the [Identity URL](https://help.salesforce.com/articleView?id=remoteaccess_using_openid.htm).
*/
export interface UserInfo {
/**
* Returns the user ID.
*/
id?: string;
/**
* Returns the organization ID.
*/
organizationId?: string;
/**
* Returns the full Identity URL.
*/
url: string;
/**
* If true, the Identity URL has been validated and is valid.
*/
validated: boolean;
}
export interface UserInfoResponse {
/**
* Identity URL that can be used to both identify the user and query for more information about the user.
*/
id?: string;
/**
* Subject that can be used to both identify the user and query for more information about the user.
*/
sub?: string;
/**
* The user information generated when parsing the [Identity URL](https://help.salesforce.com/articleView?id=remoteaccess_using_openid.htm).
*/
userInfo?: UserInfo;
}
/**
* Parse the user information from the `id` property of an access token response.
*
* It is assumed that the `id` conforms to the Salesforce [Identity URL](https://help.salesforce.com/articleView?id=remoteaccess_using_openid.htm) format.
*
* @param response The Salesforce user info response.
*/
export function parseUserInfo(response: UserInfoResponse) {
let identityUrl: string;
let validated: boolean;
if (response.id) {
identityUrl = response.id;
validated = false;
} else if (response.sub) {
identityUrl = response.sub;
// This response is obtained when the token has been introspected.
// Set validated to true as the token is valid.
validated = true;
} else {
throw new Error('Missing required string parameter: identityUrl');
}
const idUrls = identityUrl.split('/');
const id = idUrls.pop();
const organizationId = idUrls.pop();
if (!id || (id.length !== 15 && id.length !== 18)) {
throw new Error('Missing required string parameter: id');
}
if (!organizationId || (organizationId.length !== 15 && organizationId.length !== 18)) {
throw new Error('Missing required string parameter: organizationId');
}
response.userInfo = Object.assign({
id,
organizationId,
url: identityUrl,
validated
}, response.userInfo);
}
/**
* [Verifies the signature](https://help.salesforce.com/articleView?id=remoteaccess_oauth_web_server_flow.htm#grant_access_token) of the access token response.
*
* Used to verify that the identity URL hasn’t changed since the server sent it.
*
* @param clientSecret The client secret for your application.
* @param accessTokenResponse The Salesforce access token response.
*/
export function verifySignature(clientSecret: string, accessTokenResponse: SalesforceAccessTokenResponse) {
if (accessTokenResponse.signature) {
const hmac = crypto.createHmac('sha256', clientSecret);
hmac.update(`${accessTokenResponse.id}${accessTokenResponse.issued_at}`);
const expectedSignature = Buffer.from(hmac.digest('base64'));
const actualSignature = Buffer.from(accessTokenResponse.signature);
if (expectedSignature.length !== actualSignature.length) {
throw new Error('Invalid signature');
}
if (!crypto.timingSafeEqual(expectedSignature, actualSignature)) {
throw new Error('Invalid signature');
}
accessTokenResponse.userInfo = {
url: accessTokenResponse.id as string,
validated: true
};
} else {
throw new Error('No signature present');
}
}
/**
* Determines whether the response is a Salesforce access token response.
*
* @param token The access token response.
* @returns A boolean indicating if this token is a Salesforce access token response.
*/
export function isSalesforceAccessTokenResponse(token: AccessTokenResponse | OpenIDAccessTokenResponse | SalesforceAccessTokenResponse): token is SalesforceAccessTokenResponse {
return (token as SalesforceAccessTokenResponse).id !== undefined
|| (token as SalesforceAccessTokenResponse).instance_url !== undefined
|| (token as SalesforceAccessTokenResponse).issued_at !== undefined
|| (token as SalesforceAccessTokenResponse).signature !== undefined;
}
/**
* Determines whether the response is a Salesforce introspection response.
*
* @param token The introspection response.
* @returns A boolean indicating if this token is a Salesforce introspection response.
*/
export function isSalesforceIntrospectionResponse(token: IntrospectionResponse | SalesforceIntrospectionResponse): token is SalesforceIntrospectionResponse {
return (token as SalesforceIntrospectionResponse).userInfo !== undefined;
}
|
financialforcedev/orizuru-auth
|
src/index/middleware/grantChecker.ts
|
/*
* Copyright (c) 2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @module middleware/grantChecker
*/
import { NextFunction, Request, RequestHandler, Response } from '@financialforcedev/orizuru';
import { EVENT_GRANT_CHECKED, GrantOptions, JwtGrantParams, JwtTokenGrantorParams } from '../..';
import { AccessTokenResponse } from '../client/oauth2';
import { isSalesforceAccessTokenResponse } from '../client/salesforce/identity';
import { createTokenGrantor } from '../flow/jwtBearerToken';
import { DEFAULT_MIDDLEWARE_OPTIONS, MiddlewareOptions, setAccessTokenOnRequest } from './common/accessToken';
import { fail } from './common/fail';
/**
* Returns an express middleware that checks that an access token can be retrieved
* for the user specified on the request.
*
* Should be used in tandem with the tokenValidator middleware, and must be
* executed after that. This requires that a ConnectedApp is configured to pre-
* authorise users and the user is authorised.
*
* @fires EVENT_GRANT_CHECKED, EVENT_DENIED
* @param app The Orizuru server instance.
* @param [provider] The name of the auth provider. Defaults to 'salesforce'.
* @param [params] The grant checker middleware parameters.
* @param [opts] The optional parameters used when requesting grants.
* @returns A express middleware that checks an access token can be retrieved for
* the user on the request.
*/
export function createMiddleware(app: Orizuru.IServer, provider?: string, params?: JwtTokenGrantorParams, opts?: MiddlewareOptions & GrantOptions): RequestHandler {
const internalProvider = provider || 'salesforce';
const internalParams = params || app.options.openid[internalProvider];
const { setTokenOnContext, ...grantOptions } = opts || DEFAULT_MIDDLEWARE_OPTIONS;
const requestAccessToken = createTokenGrantor(app.options.authProvider[internalProvider]);
// The GrantCheckerMiddlewareParameters type excludes the grant_type
// so that it doesn't have to be set by the caller. Make sure it is set here.
const grantParams: Partial<JwtGrantParams> = Object.assign({}, internalParams);
grantParams.grantType = 'urn:ietf:params:oauth:grant-type:jwt-bearer';
return async function checkUserGrant(req: Request, res: Response, next: NextFunction) {
try {
const user = checkUserIsOnTheRequest(req);
const tokenResponse = await requestAccessToken(Object.assign({}, grantParams, { user }) as JwtGrantParams, grantOptions);
setGrant(app, req);
setAccessTokenOnRequest(req, tokenResponse.access_token, setTokenOnContext);
setInstanceUrlOnRequest(req, tokenResponse);
next();
} catch (error) {
fail(app, error, req, res, next);
}
};
}
/**
* Checks that the user is present on the request and is valid.
*
* @param req The HTTP request.
*/
function checkUserIsOnTheRequest(req: Request) {
if (!req.orizuru) {
throw new Error('Missing required object parameter: orizuru');
}
if (!req.orizuru.user) {
throw new Error('Missing required object parameter: orizuru[user]');
}
if (req.orizuru.user.username == null) {
throw new Error('Missing required string parameter: orizuru[user][username]');
}
if (!req.orizuru.user.username.length) {
throw new Error('Invalid parameter: orizuru[user][username] cannot be empty');
}
return req.orizuru.user;
}
/**
* Sets the grant checked boolean on the Orizuru context.
*
* @fires EVENT_GRANT_CHECKED
* @param app The Orizuru server instance.
* @param req The HTTP request.
*/
function setGrant(app: Orizuru.IServer, req: Request) {
const orizuru = req.orizuru!;
orizuru.grantChecked = true;
app.emit(EVENT_GRANT_CHECKED, `Grant checked for user (${orizuru.user!.username}) [${req.ip}].`);
}
/**
* Sets the instance URL on the Orizuru context.
*
* @param req The HTTP request.
* @param accessTokenResponse The access token response
*/
export function setInstanceUrlOnRequest(req: Request, accessTokenResponse: AccessTokenResponse) {
if (!isSalesforceAccessTokenResponse(accessTokenResponse)) {
return;
}
const orizuru = req.orizuru!;
orizuru.salesforce = orizuru.salesforce || {};
orizuru.salesforce.instanceUrl = accessTokenResponse.instance_url;
}
|
financialforcedev/orizuru-auth
|
src/index.ts
|
/*
* Copyright (c) 2017-2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Orizuru Auth module
* @module @financialforcedev/orizuru-auth
*/
import { clear, Environment } from './index/client/cache';
import { AccessTokenResponse, AuthOptions, AuthUrlParams, IntrospectionOptions, IntrospectionParams, IntrospectionResponse, OAuth2GrantOptions, RefreshTokenGrantorParams, TokenGrantorParams } from './index/client/oauth2';
import { JwtGrantOptions, JwtTokenGrantorParams, UserTokenGrantorParams } from './index/client/oauth2Jwt';
import { OpenIdGrantOptions, OpenIDTokenWithStandardClaims, UserInfoOptions } from './index/client/openid';
import { SalesforceGrantOptions, SalesforceUser } from './index/client/salesforce';
import { SalesforceIdentity, UserInfo } from './index/client/salesforce/identity';
import { createTokenGrantor as createJwtBearerAccessTokenGrantor } from './index/flow/jwtBearerToken';
import { createTokenGrantor as createRefreshAccessTokenGrantor } from './index/flow/refreshToken';
import { authorizationUrlGenerator, createTokenGrantor as createWebServerTokenGrantor } from './index/flow/webServer';
import { getToken, Grant } from './index/grant/grant';
import { createTokenIntrospector } from './index/introspection/introspect';
import { createMiddleware as authCallback } from './index/middleware/authCallback';
import { createMiddleware as grantChecker } from './index/middleware/grantChecker';
import { createMiddleware as retrieveIdentityInformation } from './index/middleware/identity';
import { createMiddleware as tokenIntrospection } from './index/middleware/tokenIntrospection';
import { createMiddleware as tokenValidator } from './index/middleware/tokenValidator';
import { createTokenRevoker } from './index/revocation/revoke';
import { createUserInfoRequester } from './index/userInfo/userinfo';
declare global {
namespace Express {
interface Request {
/**
* The Orizuru context for this request.
*/
orizuru?: Orizuru.Context;
}
}
namespace Orizuru {
interface Context {
/**
* The access token.
*/
accessToken?: string;
/**
* If true, the grant check has been performed for this user; an access token can be
* retrieved for the user.
*/
grantChecked?: boolean;
/**
* Salesforce related context information
*/
salesforce?: {
/**
* The Salesforce Instance URL.
*/
instanceUrl?: string;
/**
* The Salesforce Identity as defined by the [Identity URL](https://help.salesforce.com/articleView?id=remoteaccess_using_openid.htm#response) response.
*/
identity?: SalesforceIdentity;
/**
* The Salesforce user information generated when parsing the [Identity URL](https://help.salesforce.com/articleView?id=remoteaccess_using_openid.htm).
*/
userInfo?: UserInfo;
};
/**
* The information retrieved when introspecting the token.
*/
tokenInformation?: IntrospectionResponse;
/**
* The User credentials required to initialise the JWT flow.
*/
user?: SalesforceUser;
}
interface IServer {
/**
* The Orizuru Server Options.
*/
options: Options.IServer;
}
namespace Options {
interface IServer {
/**
* Auth Providers registered with this server.
*
* A map of provider name to Environment.
*
* This is referenced by each of the middleware, allowing instances to be created for
* different OpenID providers.
*/
authProvider: {
[index: string]: Environment;
};
/**
* OpenID connected app information required for the authentication middleware.
*/
openid: {
[index: string]: OpenIdOptions;
};
}
}
}
}
// Export from internal modules
export { Environment } from './index/client/cache';
export {
AccessTokenResponse,
AuthClient,
AuthCodeGrantParams,
AuthOptions,
AuthUrlParams,
ErrorResponse,
GrantParams,
HasClientId,
IntrospectionOptions,
IntrospectionParams,
IntrospectionResponse,
OAuth2GrantOptions,
RefreshGrantParams,
RefreshTokenGrantorParams,
ResponseFormat,
RevocationOptions,
TokenGrantorParams
} from './index/client/oauth2';
export {
JWT,
JwtGrantOptions,
JwtGrantParams,
JwtTokenGrantorParams,
User,
UserTokenGrantorParams
} from './index/client/oauth2Jwt';
export {
OpenIDAccessTokenResponse,
OpenIdGrantOptions,
OpenIDToken,
OpenIDTokenWithStandardClaims,
OpenIdTokenAddress,
UserInfoOptions
} from './index/client/openid';
export {
SalesforceAccessTokenResponse,
SalesforceGrantOptions,
SalesforceUser
} from './index/client/salesforce';
export { SalesforceIdentity, UserInfo } from './index/client/salesforce/identity';
export { MiddlewareOptions } from './index/middleware/common/accessToken';
// Token Grantor types
export type AuthCodeAccessTokenGrantor = (params: TokenGrantorParams, opts?: GrantOptions) => Promise<AccessTokenResponse>;
export type JwtBearerAccessTokenGrantor = (params: UserTokenGrantorParams, opts?: GrantOptions) => Promise<AccessTokenResponse>;
export type UserTokenGrantor = (params: UserTokenGrantorParams, opts?: GrantOptions) => Promise<Grant>;
export type RefreshAccessTokenGrantor = (params: RefreshTokenGrantorParams, opts?: GrantOptions) => Promise<AccessTokenResponse>;
export type AuthUrlGenerator = (params: AuthUrlParams, opts?: AuthOptions) => Promise<string>;
export type TokenIntrospector = (token: string, params: IntrospectionParams, opts?: IntrospectionOptions) => Promise<IntrospectionResponse>;
export type TokenRevoker = (token: string) => Promise<boolean>;
export type UserInfoRequester = (accessToken: string, opts?: UserInfoOptions) => Promise<OpenIDTokenWithStandardClaims>;
export type Options = AuthOptions | GrantOptions | UserInfoOptions;
export type GrantorParams = RefreshTokenGrantorParams | TokenGrantorParams | UserTokenGrantorParams;
export type OpenIdOptions = AuthUrlParams & AuthOptions & GrantorParams & IntrospectionParams & JwtTokenGrantorParams & Options;
export type GrantOptions = OAuth2GrantOptions | JwtGrantOptions | OpenIdGrantOptions | SalesforceGrantOptions;
/**
* The event fired when the authorization header is set.
* @event
*/
export const EVENT_AUTHORIZATION_HEADER_SET = Symbol();
/**
* The event fired for an unauthorized request.
* @event
*/
export const EVENT_DENIED = Symbol();
/**
* The event fired when the grant has been checked.
* @event
*/
export const EVENT_GRANT_CHECKED = Symbol();
/**
* The event fired when the identity has been retrieved from Salesforce using the
* [Identity URL](https://help.salesforce.com/articleView?id=remoteaccess_using_openid.htm).
* @event
*/
export const EVENT_USER_IDENTITY_RETRIEVED = Symbol();
/**
* The event fired when an access token has been introspected.
* @event
*/
export const EVENT_TOKEN_INTROSPECTED = Symbol();
/**
* The event fired when an access token has been validated.
* @event
*/
export const EVENT_TOKEN_VALIDATED = Symbol();
const jwtBearerToken = {
/**
* Creates an access token grantor that exchanges a JWT for an access token.
*/
createTokenGrantor: createJwtBearerAccessTokenGrantor
};
const refreshToken = {
/**
* Creates an access token grantor that exchanges a refresh token for an access token.
*
* Rather than using the client secret of the Salesforce Connected Application, this
* function creates a signed JWT bearer assertion to validate the user.
*/
createTokenGrantor: createRefreshAccessTokenGrantor
};
const webServer = {
/**
* Generates URLs required to initialise the [OAuth 2.0 Web Server Authentication Flow](https://help.salesforce.com/articleView?id=remoteaccess_oauth_web_server_flow.htm).
*/
authorizationUrlGenerator,
/**
* Creates an access token grantor that [exchanges a verification code for an access token](https://help.salesforce.com/articleView?id=remoteaccess_oauth_web_server_flow.htm#vc_for_at).
*
* Rather than using the client secret of the Salesforce Connected Application, this
* function creates a signed JWT bearer assertion to validate the user.
*/
createTokenGrantor: createWebServerTokenGrantor
};
/**
* Returns the collection of OAuth 2.0 flow functions.
*/
export const flow = {
/**
* Returns functions to handle the [OAuth 2.0 JWT Bearer Token Flow](https://help.salesforce.com/articleView?id=remoteaccess_oauth_jwt_flow.htm).
*/
jwtBearerToken,
/**
* Returns functions to handle the [OAuth 2.0 Refresh Token Flow](https://help.salesforce.com/articleView?id=remoteaccess_oauth_refresh_token_flow.htm).
*/
refreshToken,
/**
* Returns functions to handle the [OAuth 2.0 Web Server Authentication Flow](https://help.salesforce.com/articleView?id=remoteaccess_oauth_web_server_flow.htm).
*/
webServer
};
/**
* Returns the collection of grant functions.
*/
export const grant = {
/**
* Returns a function that can obtain a token for the passed user.
*/
getToken
};
/**
* Returns the collection of introspection functions.
*/
export const introspection = {
/**
* Returns a function that introspects a token.
*/
createTokenIntrospector
};
/**
* Returns the collection of middleware functions.
*/
export const middleware = {
/**
* Returns an express middleware that [exchanges a verification code for an access token](https://help.salesforce.com/articleView?id=remoteaccess_oauth_web_server_flow.htm#vc_for_at).
*
* This can be used in tandem with the tokenValidator to set the user on the request.
*/
authCallback,
/**
* Returns an express middleware that checks that an access token
* can be retrieved for the user specified on the request.
* Should be used in tandem with the tokenValidator middleware,
* and must be executed after that. This requires that a ConnectedApp
* is configured to pre authorise users and the user is
* authorised.
*/
grantChecker,
/**
* Returns an express middleware that uses the [Identity URL](https://help.salesforce.com/articleView?id=remoteaccess_using_openid.htm) to retrieve information
* about the current Salesforce user.
*/
retrieveIdentityInformation,
/**
* Returns an express middleware that introspects the access token passed in an HTTP
* Authorization header and if successful updates the request object.
*/
tokenIntrospection,
/**
* Returns an express middleware that validates the OpenID Connect
* access token passed in an HTTP Authorization header and if successful
* sets the user object onto the request object.
*/
tokenValidator
};
/**
* Returns the collection of OpenID client functions.
*/
export const openIdClient = {
/**
* Clears the OpenID client cache.
*
* This will cause new OpenID clients to be created and the [OpenID provider configuration information](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig)
* to be queried again.
*/
clearCache: clear
};
/**
* Returns the collection of revocation functions.
*/
export const revocation = {
/**
* Returns a function that [revokes access tokens](https://help.salesforce.com/articleView?id=remoteaccess_revoke_token.htm).
*/
createTokenRevoker
};
/**
* Returns the collection of [user information](https://help.salesforce.com/articleView?id=remoteaccess_using_userinfo_endpoint.htm) functions.
*/
export const userInfo = {
/**
* Returns a function that requests the user information for a given access token.
*/
createUserInfoRequester
};
|
financialforcedev/orizuru-auth
|
test/index/middleware/grantChecker.test.ts
|
<filename>test/index/middleware/grantChecker.test.ts
/*
* Copyright (c) 2017-2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import chai from 'chai';
import sinon, { SinonStub } from 'sinon';
import sinonChai from 'sinon-chai';
import { Request, RequestHandler, Response } from '@financialforcedev/orizuru';
import { Environment, EVENT_GRANT_CHECKED, GrantOptions, OpenIdOptions, SalesforceAccessTokenResponse } from '../../../src';
import * as jwtBearerToken from '../../../src/index/flow/jwtBearerToken';
import { MiddlewareOptions } from '../../../src/index/middleware/common/accessToken';
import * as fail from '../../../src/index/middleware/common/fail';
import { createMiddleware } from '../../../src/index/middleware/grantChecker';
const expect = chai.expect;
const has = sinon.match.has;
chai.use(sinonChai);
describe('index/middleware/grantChecker', () => {
let app: Orizuru.IServer;
let env: Environment;
let requestAccessTokenStub: SinonStub;
beforeEach(() => {
env = {
httpTimeout: 4001,
issuerURI: 'https://login.salesforce.com/',
type: 'OpenID'
};
const openIdOptions: Partial<OpenIdOptions> = {
clientId: 'testClientId',
clientSecret: 'testClientSecret',
redirectUri: 'https://localhost:8080/api/auth/v1.0/callback',
signingSecret: 'testSigningSecret'
};
const partialApp: Partial<Orizuru.IServer> = {
emit: sinon.stub(),
options: {
authProvider: {
salesforce: env
},
openid: {
salesforce: openIdOptions as OpenIdOptions
}
}
};
app = partialApp as Orizuru.IServer;
requestAccessTokenStub = sinon.stub();
sinon.stub(jwtBearerToken, 'createTokenGrantor').returns(requestAccessTokenStub);
sinon.stub(fail, 'fail');
});
afterEach(() => {
// Then
expect(jwtBearerToken.createTokenGrantor).to.have.been.calledOnce;
expect(jwtBearerToken.createTokenGrantor).to.have.been.calledWithExactly(app.options.authProvider.salesforce);
sinon.restore();
});
it('should return a function when called with the app', () => {
// Given
// When
const middleware = createMiddleware(app);
// Then
expect(middleware).to.be.a('function');
});
describe('checkUserGrant', () => {
let middleware: RequestHandler;
let req: Request;
let res: Response;
let next: SinonStub;
let opts: MiddlewareOptions & GrantOptions;
beforeEach(() => {
const partialRequest: Partial<Request> = {
ip: '1.1.1.1',
orizuru: {
user: {
organizationId: 'testOrganizationId',
username: '<EMAIL>'
}
}
};
req = partialRequest as Request;
const partialResponse: Partial<Response> = {};
res = partialResponse as Response;
next = sinon.stub();
opts = {
verifySignature: false
};
middleware = createMiddleware(app, 'salesforce', app.options.openid.salesforce, opts);
});
describe('should fail the request', () => {
afterEach(() => {
// Then
expect(fail.fail).to.have.been.calledOnce;
expect(next).to.not.have.been.called;
});
it('if orizuru is not on the request', async () => {
// Given
delete req.orizuru;
// When
await middleware(req, res, next);
// Then
expect(fail.fail).to.have.been.calledWithExactly(app, has('message', 'Missing required object parameter: orizuru'), req, res, next);
});
it('if the user is not on the request', async () => {
// Given
delete req.orizuru!.user;
// When
await middleware(req, res, next);
// Then
expect(fail.fail).to.have.been.calledWithExactly(app, has('message', 'Missing required object parameter: orizuru[user]'), req, res, next);
});
it('if the username is not on the request', async () => {
// Given
delete req.orizuru!.user!.username;
// When
await middleware(req, res, next);
// Then
expect(fail.fail).to.have.been.calledWithExactly(app, has('message', 'Missing required string parameter: orizuru[user][username]'), req, res, next);
});
it('if the username is empty on the request', async () => {
// Given
req.orizuru!.user!.username = '';
// When
await middleware(req, res, next);
// Then
expect(fail.fail).to.have.been.calledWithExactly(app, has('message', 'Invalid parameter: orizuru[user][username] cannot be empty'), req, res, next);
});
it('if requestAccessToken rejects', async () => {
// Given
requestAccessTokenStub.rejects(new Error('Invalid grant for user (<EMAIL>). Caused by: something or other'));
// When
await middleware(req, res, next);
// Then
expect(fail.fail).to.have.been.calledWithExactly(app, has('message', 'Invalid grant for user (<EMAIL>). Caused by: something or other'), req, res, next);
});
});
describe('should call next if the grant is validated', () => {
beforeEach(() => {
requestAccessTokenStub.resolves({
access_token: 'testAccessToken'
});
});
it('and update orizuru on the request', async () => {
// Given
// When
await middleware(req, res, next);
// Then
expect(req.orizuru).to.have.property('user').that.eqls({
organizationId: 'testOrganizationId',
username: '<EMAIL>'
});
expect(requestAccessTokenStub).to.have.been.calledOnce;
expect(requestAccessTokenStub).to.have.been.calledWithExactly({
clientId: 'testClientId',
clientSecret: 'testClientSecret',
grantType: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
redirectUri: 'https://localhost:8080/api/auth/v1.0/callback',
signingSecret: 'testSigningSecret',
user: {
organizationId: 'testOrganizationId',
username: '<EMAIL>'
}
}, { verifySignature: false });
expect(app.emit).to.have.been.calledOnce;
expect(app.emit).to.have.been.calledWithExactly(EVENT_GRANT_CHECKED, 'Grant checked for user (<EMAIL>) [1.1.1.1].');
expect(next).to.have.been.calledOnce;
expect(next).to.have.been.calledWithExactly();
});
it('and set the access token on request if required', async () => {
// Given
sinon.resetHistory();
opts.setTokenOnContext = true;
middleware = createMiddleware(app, 'salesforce', app.options.openid.salesforce, opts);
// When
await middleware(req, res, next);
// Then
expect(req.orizuru).to.have.property('accessToken').that.eqls('testAccessToken');
expect(requestAccessTokenStub).to.have.been.calledOnce;
expect(requestAccessTokenStub).to.have.been.calledWithExactly(sinon.match.object, {
verifySignature: false
});
expect(next).to.have.been.calledOnce;
});
it('and set the instance URL on request if required', async () => {
// Given
const tokenResponse: Partial<SalesforceAccessTokenResponse> = {
access_token: 'testAccessToken',
instance_url: 'https://test.salesforce.com'
};
requestAccessTokenStub.resolves(tokenResponse);
// When
await middleware(req, res, next);
// Then
expect(req.orizuru).to.have.property('salesforce').that.has.property('instanceUrl', 'https://test.salesforce.com');
expect(requestAccessTokenStub).to.have.been.calledOnce;
expect(requestAccessTokenStub).to.have.been.calledWithExactly(sinon.match.object, {
verifySignature: false
});
expect(next).to.have.been.calledOnce;
});
});
});
});
|
financialforcedev/orizuru-auth
|
src/index/client/salesforce.ts
|
<reponame>financialforcedev/orizuru-auth
/*
* Copyright (c) 2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @module client/salesforce
*/
import { Environment } from './cache';
import { GrantParams, IntrospectionOptions, IntrospectionResponse } from './oauth2';
import { User } from './oauth2Jwt';
import { OpenIDAccessTokenResponse, OpenIdClient, OpenIdGrantOptions } from './openid';
import { parseUserInfo, UserInfoResponse, verifySignature } from './salesforce/identity';
/**
* The Salesforce Access Token Response.
*
* @example
* ```json
*
* {
* "id": "https://login.salesforce.com/id/00Dx0000000BV7z/005x00000012Q9P",
* "issued_at": "1278448101416",
* "refresh_token": "<KEY>
* "instance_url": "https://yourInstance.salesforce.com/",
* "signature": "CMJ4l+CCaPQiKjoOEwEig9H4wqhpuLSk4J2urAe+fVg=",
* "access_token": "<KEY>",
* "token_type": "Bearer",
* "scope": "id api refresh_token"
* }
*
* ```
*/
export interface SalesforceAccessTokenResponse extends OpenIDAccessTokenResponse, UserInfoResponse {
/**
* A URL indicating the instance of the user’s org. For example: https://yourInstance.salesforce.com/.
*/
instance_url?: string;
/**
* If the user is a member of a Salesforce community, the community URL is provided.
*/
sfdc_community_url?: string;
/**
* If the user is a member of a Salesforce community, the user’s community ID is provided.
*/
sfdc_community_id?: string;
/**
* Base64-encoded HMAC-SHA256 signature signed with the client secret (private key) containing the
* concatenated ID and issued_at. Used to verify that the identity URL hasn’t changed since the
* server sent it.
*/
signature: string;
/**
* When the signature was created.
*/
issued_at: string;
}
/**
* Optional parameters used when requesting grants.
*/
export interface SalesforceGrantOptions extends OpenIdGrantOptions {
/**
* If true, parses the user information from the id field in the access token response.
*
* This returns the user ID, organization ID and the ID url.
*/
parseUserInfo?: boolean;
/**
* If true, the signature on the access token response is verified.
*/
verifySignature?: boolean;
}
/**
* The Salesforce Introspection Options.
*/
export interface SalesforceIntrospectionOptions extends IntrospectionOptions {
/**
* If true, parses the user information from the id field in the access token response.
*
* This returns the user ID, organization ID and the ID url.
*/
parseUserInfo?: boolean;
}
/**
* The Salesforce Introspection Response.
*
* Adds the user info information to the standard introspection response.
*
* @example
* ```json
* {
* "active": true,
* "client_id": "OAuthSp",
* "exp": 1528502109,
* "iat": 1528494909,
* "nbf": 1528494909,
* "scope": "id api web full refresh_token openid",
* "sub": "https://login.salesforce.com/id/00Dxx0000001gEREAY/005xx000001Sv6AAAS",
* "token_type": "access_token",
* "username": "<EMAIL>"
* }
* ```
*/
export interface SalesforceIntrospectionResponse extends IntrospectionResponse, UserInfoResponse {
}
/**
* The User credentials required to initialise the JWT flow.
*/
export interface SalesforceUser extends User {
/**
* The organization ID.
*/
organizationId?: string;
}
/**
* A Salesforce Client that implements the [Salesforce OAuth 2.0](https://help.salesforce.com/articleView?id=remoteaccess_authenticate_overview.htm) specification.
*/
export class SalesforceClient extends OpenIdClient {
/**
* Creates a new OpenID client with the given environment.
*
* @param env The OAuth2 environment parameters.
*/
constructor(env: Environment) {
super(env);
this.clientType = 'Salesforce';
}
/**
* @inheritdoc
* @returns The Salesforce Access Token Response.
*/
public async grant(params: GrantParams, opts?: SalesforceGrantOptions): Promise<SalesforceAccessTokenResponse> {
return super.grant(params as GrantParams, opts) as Promise<SalesforceAccessTokenResponse>;
}
/**
* @inheritdoc
*/
protected handleAccessTokenResponse(accessTokenResponse: SalesforceAccessTokenResponse, internalOpts: SalesforceGrantOptions) {
super.handleAccessTokenResponse(accessTokenResponse, internalOpts);
try {
if (internalOpts.verifySignature) {
if (internalOpts && internalOpts.clientSecret) {
verifySignature(internalOpts.clientSecret, accessTokenResponse);
} else {
throw new Error('Missing required string parameter: clientSecret');
}
}
if (internalOpts.parseUserInfo) {
parseUserInfo(accessTokenResponse);
}
} catch (error) {
throw new Error(`Failed to obtain grant: ${error.message}.`);
}
return accessTokenResponse;
}
/**
* @inheritdoc
*/
protected handleIntrospectionResponse(introspectionResponse: SalesforceIntrospectionResponse, internalOpts: SalesforceIntrospectionOptions) {
if (internalOpts.parseUserInfo) {
parseUserInfo(introspectionResponse);
}
return introspectionResponse;
}
}
|
financialforcedev/orizuru-auth
|
test/index/middleware/authCallback.test.ts
|
/*
* Copyright (c) 2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import chai from 'chai';
import sinon, { SinonStub } from 'sinon';
import sinonChai from 'sinon-chai';
import { Request, RequestHandler, Response } from '@financialforcedev/orizuru';
import { Environment, EVENT_AUTHORIZATION_HEADER_SET, OpenIdOptions, OpenIDTokenWithStandardClaims, SalesforceAccessTokenResponse } from '../../../src';
import * as webServer from '../../../src/index/flow/webServer';
import * as fail from '../../../src/index/middleware/common/fail';
import { createMiddleware } from '../../../src/index/middleware/authCallback';
const expect = chai.expect;
const has = sinon.match.has;
chai.use(sinonChai);
describe('index/middleware/authCallback', () => {
let app: Orizuru.IServer;
let env: Environment;
let requestAccessTokenStub: SinonStub;
beforeEach(() => {
env = {
httpTimeout: 4001,
issuerURI: 'https://login.salesforce.com/',
type: 'OpenID'
};
const openIdOptions: Partial<OpenIdOptions> = {
clientId: 'testClientId',
clientSecret: 'testClientSecret',
redirectUri: 'https://localhost:8080/api/auth/v1.0/callback',
scope: 'api openid',
signingSecret: 'testSigningSecret'
};
const partialApp: Partial<Orizuru.IServer> = {
emit: sinon.stub(),
options: {
authProvider: {
salesforce: env
},
openid: {
salesforce: openIdOptions as OpenIdOptions
}
}
};
app = partialApp as Orizuru.IServer;
requestAccessTokenStub = sinon.stub();
sinon.stub(webServer, 'createTokenGrantor').returns(requestAccessTokenStub);
sinon.stub(fail, 'fail');
});
afterEach(() => {
// Then
expect(webServer.createTokenGrantor).to.have.been.calledOnce;
expect(webServer.createTokenGrantor).to.have.been.calledWithExactly(app.options.authProvider.salesforce);
sinon.restore();
});
it('should return a function when called with the app', () => {
// Given
// When
const middleware = createMiddleware(app);
// Then
expect(middleware).to.be.a('function');
});
describe('checkUserGrant', () => {
let middleware: RequestHandler;
let req: Request;
let res: Response;
let next: SinonStub;
beforeEach(() => {
const partialRequest: Partial<Request> = {
headers: {},
ip: '1.1.1.1',
query: {
code: 'testCode'
}
};
req = partialRequest as Request;
const partialResponse: Partial<Response> = {};
res = partialResponse as Response;
next = sinon.stub();
middleware = createMiddleware(app, 'salesforce', app.options.openid.salesforce, {
decodeIdToken: true,
signingSecret: 'testSigningSecret'
});
});
describe('should fail the request', () => {
afterEach(() => {
// Then
expect(fail.fail).to.have.been.calledOnce;
expect(next).to.not.have.been.called;
});
it('if query is not on the request', async () => {
// Given
delete req.query;
// When
await middleware(req, res, next);
// Then
expect(fail.fail).to.have.been.calledWithExactly(app, has('message', 'Missing required object parameter: query'), req, res, next);
});
it('if the code is not on the request', async () => {
// Given
delete req.query.code;
// When
await middleware(req, res, next);
// Then
expect(fail.fail).to.have.been.calledWithExactly(app, has('message', 'Missing required string parameter: query[code]'), req, res, next);
});
it('if the query parameters contain an error', async () => {
// Given
req.query.error = 'access-denied';
// When
await middleware(req, res, next);
// Then
expect(fail.fail).to.have.been.calledWithExactly(app, has('message', 'access-denied'), req, res, next);
});
it('if requestAccessToken rejects', async () => {
// Given
requestAccessTokenStub.rejects(new Error('Invalid grant for user (<EMAIL>). Caused by: something or other'));
// When
await middleware(req, res, next);
// Then
expect(fail.fail).to.have.been.calledWithExactly(app, has('message', 'Invalid grant for user (<EMAIL>). Caused by: something or other'), req, res, next);
});
});
describe('should call next if the code is exchanged for an access token and update the authorization header', () => {
let accessTokenResponse: SalesforceAccessTokenResponse;
beforeEach(() => {
const partialIdToken: Partial<OpenIDTokenWithStandardClaims> = {
email: '<EMAIL>'
};
accessTokenResponse = {
access_token: '<KEY>',
id: 'https://login.salesforce.com/id/00Dxx0000001gPLEAY/005xx000001SwiUAAS',
id_token: partialIdToken as OpenIDTokenWithStandardClaims,
instance_url: 'https://yourInstance.salesforce.com/',
issued_at: '1278448384422',
scope: 'id api refresh_token',
signature: 'R9e8hftsV8AqMd5M3ddTXsXNr6NwHoye4VeNY8Tqs44=',
token_type: 'Bearer',
userInfo: {
id: '005xx000001SwiUAAS',
organizationId: '00Dxx0000001gPLEAY',
url: 'https://login.salesforce.com/id/00Dxx0000001gPLEAY/005xx000001SwiUAAS',
validated: true
}
};
requestAccessTokenStub.resolves(accessTokenResponse);
});
afterEach(() => {
// Then
expect(requestAccessTokenStub).to.have.been.calledOnce;
expect(requestAccessTokenStub).to.have.been.calledWithExactly({
clientId: 'testClientId',
clientSecret: 'testClientSecret',
code: 'testCode',
grantType: 'authorization_code',
redirectUri: 'https://localhost:8080/api/auth/v1.0/callback',
scope: 'api openid',
signingSecret: 'testSigningSecret'
}, { decodeIdToken: true, signingSecret: 'testSigningSecret' });
});
it('adding the orizuru userInfo property for a salesforce access token', async () => {
// Given
// When
await middleware(req, res, next);
// Then
expect(req.headers).to.have.property('authorization', 'Bearer <KEY>');
expect(req).to.have.property('orizuru');
expect(req.orizuru).to.have.property('salesforce').that.eqls({
instanceUrl: 'https://yourInstance.salesforce.com/',
userInfo: {
id: '005xx000001SwiUAAS',
organizationId: '00Dxx0000001gPLEAY',
url: 'https://login.salesforce.com/id/00Dxx0000001gPLEAY/005xx000001SwiUAAS',
validated: true
}
});
expect(req.orizuru!.salesforce).to.have.property('userInfo').that.eqls({
id: '005xx000001SwiUAAS',
organizationId: '00Dxx0000001gPLEAY',
url: 'https://login.salesforce.com/id/00Dxx0000001gPLEAY/005xx000001SwiUAAS',
validated: true
});
expect(app.emit).to.have.been.calledOnce;
expect(app.emit).to.have.been.calledWithExactly(EVENT_AUTHORIZATION_HEADER_SET, 'Authorization headers set for user (<EMAIL>) [1.1.1.1].');
expect(next).to.have.been.calledOnce;
expect(next).to.have.been.calledWithExactly();
expect(req.orizuru).to.not.have.property('accessToken');
expect(req.orizuru).to.not.have.property('grantChecked');
});
it('adding the orizuru userInfo property respecting an existing orizuru property', async () => {
// Given
req.orizuru = {
grantChecked: true
};
// When
await middleware(req, res, next);
// Then
expect(req.headers).to.have.property('authorization', 'Bearer 00Dx0000000BV7z!AR8AQP0jITN80ESEsj5EbaZTFG0RNBaT1cyWk7TrqoDjoNIWQ2ME_sTZzBjfmOE6zMHq6y8PIW4eWze9JksNEkWUl.Cju7m4');
expect(req).to.have.property('orizuru');
expect(req.orizuru).to.have.property('salesforce');
expect(req.orizuru!.salesforce).to.have.property('userInfo').that.eqls({
id: '005xx000001SwiUAAS',
organizationId: '00Dxx0000001gPLEAY',
url: 'https://login.salesforce.com/id/00Dxx0000001gPLEAY/005xx000001SwiUAAS',
validated: true
});
expect(req.orizuru).to.have.property('grantChecked', true);
expect(app.emit).to.have.been.calledOnce;
expect(app.emit).to.have.been.calledWithExactly(EVENT_AUTHORIZATION_HEADER_SET, 'Authorization headers set for user (<EMAIL>) [1.1.1.1].');
expect(next).to.have.been.calledOnce;
expect(next).to.have.been.calledWithExactly();
expect(req.orizuru).to.not.have.property('accessToken');
});
it('adding the orizuru access token property for a salesforce access token', async () => {
// Given
sinon.resetHistory();
middleware = createMiddleware(app, 'salesforce', app.options.openid.salesforce, {
decodeIdToken: true,
setTokenOnContext: true,
signingSecret: 'testSigningSecret'
});
// When
await middleware(req, res, next);
// Then
expect(req.headers).to.have.property('authorization', 'Bearer <KEY>BV7z!AR<KEY>');
expect(req).to.have.property('orizuru');
expect(req.orizuru).to.have.property('accessToken', '<KEY>');
expect(req.orizuru).to.have.property('salesforce');
expect(req.orizuru!.salesforce).to.have.property('userInfo').that.eqls({
id: '005xx000001SwiUAAS',
organizationId: '00Dxx0000001gPLEAY',
url: 'https://login.salesforce.com/id/00Dxx0000001gPLEAY/005xx000001SwiUAAS',
validated: true
});
expect(app.emit).to.have.been.calledOnce;
expect(app.emit).to.have.been.calledWithExactly(EVENT_AUTHORIZATION_HEADER_SET, 'Authorization headers set for user (<EMAIL>) [1.1.1.1].');
expect(next).to.have.been.calledOnce;
expect(next).to.have.been.calledWithExactly();
expect(req.orizuru).to.not.have.property('grantChecked');
});
it('adding the orizuru user property for an openid access token', async () => {
// Given
delete accessTokenResponse.id;
delete accessTokenResponse.instance_url;
delete accessTokenResponse.issued_at;
delete accessTokenResponse.signature;
// When
await middleware(req, res, next);
// Then
expect(req.headers).to.have.property('authorization', 'Bearer 00Dx0000000BV7z!AR<KEY>');
expect(app.emit).to.have.been.calledOnce;
expect(app.emit).to.have.been.calledWithExactly(EVENT_AUTHORIZATION_HEADER_SET, 'Authorization headers set for user (<EMAIL>) [1.1.1.1].');
expect(next).to.have.been.calledOnce;
expect(next).to.have.been.calledWithExactly();
expect(req).to.not.have.property('orizuru');
});
it('and emit an event with the user id if the id_token has not been decoded but the userinfo is present', async () => {
// Given
delete accessTokenResponse.id_token;
// When
await middleware(req, res, next);
// Then
expect(req.headers).to.have.property('authorization', 'Bearer <KEY>');
expect(app.emit).to.have.been.calledOnce;
expect(app.emit).to.have.been.calledWithExactly(EVENT_AUTHORIZATION_HEADER_SET, 'Authorization headers set for user (005xx000001SwiUAAS) [1.1.1.1].');
expect(next).to.have.been.calledOnce;
expect(next).to.have.been.calledWithExactly();
});
it('and emit an event with the user as unknown if the id_token has been decoded but the user id is not present', async () => {
// Given
delete accessTokenResponse.userInfo!.id;
delete (accessTokenResponse.id_token as OpenIDTokenWithStandardClaims).email;
// When
await middleware(req, res, next);
// Then
expect(req.headers).to.have.property('authorization', 'Bearer 00Dx0000000BV7z!AR8AQP0jITN80ESEsj5EbaZTFG0RNBaT1cyWk7TrqoDjoNIWQ2ME_sTZzBjfmOE6zMHq6y8PIW4eWze9JksNEkWUl.Cju7m4');
expect(app.emit).to.have.been.calledOnce;
expect(app.emit).to.have.been.calledWithExactly(EVENT_AUTHORIZATION_HEADER_SET, 'Authorization headers set for user (unknown) [1.1.1.1].');
expect(next).to.have.been.calledOnce;
expect(next).to.have.been.calledWithExactly();
});
it('and emit an event with the user as unknown if the id_token has not been decoded', async () => {
// Given
delete accessTokenResponse.id_token;
delete accessTokenResponse.userInfo;
// When
await middleware(req, res, next);
// Then
expect(req.headers).to.have.property('authorization', 'Bearer <KEY>');
expect(app.emit).to.have.been.calledOnce;
expect(app.emit).to.have.been.calledWithExactly(EVENT_AUTHORIZATION_HEADER_SET, 'Authorization headers set for user (unknown) [1.1.1.1].');
expect(next).to.have.been.calledOnce;
expect(next).to.have.been.calledWithExactly();
});
it('and not have an orizuru property if the userinfo has not been parsed', async () => {
// Given
delete accessTokenResponse.userInfo;
// When
await middleware(req, res, next);
// Then
expect(req.headers).to.have.property('authorization', 'Bearer <KEY>');
expect(app.emit).to.have.been.calledOnce;
expect(app.emit).to.have.been.calledWithExactly(EVENT_AUTHORIZATION_HEADER_SET, 'Authorization headers set for user (<EMAIL>) [1.1.1.1].');
expect(next).to.have.been.calledOnce;
expect(next).to.have.been.calledWithExactly();
expect(req).to.not.have.property('orizuru');
});
});
});
});
|
financialforcedev/orizuru-auth
|
test/index/client/validator/environment.test.ts
|
<reponame>financialforcedev/orizuru-auth<filename>test/index/client/validator/environment.test.ts
/*
* Copyright (c) 2017-2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import chai from 'chai';
import { Environment } from '../../../../src';
import { validate } from '../../../../src/index/client/validator/environment';
const expect = chai.expect;
describe('index/client/validator/environment', () => {
let env: Environment;
beforeEach(() => {
env = {
authorizationEndpoint: 'https://login.salesforce.com/services/oauth2/authorize',
httpTimeout: 4001,
issuerURI: 'https://login.salesforce.com',
revocationEndpoint: 'https://login.salesforce.com/services/oauth2/revoke',
tokenEndpoint: 'https://login.salesforce.com/services/oauth2/token',
type: 'OpenID'
};
});
describe('should reject', () => {
it('if the environment is undefined', () => {
// Given
// When
// Then
expect(() => validate(undefined)).to.throw('Missing required object parameter.');
});
it('if httpTimeout is undefined', () => {
// Given
delete env.httpTimeout;
// When
// Then
expect(() => validate(env)).to.throw('Missing required number parameter: httpTimeout.');
});
it('if httpTimeout is not an integer', () => {
// Given
env.httpTimeout = 'test' as unknown as number;
// When
// Then
expect(() => validate(env)).to.throw('Invalid parameter: httpTimeout is not a number.');
});
it('if issuerURI is undefined', () => {
// Given
delete env.issuerURI;
// When
// Then
expect(() => validate(env)).to.throw('Missing required string parameter: issuerURI.');
});
it('if issuerURI is empty', () => {
// Given
env.issuerURI = '';
// When
// Then
expect(() => validate(env)).to.throw('Invalid parameter: issuerURI cannot be empty.');
});
it('if issuerURI is not a string', () => {
// Given
Object.assign(env, {
issuerURI: 2
});
// When
// Then
expect(() => validate(env)).to.throw('Invalid parameter: issuerURI is not a string.');
});
it('if the type is undefined', () => {
// Given
delete env.type;
// When
// Then
expect(() => validate(env)).to.throw('Missing required string parameter: type.');
});
it('if the type is not a string', () => {
// Given
Object.assign(env, {
type: 2
});
// When
// Then
expect(() => validate(env)).to.throw('Invalid parameter: type is not a string.');
});
it('if the authorizationEndpoint is not a string', () => {
// Given
Object.assign(env, {
authorizationEndpoint: 2
});
// When
// Then
expect(() => validate(env)).to.throw('Invalid parameter: authorizationEndpoint is not a string.');
});
it('if the revocationEndpoint is not a string', () => {
// Given
Object.assign(env, {
revocationEndpoint: 2
});
// When
// Then
expect(() => validate(env)).to.throw('Invalid parameter: revocationEndpoint is not a string.');
});
it('if the tokenEndpoint is not a string', () => {
// Given
Object.assign(env, {
tokenEndpoint: 2
});
// When
// Then
expect(() => validate(env)).to.throw('Invalid parameter: tokenEndpoint is not a string.');
});
});
describe('should resolve', () => {
it('if the environment is correct using only the required properties', () => {
// Given
delete env.authorizationEndpoint;
delete env.revocationEndpoint;
delete env.tokenEndpoint;
// When
// Then
expect(validate(env)).to.eql({
authorizationEndpoint: undefined,
httpTimeout: 4001,
issuerURI: 'https://login.salesforce.com',
revocationEndpoint: undefined,
tokenEndpoint: undefined,
type: 'OpenID'
});
});
it('if the environment is correct, limiting to only the expected properties', () => {
// Given
Object.assign(env, {
invalid: true
});
// When
// Then
expect(validate(env)).to.eql({
authorizationEndpoint: 'https://login.salesforce.com/services/oauth2/authorize',
httpTimeout: 4001,
issuerURI: 'https://login.salesforce.com',
revocationEndpoint: 'https://login.salesforce.com/services/oauth2/revoke',
tokenEndpoint: 'https://login.salesforce.com/services/oauth2/token',
type: 'OpenID'
});
});
});
});
|
financialforcedev/orizuru-auth
|
src/index/client/cache.ts
|
/*
* Copyright (c) 2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @module client/cache
*/
import { createHash } from 'crypto';
import { AuthClient, OAuth2Client } from './oauth2';
import { OAuth2JWTClient } from './oauth2Jwt';
import { OpenIdClient } from './openid';
import { SalesforceClient } from './salesforce';
const cache = new Map<string, AuthClient>();
/**
* The Auth client environment parameters.
*/
export interface Environment {
/**
* [Authorization Endpoint](https://tools.ietf.org/html/rfc6749#section-3.1).
*
* This must be defined for OAuth2 clients; it should be omitted for OpenID clients as
* they use the [OpenID Provider Issuer Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html).
*/
authorizationEndpoint?: string;
/**
* The HTTP timeout used when creating an Auth Client.
*/
httpTimeout: number;
/**
* [Introspection Endpoint](https://tools.ietf.org/html/rfc7662#section-2).
*
* This may be defined for OAuth2 clients; it should be omitted for OpenID clients as
* they use the [OpenID Provider Issuer Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html).
*/
introspectionEndpoint?: string | null;
/**
* The Issuer URI used when creating an Auth Client.
*/
issuerURI: string;
/**
* [Revocation Endpoint](https://tools.ietf.org/html/rfc7009#section-2.1)
*
* This must be defined for OAuth2 clients; it should be omitted for OpenID clients as
* they use the [OpenID Provider Issuer Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html).
*/
revocationEndpoint?: string;
/**
* [Token Endpoint](https://tools.ietf.org/html/rfc6749#section-3.2)
*
* This must be defined for OAuth2 clients; it should be omitted for OpenID clients as
* they use the [OpenID Provider Issuer Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html).
*/
tokenEndpoint?: string;
/**
* The type of Auth Client.
*/
type: 'OAuth2' | 'OAuth2JWT' | 'OpenID' | 'Salesforce';
}
/**
* Finds the auth client for the given environment.
*
* If the auth client is not found, a new client is created and stored in the cache.
*
* @param env The auth environment parameters.
*/
export async function findOrCreateClient(env: Environment) {
const key = createKey(env);
let client = cache.get(key);
if (!client) {
if (env.type === 'Salesforce') {
client = new SalesforceClient(env);
} else if (env.type === 'OpenID') {
client = new OpenIdClient(env);
} else if (env.type === 'OAuth2JWT') {
client = new OAuth2JWTClient(env);
} else {
client = new OAuth2Client(env);
}
await client.init();
cache.set(key, client);
}
return client;
}
/**
* Clears the OpenID client cache.
*
* This results in the recreation of OpenID clients.
*/
export function clear() {
cache.clear();
}
/**
* Creates a hash key for the given environment to use in the cache.
*
* @param env The auth environment parameters.
*/
function createKey(env: Environment) {
const { httpTimeout, issuerURI, type } = env;
return createHash('sha1').update(`${type}|${issuerURI}|${httpTimeout}`).digest('hex');
}
|
financialforcedev/orizuru-auth
|
src/index/grant/grant.ts
|
/*
* Copyright (c) 2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @module grant/grant
*/
import { AccessTokenResponse, Environment, GrantOptions, JwtGrantParams, User, UserTokenGrantor, UserTokenGrantorParams } from '../..';
import { findOrCreateClient } from '../client/cache';
import { isSalesforceAccessTokenResponse, UserInfo } from '../client/salesforce/identity';
import { validate } from '../client/validator/environment';
export interface Grant {
/**
* The access token issued by the authorization server.
*/
accessToken: string;
/**
* A URL indicating the instance of the user’s org. For example: https://yourInstance.salesforce.com/.
*/
instanceUrl?: string;
/**
* The user information generated when parsing the [Identity URL](https://help.salesforce.com/articleView?id=remoteaccess_using_openid.htm).
*/
userInfo?: UserInfo;
}
/**
* Returns a function that can obtain a token for the passed user.
*
* @param env The auth environment parameters.
* @returns A function that retrieves the user credentials.
*/
export function getToken(env: Environment): UserTokenGrantor {
const validatedEnvironment = validate(env);
return async function getUserCredentials(params: UserTokenGrantorParams, opts?: GrantOptions) {
try {
validateUser(params.user);
// The TokenGrantorParams interface excludes the grant_type so that it
// doesn't have to be set by the caller. Make sure it is set here.
const internalParams: Partial<JwtGrantParams> = Object.assign({}, params);
internalParams.grantType = 'urn:ietf:params:oauth:grant-type:jwt-bearer';
const authorizationGrant = await obtainGrant(validatedEnvironment, internalParams as JwtGrantParams, opts);
return convertGrantToCredentials(authorizationGrant);
} catch (error) {
throw new Error(`Failed to obtain grant for user${error.message}.`);
}
};
}
/**
* Validates that the user contains the correct information.
* @param user The user to validate.
*/
function validateUser(user: User) {
if (!user) {
throw new Error('. Caused by: Missing required object parameter: user');
}
if (user.username == null) {
throw new Error('. Caused by: Missing required string parameter: user[username]');
}
if (!user.username.length) {
throw new Error('. Caused by: Invalid parameter: user[username] cannot be empty');
}
}
/**
* Obtains a grant for the given user using the OpenID client.
* @param env The auth environment parameters.
* @param params The parameters required for the JWT grant type.
* @param [opts] The grant options to be used.
* @returns The access token response.
*/
async function obtainGrant(env: Environment, params: JwtGrantParams, opts?: GrantOptions) {
try {
const client = await findOrCreateClient(env);
return await client.grant(params, opts);
} catch (error) {
throw new Error(` (${params.user.username}). Caused by: ${error.message}`);
}
}
/**
* Converts the access token response to a grant that can be used in tandem with
* other NPM modules such as [JSforce])https://github.com/jsforce/jsforce).
* @param token - The access token response.
* @returns The user credentials.
*/
function convertGrantToCredentials(token: AccessTokenResponse): Grant {
if (isSalesforceAccessTokenResponse(token)) {
return {
accessToken: token.access_token,
instanceUrl: token.instance_url,
userInfo: token.userInfo
};
}
return { accessToken: token.access_token };
}
|
financialforcedev/orizuru-auth
|
src/index/introspection/introspect.ts
|
<filename>src/index/introspection/introspect.ts
/*
* Copyright (c) 2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @module introspection/introspect
*/
import { Environment, IntrospectionOptions, TokenIntrospector } from '../..';
import { findOrCreateClient } from '../client/cache';
import { IntrospectionParams } from '../client/oauth2';
import { validate } from '../client/validator/environment';
/**
* Returns a function that introspects a token.
*
* @param env The auth environment parameters.
*/
export function createTokenIntrospector(env: Environment): TokenIntrospector {
const validatedEnvironment = validate(env);
return async function introspectToken(token: string, params: IntrospectionParams, opts?: IntrospectionOptions) {
const client = await findOrCreateClient(validatedEnvironment);
return client.introspect(token, params, opts);
};
}
|
financialforcedev/orizuru-auth
|
test/index/middleware/tokenIntrospection.test.ts
|
<reponame>financialforcedev/orizuru-auth<gh_stars>1-10
/*
* Copyright (c) 2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import chai from 'chai';
import sinon, { SinonStub } from 'sinon';
import sinonChai from 'sinon-chai';
import { Request, RequestHandler, Response } from '@financialforcedev/orizuru';
import { Environment, EVENT_TOKEN_INTROSPECTED, EVENT_TOKEN_VALIDATED, IntrospectionParams, IntrospectionResponse, OpenIdOptions } from '../../../src';
import * as introspect from '../../../src/index/introspection/introspect';
import * as accessToken from '../../../src/index/middleware/common/accessToken';
import * as fail from '../../../src/index/middleware/common/fail';
import { createMiddleware } from '../../../src/index/middleware/tokenIntrospection';
const expect = chai.expect;
const has = sinon.match.has;
chai.use(sinonChai);
describe('index/middleware/tokenIntrospection', () => {
let app: Orizuru.IServer;
let env: Environment;
let params: IntrospectionParams;
let introspectTokenStub: SinonStub;
beforeEach(() => {
env = {
httpTimeout: 4001,
issuerURI: 'https://login.salesforce.com/',
type: 'OpenID'
};
params = {
clientId: 'testClientId',
clientSecret: 'testClientSecret'
};
const partialApp: Partial<Orizuru.IServer> = {
emit: sinon.stub(),
options: {
authProvider: {
salesforce: env
},
openid: {
salesforce: params as OpenIdOptions
}
}
};
app = partialApp as Orizuru.IServer;
introspectTokenStub = sinon.stub();
sinon.stub(introspect, 'createTokenIntrospector').returns(introspectTokenStub);
sinon.stub(accessToken, 'extractAccessToken').returns('12345');
sinon.stub(fail, 'fail');
});
afterEach(() => {
// Then
expect(introspect.createTokenIntrospector).to.have.been.calledOnce;
expect(introspect.createTokenIntrospector).to.have.been.calledWithExactly(app.options.authProvider.salesforce);
sinon.restore();
});
it('should return a function when called with the app', () => {
// Given
// When
const middleware = createMiddleware(app);
// Then
expect(middleware).to.be.a('function');
});
describe('introspectToken', () => {
let middleware: RequestHandler;
let req: Request;
let res: Response;
let next: SinonStub;
beforeEach(() => {
const partialRequest: Partial<Request> = {
ip: '1.1.1.1'
};
req = partialRequest as Request;
const partialResponse: Partial<Response> = {};
res = partialResponse as Response;
next = sinon.stub();
});
describe('should fail the request', () => {
beforeEach(() => {
middleware = createMiddleware(app, 'salesforce', app.options.openid.salesforce);
});
afterEach(() => {
// Then
expect(fail.fail).to.have.been.calledOnce;
expect(next).to.not.have.been.called;
});
it('if validateAccessToken rejects', async () => {
// Given
req.headers = {
authorization: 'Bearer 12345'
};
introspectTokenStub.rejects(new Error('Failed to retrieve user information.'));
// When
await middleware(req, res, next);
// Then
expect(fail.fail).to.have.been.calledWithExactly(app, has('message', 'Failed to retrieve user information.'), req, res, next);
expect(introspectTokenStub).to.have.been.calledOnce;
expect(introspectTokenStub).to.have.been.calledWithExactly('12345', {
clientId: 'testClientId',
clientSecret: 'testClientSecret'
}, {});
});
});
describe('should call next if the token is introspected', () => {
let response: IntrospectionResponse;
beforeEach(() => {
req.headers = {
authorization: 'Bearer 12345'
};
middleware = createMiddleware(app, 'salesforce', app.options.openid.salesforce);
response = {
active: true,
client_id: 'OAuthSp',
exp: 1528502109,
iat: 1528494909,
nbf: 1528494909,
scope: 'id api web full refresh_token openid',
sub: 'https://login.salesforce.com/id/00Dxx0000001gEREAY/005xx000001Sv6AAAS',
token_type: 'access_token',
userInfo: {
id: '005xx000001Sv6AAAS',
organizationId: '00Dxx0000001gEREAY',
url: 'https://login.salesforce.com/id/00Dxx0000001gEREAY/005xx000001Sv6AAAS',
validated: false
},
username: '<EMAIL>'
};
introspectTokenStub.resolves(response);
});
afterEach(() => {
// Then
expect(introspectTokenStub).to.have.been.calledOnce;
expect(introspectTokenStub).to.have.been.calledWithExactly('12345', {
clientId: 'testClientId',
clientSecret: 'testClientSecret'
}, {});
expect(next).to.have.been.calledOnce;
expect(next).to.have.been.calledWithExactly();
});
it('adding the orizuru access token property for a salesforce access token', async () => {
// Given
sinon.resetHistory();
middleware = createMiddleware(app, 'salesforce', app.options.openid.salesforce, {
setTokenOnContext: true
});
// When
await middleware(req, res, next);
// Then
expect(req.headers).to.have.property('authorization', 'Bearer 12345');
expect(req).to.have.property('orizuru');
expect(req.orizuru).to.have.property('accessToken', '12345');
expect(req.orizuru).to.have.property('user').that.eqls({
organizationId: '00Dxx0000001gEREAY',
username: '<EMAIL>'
});
expect(req.orizuru).to.have.property('tokenInformation').that.eqls({
active: true,
client_id: 'OAuthSp',
exp: 1528502109,
iat: 1528494909,
nbf: 1528494909,
scope: 'id api web full refresh_token openid',
sub: 'https://login.salesforce.com/id/00Dxx0000001gEREAY/005xx000001Sv6AAAS',
token_type: 'access_token',
userInfo: {
id: '005xx000001Sv6AAAS',
organizationId: '00Dxx0000001gEREAY',
url: 'https://login.salesforce.com/id/00Dxx0000001gEREAY/005xx000001Sv6AAAS',
validated: false
},
username: '<EMAIL>'
});
expect(app.emit).to.have.been.calledTwice;
expect(app.emit).to.have.been.calledWithExactly(EVENT_TOKEN_INTROSPECTED, 'Token introspected for user (<EMAIL>) [1.1.1.1].');
expect(app.emit).to.have.been.calledWithExactly(EVENT_TOKEN_VALIDATED, 'Token validated for user (<EMAIL>) [1.1.1.1].');
});
it('and set orizuru on the request with the username', async () => {
// Given
// When
await middleware(req, res, next);
// Then
expect(req.orizuru).to.have.property('user').that.eqls({
organizationId: '00Dxx0000001gEREAY',
username: '<EMAIL>'
});
expect(req.orizuru).to.have.property('tokenInformation').that.eqls({
active: true,
client_id: 'OAuthSp',
exp: 1528502109,
iat: 1528494909,
nbf: 1528494909,
scope: 'id api web full refresh_token openid',
sub: 'https://login.salesforce.com/id/00Dxx0000001gEREAY/005xx000001Sv6AAAS',
token_type: 'access_token',
userInfo: {
id: '005xx000001Sv6AAAS',
organizationId: '00Dxx0000001gEREAY',
url: 'https://login.salesforce.com/id/00Dxx0000001gEREAY/005xx000001Sv6AAAS',
validated: false
},
username: '<EMAIL>'
});
expect(app.emit).to.have.been.calledTwice;
expect(app.emit).to.have.been.calledWithExactly(EVENT_TOKEN_INTROSPECTED, 'Token introspected for user (<EMAIL>) [1.1.1.1].');
expect(app.emit).to.have.been.calledWithExactly(EVENT_TOKEN_VALIDATED, 'Token validated for user (<EMAIL>) [1.1.1.1].');
expect(req.orizuru).to.not.have.property('accessToken');
});
it('and set orizuru on the request without the username', async () => {
// Given
delete response.sub;
delete response.userInfo;
delete response.username;
// When
await middleware(req, res, next);
// Then
expect(req.orizuru).to.have.property('tokenInformation').that.eqls({
active: true,
client_id: 'OAuthSp',
exp: 1528502109,
iat: 1528494909,
nbf: 1528494909,
scope: 'id api web full refresh_token openid',
token_type: 'access_token'
});
expect(app.emit).to.have.been.calledOnce;
expect(app.emit).to.have.been.calledWithExactly(EVENT_TOKEN_INTROSPECTED, 'Token introspected for user (unknown) [1.1.1.1].');
expect(req.orizuru).to.not.have.property('user');
});
it('and set orizuru on the request without the userInfo', async () => {
// Given
delete response.sub;
delete response.userInfo;
// When
await middleware(req, res, next);
// Then
expect(req.orizuru).to.have.property('user').that.eqls({
username: '<EMAIL>'
});
expect(req.orizuru).to.have.property('tokenInformation').that.eqls({
active: true,
client_id: 'OAuthSp',
exp: 1528502109,
iat: 1528494909,
nbf: 1528494909,
scope: 'id api web full refresh_token openid',
token_type: 'access_token',
username: '<EMAIL>'
});
expect(app.emit).to.have.been.calledTwice;
expect(app.emit).to.have.been.calledWithExactly(EVENT_TOKEN_INTROSPECTED, 'Token introspected for user (<EMAIL>) [1.1.1.1].');
expect(app.emit).to.have.been.calledWithExactly(EVENT_TOKEN_VALIDATED, 'Token validated for user (<EMAIL>) [1.1.1.1].');
});
it('and respect an existing orizuru object', async () => {
// Given
req.orizuru = {
grantChecked: true
};
// When
await middleware(req, res, next);
// Then
expect(req.orizuru).to.have.property('grantChecked', true);
expect(req.orizuru).to.have.property('user').that.eqls({
organizationId: '00Dxx0000001gEREAY',
username: '<EMAIL>'
});
expect(req.orizuru).to.have.property('tokenInformation').that.eqls({
active: true,
client_id: 'OAuthSp',
exp: 1528502109,
iat: 1528494909,
nbf: 1528494909,
scope: 'id api web full refresh_token openid',
sub: 'https://login.salesforce.com/id/00Dxx0000001gEREAY/005xx000001Sv6AAAS',
token_type: 'access_token',
userInfo: {
id: '005xx000001Sv6AAAS',
organizationId: '00Dxx0000001gEREAY',
url: 'https://login.salesforce.com/id/00Dxx0000001gEREAY/005xx000001Sv6AAAS',
validated: false
},
username: '<EMAIL>'
});
expect(app.emit).to.have.been.calledTwice;
expect(app.emit).to.have.been.calledWithExactly(EVENT_TOKEN_INTROSPECTED, 'Token introspected for user (<EMAIL>) [1.1.1.1].');
expect(app.emit).to.have.been.calledWithExactly(EVENT_TOKEN_VALIDATED, 'Token validated for user (<EMAIL>) [1.1.1.1].');
});
});
});
});
|
financialforcedev/orizuru-auth
|
test/index/grant/grant.test.ts
|
/*
* Copyright (c) 2017-2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
import sinon, { SinonStub, SinonStubbedInstance } from 'sinon';
import sinonChai from 'sinon-chai';
import { AccessTokenResponse, Environment, GrantOptions, JwtGrantParams, SalesforceAccessTokenResponse, UserTokenGrantor } from '../../../src';
import * as cache from '../../../src/index/client/cache';
import { AuthClient } from '../../../src/index/client/oauth2';
import { OpenIdClient } from '../../../src/index/client/openid';
import * as validator from '../../../src/index/client/validator/environment';
import { getToken } from '../../../src/index/grant/grant';
const expect = chai.expect;
chai.use(chaiAsPromised);
chai.use(sinonChai);
describe('index/grant/grant', () => {
let env: Environment;
let cacheStub: SinonStub<[Environment], Promise<AuthClient>>;
let openIdClientStubInstance: SinonStubbedInstance<OpenIdClient>;
beforeEach(() => {
env = {
httpTimeout: 4001,
issuerURI: 'https://login.salesforce.com/',
type: 'OpenID'
};
openIdClientStubInstance = sinon.createStubInstance(OpenIdClient);
cacheStub = sinon.stub(cache, 'findOrCreateClient').resolves(openIdClientStubInstance);
sinon.stub(validator, 'validate').returns(env);
});
afterEach(() => {
sinon.restore();
});
it('should return a function when called with the app', () => {
// Given
// When
const getUserCredentials = getToken(env);
// Then
expect(getUserCredentials).to.be.a('function');
expect(validator.validate).to.have.been.calledOnce;
expect(validator.validate).to.have.been.calledWithExactly(env);
});
describe('getUserCredentials', () => {
let getUserCredentials: UserTokenGrantor;
let params: JwtGrantParams;
let opts: GrantOptions;
beforeEach(() => {
params = {
clientId: 'testClientId',
grantType: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
signingSecret: 'testSigningSecret',
user: {
username: '<EMAIL>'
}
};
opts = {
decodeIdToken: false,
verifySignature: false
};
getUserCredentials = getToken(env);
});
describe('should throw an error', () => {
it('if user is missing', async () => {
// Given
delete params.user;
// When
// Then
await expect(getUserCredentials(params)).to.eventually.be.rejectedWith('Failed to obtain grant for user. Caused by: Missing required object parameter: user');
});
it('if username is missing', async () => {
// Given
delete params.user.username;
// When
// Then
await expect(getUserCredentials(params)).to.eventually.be.rejectedWith('Failed to obtain grant for user. Caused by: Missing required string parameter: user[username]');
});
it('if username is empty', async () => {
// Given
params.user.username = '';
// When
// Then
await expect(getUserCredentials(params)).to.eventually.be.rejectedWith('Failed to obtain grant for user. Caused by: Invalid parameter: user[username] cannot be empty');
});
it('if findOrCreateClient rejects', async () => {
// Given
cacheStub.rejects(new Error('something or other'));
// When
await expect(getUserCredentials(params)).to.eventually.be.rejectedWith('Failed to obtain grant for user (<EMAIL>). Caused by: something or other');
// Then
expect(cache.findOrCreateClient).to.have.been.calledOnce;
expect(cache.findOrCreateClient).to.have.been.calledWith(env);
});
it('if obtainAuthorizationGrant rejects', async () => {
// Given
openIdClientStubInstance.grant.throws(new Error('something or other'));
// When
await expect(getUserCredentials(params, opts)).to.eventually.be.rejectedWith('Failed to obtain grant for user (<EMAIL>). Caused by: something or other');
// Then
expect(cache.findOrCreateClient).to.have.been.calledOnce;
expect(cache.findOrCreateClient).to.have.been.calledWith(env);
expect(openIdClientStubInstance.grant).to.have.been.calledWith({
clientId: 'testClientId',
grantType: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
signingSecret: 'testSigningSecret',
user: {
username: '<EMAIL>'
}
}, { decodeIdToken: false, verifySignature: false });
});
});
describe('should obtain the grant', () => {
it('for a salesforce access token response', async () => {
// Given
const token: SalesforceAccessTokenResponse = {
access_token: '<KEY>',
id: 'https://login.salesforce.com/id/00Dxx0000001gPLEAY/005xx000001SwiUAAS',
instance_url: 'https:// yourInstance.salesforce.com',
issued_at: '1551531242643',
scope: 'web openid api id',
signature: 'd4A6A67xJuzK4iYucL/EsnC/caaWl0aUfs1a8aSFAMw=',
token_type: 'Bearer',
userInfo: {
id: '005xx000001SwiUAAS',
organizationId: '00Dxx0000001gPLEAY',
url: 'https://login.salesforce.com/id/00Dxx0000001gPLEAY/005xx000001SwiUAAS',
validated: true
}
};
openIdClientStubInstance.grant.resolves(token);
// When
const userCredentials = await getUserCredentials(params, opts);
// Then
expect(userCredentials).to.eql({
accessToken: '<KEY>zU31IbYNNJguseu',
instanceUrl: 'https:// yourInstance.salesforce.com',
userInfo: {
id: '005xx000001SwiUAAS',
organizationId: '00Dxx0000001gPLEAY',
url: 'https://login.salesforce.com/id/00Dxx0000001gPLEAY/005xx000001SwiUAAS',
validated: true
}
});
expect(cache.findOrCreateClient).to.have.been.calledOnce;
expect(cache.findOrCreateClient).to.have.been.calledWith(env);
expect(openIdClientStubInstance.grant).to.have.been.calledWith({
clientId: 'testClientId',
grantType: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
signingSecret: 'testSigningSecret',
user: {
username: '<EMAIL>'
}
}, { decodeIdToken: false, verifySignature: false });
});
it('for an access token response', async () => {
// Given
const token: AccessTokenResponse = {
access_token: '<KEY>',
scope: 'web openid api id',
token_type: 'Bearer'
};
openIdClientStubInstance.grant.resolves(token);
// When
const userCredentials = await getUserCredentials(params, opts);
// Then
expect(userCredentials).to.eql({
accessToken: '<KEY>'
});
expect(cache.findOrCreateClient).to.have.been.calledOnce;
expect(cache.findOrCreateClient).to.have.been.calledWith(env);
expect(openIdClientStubInstance.grant).to.have.been.calledWith({
clientId: 'testClientId',
grantType: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
signingSecret: 'testSigningSecret',
user: {
username: '<EMAIL>'
}
}, { decodeIdToken: false, verifySignature: false });
});
});
});
});
|
financialforcedev/orizuru-auth
|
src/index/middleware/identity.ts
|
<filename>src/index/middleware/identity.ts
/*
* Copyright (c) 2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @module middleware/identity
*/
import { AxiosResponse, default as axios } from 'axios';
import { NextFunction, Request, RequestHandler, Response } from '@financialforcedev/orizuru';
import { EVENT_USER_IDENTITY_RETRIEVED, SalesforceIdentity } from '../..';
import { extractAccessToken } from './common/accessToken';
import { fail } from './common/fail';
/**
* Returns an express middleware that uses the [Identity URL](https://help.salesforce.com/articleView?id=remoteaccess_using_openid.htm)
* to retrieve information about the current Salesforce user.
*
* This can be used in tandem with the **auth callback** middleware to retrieve the user information with the granted access token.
*
* @fires EVENT_USER_IDENTITY_RETRIEVED
* @param app The Orizuru server instance.
* @returns An express middleware that retrieves the identity information.
*/
export function createMiddleware(app: Orizuru.IServer): RequestHandler {
return async function retrieveIdentityInformation(req: Request, res: Response, next: NextFunction) {
try {
const identityUrl = validateRequest(req);
const identityResponse: AxiosResponse<SalesforceIdentity> = await axios.get(identityUrl, {
headers: {
Authorization: req.headers.authorization
}
});
setIdentityInformation(app, req, identityResponse.data);
next();
} catch (error) {
fail(app, error, req, res, next);
}
};
}
/**
* Validate the request.
*
* @param req The HTTP request.
* @returns The Identity URL.
*/
function validateRequest(req: Request) {
extractAccessToken(req);
if (!req.orizuru) {
throw new Error('Missing required object parameter: orizuru.');
}
if (!req.orizuru.salesforce) {
throw new Error('Missing required object parameter: orizuru[salesforce].');
}
const salesforce = req.orizuru.salesforce;
if (!salesforce.userInfo) {
throw new Error('Missing required object parameter: orizuru[salesforce][userInfo].');
}
const userInfo = salesforce.userInfo;
if (!userInfo.url) {
throw new Error('Missing required string parameter: orizuru[salesforce][userInfo][url].');
}
if (userInfo.validated === false) {
throw new Error('The Identity URL must be validated.');
}
if (!userInfo.validated) {
throw new Error('Missing required string parameter: orizuru[salesforce][userInfo][validated].');
}
return userInfo.url;
}
/**
* Sets the identity information in the Orizuru context and emits a user identity
* retrieved event.
*
* @param app The Orizuru server instance.
* @param req The HTTP request.
* @param identity The Salesforce Identity.
*/
function setIdentityInformation(app: Orizuru.IServer, req: Request, identity: SalesforceIdentity) {
req.orizuru!.salesforce!.identity = identity;
app.emit(EVENT_USER_IDENTITY_RETRIEVED, `Identity information retrieved for user (${identity.username}) [${req.ip}].`);
}
|
financialforcedev/orizuru-auth
|
systemtests/suite2.test.ts
|
<reponame>financialforcedev/orizuru-auth
/*
* Copyright (c) 2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import chai from 'chai';
import config from 'config';
import { Browser, BrowserContext, launch, Page } from 'puppeteer';
import sinon from 'sinon';
import sinonChai from 'sinon-chai';
import superagent from 'superagent';
import { EVENT_AUTHORIZATION_HEADER_SET, EVENT_DENIED } from '../src/index';
import { TestServer, TrustedSuperAgentRequest } from './server/common';
import { createServer } from './server/google';
const expect = chai.expect;
const fail = chai.assert.fail;
chai.use(sinonChai);
describe('Suite 2 - Puppeteer script for Google authentication using OpenID client', () => {
let accessToken: string;
let browser: Browser;
let context: BrowserContext;
let page: Page;
let server: TestServer;
beforeAll(async () => {
jest.setTimeout(30000);
server = await createServer('googleOpenId');
browser = await launch({
headless: true,
ignoreHTTPSErrors: true
});
sinon.spy(server, 'emit');
await server.listen();
});
beforeEach(async () => {
context = await browser.createIncognitoBrowserContext();
page = await context.newPage();
});
afterEach(async () => {
await context.close();
sinon.reset();
});
afterAll(async () => {
await browser.close();
await server.close();
sinon.restore();
});
it('should approve the app to obtain an access token', async () => {
// Given
const username = config.get<string>('test.google.username');
const password = config.get<string>('<PASSWORD>.google.password');
await page.goto('https://localhost:8080/api/v1.0/auth');
await page.waitForSelector('#identifierId');
await page.type('#identifierId', username);
await Promise.all([
page.click('#identifierNext'),
page.waitForSelector('#passwordNext')
]);
// Sleep for a couple of seconds
await new Promise((resolve) => setTimeout(resolve, 2000));
await page.type('input[name="password"]', password);
await Promise.all([
page.click('#passwordNext'),
page.waitForSelector('#submit_approve_access')
]);
await Promise.all([
page.click('#submit_approve_access'),
page.waitForNavigation()
]);
const contents = await page.content();
const regex = new RegExp('<pre .*>(.*)</pre>');
const matches = regex.exec(contents) as RegExpExecArray;
// Then
expect(matches).not.to.be.null;
expect(matches).to.have.length(2);
const headers = JSON.parse(matches.pop() as string);
expect(headers).to.have.property('authorization').that.matches(/^Bearer .+$/);
expect(server.emit).to.have.been.calledOnce;
expect(server.emit).to.have.been.calledWithExactly(EVENT_AUTHORIZATION_HEADER_SET, `Authorization headers set for user (${username}) [::1].`);
accessToken = headers.authorization;
});
it('should revoke the token', async () => {
// Given
if (!accessToken) {
fail('No access token');
}
const request = superagent.get('https://localhost:8080/api/auth/v1.0/revokeToken') as TrustedSuperAgentRequest;
// When
const response = await request.trustLocalhost(true)
.set('Authorization', accessToken)
.send({});
// Then
expect(response).to.have.property('status', 200);
expect(response).to.have.property('body').that.eqls({
tokenRevoked: true
});
});
it('should deny the app and obtain a 401 response', async () => {
// Given
const username = config.get<string>('test.google.username');
const password = config.get<string>('<PASSWORD>');
await page.goto('https://localhost:8080/api/v1.0/auth');
await page.waitForSelector('#identifierId');
await page.type('#identifierId', username);
await Promise.all([
page.click('#identifierNext'),
page.waitForSelector('#passwordNext')
]);
// Sleep for a couple of seconds
await new Promise((resolve) => setTimeout(resolve, 2000));
await page.type('input[name="password"]', password);
await Promise.all([
page.click('#passwordNext'),
page.waitForSelector('#submit_approve_access')
]);
// When
await Promise.all([
page.click('#submit_deny_access'),
page.waitForResponse((res) => {
if (res.status() === 401) {
return true;
}
return false;
})
]);
// Then
expect(server.emit).to.have.been.calledOnce;
expect(server.emit).to.have.been.calledWithExactly(EVENT_DENIED, 'Access denied to: ::1. Error: access_denied');
});
});
|
financialforcedev/orizuru-auth
|
test/index/client/salesforce/identity.test.ts
|
/*
* Copyright (c) 2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import chai from 'chai';
import sinon from 'sinon';
import sinonChai from 'sinon-chai';
import { SalesforceAccessTokenResponse } from '../../../../src';
import { parseUserInfo, UserInfoResponse, verifySignature } from '../../../../src/index/client/salesforce/identity';
const expect = chai.expect;
chai.use(sinonChai);
describe('index/client/salesforce/identity', () => {
beforeEach(() => {
sinon.stub(Date, 'now').returns(1551521526000);
});
afterEach(() => {
sinon.restore();
});
describe('parseUserInfo', () => {
let userInfoResponse: UserInfoResponse;
beforeEach(() => {
userInfoResponse = {
id: 'https://login.salesforce.com/id/00Dxx0000001gPLEAY/005xx000001SwiUAAS'
};
});
describe('should throw an error', () => {
it('if the id is not present when validated', () => {
// Given
delete userInfoResponse.id;
// When
// Then
expect(() => parseUserInfo(userInfoResponse)).to.throw('Missing required string parameter: identityUrl');
});
it('if the user ID is not present', () => {
// Given
userInfoResponse.id = 'https://login.salesforce.com/id';
// When
// Then
expect(() => parseUserInfo(userInfoResponse)).to.throw('Missing required string parameter: id');
});
it('if the organization ID is not present', () => {
// Given
userInfoResponse.id = 'https://login.salesforce.com/id/00Dxx0000001gPLEAY';
// When
// Then
expect(() => parseUserInfo(userInfoResponse)).to.throw('Missing required string parameter: organizationId');
});
});
it('should parse the user information from the id property', () => {
// Given
// When
parseUserInfo(userInfoResponse);
// Then
expect(userInfoResponse).to.eql({
id: 'https://login.salesforce.com/id/00Dxx0000001gPLEAY/005xx000001SwiUAAS',
userInfo: {
id: '005xx000001SwiUAAS',
organizationId: '00Dxx0000001gPLEAY',
url: 'https://login.salesforce.com/id/00Dxx0000001gPLEAY/005xx000001SwiUAAS',
validated: false
}
});
});
it('should parse the user information from the sub property', () => {
// Given
userInfoResponse.sub = userInfoResponse.id;
delete userInfoResponse.id;
// When
parseUserInfo(userInfoResponse);
// Then
expect(userInfoResponse).to.eql({
sub: 'https://login.salesforce.com/id/00Dxx0000001gPLEAY/005xx000001SwiUAAS',
userInfo: {
id: '005xx000001SwiUAAS',
organizationId: '00Dxx0000001gPLEAY',
url: 'https://login.salesforce.com/id/00Dxx0000001gPLEAY/005xx000001SwiUAAS',
validated: true
}
});
});
it('should respect an existing userinfo property', () => {
// Given
userInfoResponse.userInfo = {
url: 'https://login.salesforce.com/id/00Dxx0000001gPLEAY/005xx000001SwiUAAS',
validated: true
};
// When
parseUserInfo(userInfoResponse);
// Then
expect(userInfoResponse).to.eql({
id: 'https://login.salesforce.com/id/00Dxx0000001gPLEAY/005xx000001SwiUAAS',
userInfo: {
id: '005xx000001SwiUAAS',
organizationId: '00Dxx0000001gPLEAY',
url: 'https://login.salesforce.com/id/00Dxx0000001gPLEAY/005xx000001SwiUAAS',
validated: true
}
});
});
});
describe('verifySignature', () => {
let accessTokenResponse: SalesforceAccessTokenResponse;
beforeEach(() => {
accessTokenResponse = {
access_token: '00Dxx0000001gPL!AR8AQJXg5oj8jXSgxJfA0lBog.39AsX.LVpxezPwuX5VAIrrbbHMuol7GQxnMeYMN7cj8EoWr78nt1u44zU31IbYNNJguseu',
id: 'https://login.salesforce.com/id/00Dxx0000001gPLEAY/005xx000001SwiUAAS',
id_token: '<KEY>',
instance_url: 'https:// yourInstance.salesforce.com',
issued_at: '1551531242643',
scope: 'web openid api id',
signature: 'HHjDwETDb5VyLcjcB6+c/brBnhAE7zNKu0bgYnVqn9o=',
token_type: 'Bearer'
};
});
describe('should throw an error', () => {
it('if the signature is not present when validated', () => {
// Given
delete accessTokenResponse.signature;
// When
// Then
expect(() => verifySignature('testOpenidClientSecret', accessTokenResponse)).to.throw('No signature present');
});
it('if the signature is not the correct length', () => {
// Given
accessTokenResponse.signature = 'invalid';
// When
expect(() => verifySignature('testOpenidClientSecret', accessTokenResponse)).to.throw('Invalid signature');
});
it('if the signature does not match the expected signature', () => {
// Given
accessTokenResponse.signature = 'd4A6A67xJuzK4iYucL/EsnC/caaWl0aUfs1a9aSFAMw=';
// When
// Then
expect(() => verifySignature('testOpenidClientSecret', accessTokenResponse)).to.throw('Invalid signature');
});
});
describe('should not throw an error', () => {
it('if the signature is valid', () => {
// Given
// When
expect(() => verifySignature('testOpenidClientSecret', accessTokenResponse)).to.not.throw();
// Then
expect(accessTokenResponse).to.eql({
access_token: '<KEY>',
id: 'https://login.salesforce.com/id/00Dxx0000001gPLEAY/005xx000001SwiUAAS',
id_token: '<KEY>',
instance_url: 'https:// yourInstance.salesforce.com',
issued_at: '1551531242643',
scope: 'web openid api id',
signature: 'HHjDwETDb5VyLcjcB6+c/brBnhAE7zNKu0bgYnVqn9o=',
token_type: 'Bearer',
userInfo: {
url: 'https://login.salesforce.com/id/00Dxx0000001gPLEAY/005xx000001SwiUAAS',
validated: true
}
});
});
});
});
});
|
financialforcedev/orizuru-auth
|
src/index/flow/refreshToken.ts
|
<reponame>financialforcedev/orizuru-auth
/*
* Copyright (c) 2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @module flow/refreshToken
*/
import { AccessTokenResponse, Environment, GrantOptions, RefreshAccessTokenGrantor, RefreshGrantParams, RefreshTokenGrantorParams } from '..';
import { findOrCreateClient } from '../client/cache';
import { validate } from '../client/validator/environment';
/**
* Uses the [OAuth 2.0 Refresh Token Flow](https://help.salesforce.com/articleView?id=remoteaccess_oauth_refresh_token_flow.htm) to renew tokens issued by the web server or
* user-agent flows.
*
* @param env The auth environment parameters.
* @returns A function that requests an access token from the given refresh token.
*/
export function createTokenGrantor(env: Environment): RefreshAccessTokenGrantor {
const validatedEnvironment = validate(env);
return async function requestAccessToken(params: RefreshTokenGrantorParams, opts?: GrantOptions): Promise<AccessTokenResponse> {
const client = await findOrCreateClient(validatedEnvironment);
// The RefreshTokenGrantorParams interface excludes the grant_type so that it
// doesn't have to be set by the caller. Make sure it is set here.
const internalParams: Partial<RefreshGrantParams> = Object.assign({}, params);
internalParams.grantType = 'refresh_token';
const accessTokenResponse = await client.grant(internalParams as RefreshGrantParams, opts);
accessTokenResponse.refresh_token = params.refreshToken;
return accessTokenResponse;
};
}
|
financialforcedev/orizuru-auth
|
src/index/middleware/tokenValidator.ts
|
<reponame>financialforcedev/orizuru-auth<filename>src/index/middleware/tokenValidator.ts
/*
* Copyright (c) 2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @module middleware/tokenValidator
*/
import { NextFunction, Request, RequestHandler, Response } from '@financialforcedev/orizuru';
import { EVENT_TOKEN_VALIDATED, OpenIDTokenWithStandardClaims, UserInfoOptions } from '../..';
import { SalesforceUser } from '../client/salesforce';
import { createUserInfoRequester } from '../userInfo/userinfo';
import { DEFAULT_MIDDLEWARE_OPTIONS, extractAccessToken, MiddlewareOptions, setAccessTokenOnRequest } from './common/accessToken';
import { fail } from './common/fail';
const instanceUrlRegex = new RegExp('(https:\/\/[^\/]*)');
/**
* Returns an express middleware that validates the OpenID Connect access token
* passed in an HTTP Authorization header and if successful sets the user object onto
* the request object.
*
* @fires EVENT_TOKEN_VALIDATED, EVENT_DENIED
* @param app The Orizuru server instance.
* @param [provider] The name of the auth provider. Defaults to 'salesforce'.
* @param [opts] The optional parameters used when requesting user information.
* @returns An express middleware that validates an access token.
*/
export function createMiddleware(app: Orizuru.IServer, provider?: string, opts?: MiddlewareOptions & UserInfoOptions): RequestHandler {
const internalProvider = provider || 'salesforce';
const { setTokenOnContext, ...userInfoOptions } = opts || DEFAULT_MIDDLEWARE_OPTIONS;
const requestUserInfo = createUserInfoRequester(app.options.authProvider[internalProvider]);
return async function validateToken(req: Request, res: Response, next: NextFunction) {
try {
const accessToken = extractAccessToken(req);
const userInfo = await requestUserInfo(accessToken, userInfoOptions);
setUserOnRequest(app, req, userInfo);
setAccessTokenOnRequest(req, accessToken, setTokenOnContext);
setInstanceUrlOnRequest(req, userInfo);
next();
} catch (error) {
fail(app, error, req, res, next);
}
};
}
/**
* Sets the user on the Orizuru context.
*
* @fires EVENT_TOKEN_VALIDATED
* @param app The Orizuru server instance.
* @param req The HTTP request.
* @param userInfo The user information.
*/
function setUserOnRequest(app: Orizuru.IServer, req: Request, userInfo: OpenIDTokenWithStandardClaims) {
const user: SalesforceUser = {
username: userInfo.preferred_username
};
if (userInfo.organization_id && typeof userInfo.organization_id === 'string') {
user.organizationId = userInfo.organization_id;
}
const orizuru = req.orizuru || {};
orizuru.user = user;
req.orizuru = orizuru;
app.emit(EVENT_TOKEN_VALIDATED, `Token validated for user (${user.username}) [${req.ip}].`);
}
/**
* Sets the Salesforce instance URL on the Orizuru context.
*
* @param req The HTTP request.
* @param userInfo The user information.
*/
function setInstanceUrlOnRequest(req: Request, userInfo: OpenIDTokenWithStandardClaims) {
if (!userInfo.urls) {
return;
}
const orizuru = req.orizuru!;
orizuru.salesforce = orizuru.salesforce || {};
const urls = Object.values(userInfo.urls);
while (urls.length) {
const url = urls.shift();
const regexResults = instanceUrlRegex.exec(url);
if (regexResults) {
orizuru.salesforce.instanceUrl = regexResults[0];
break;
}
}
req.orizuru = orizuru;
}
|
financialforcedev/orizuru-auth
|
test/index/client/cache.test.ts
|
<reponame>financialforcedev/orizuru-auth<gh_stars>1-10
/*
* Copyright (c) 2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import chai from 'chai';
import sinon, { SinonStub, SinonStubbedInstance } from 'sinon';
import sinonChai from 'sinon-chai';
import crypto, { Hash } from 'crypto';
import { TransformOptions } from 'stream';
import { Environment } from '../../../src';
import * as oauth2Client from '../../../src/index/client/oauth2';
import * as oauth2JwtClient from '../../../src/index/client/oauth2Jwt';
import * as openIdClient from '../../../src/index/client/openid';
import * as salesforceClient from '../../../src/index/client/salesforce';
import * as cache from '../../../src/index/client/cache';
const expect = chai.expect;
chai.use(sinonChai);
describe('index/client/cache', () => {
let productionEnv: Environment;
let sandboxEnvironment: Environment;
let createHashStub: SinonStub<[string, (TransformOptions | undefined)?], crypto.Hash>;
let digestStub: SinonStub;
let updateStub: SinonStub;
let oauth2ClientStubInstance: SinonStubbedInstance<oauth2Client.OAuth2Client>;
let oauth2JwtClientStubInstance: SinonStubbedInstance<oauth2JwtClient.OAuth2JWTClient>;
let openIdClientStubInstance: SinonStubbedInstance<openIdClient.OpenIdClient>;
let salesforceClientStubInstance: SinonStubbedInstance<salesforceClient.SalesforceClient>;
beforeEach(() => {
productionEnv = {
httpTimeout: 4001,
issuerURI: 'https://login.salesforce.com',
type: 'OpenID'
};
sandboxEnvironment = {
httpTimeout: 4001,
issuerURI: 'https://test.salesforce.com',
type: 'OpenID'
};
digestStub = sinon.stub();
updateStub = sinon.stub();
const partialHash: Partial<Hash> = {
digest: digestStub,
update: updateStub
};
updateStub.returns(partialHash);
createHashStub = sinon.stub(crypto, 'createHash').returns(partialHash as Hash);
oauth2ClientStubInstance = sinon.createStubInstance(oauth2Client.OAuth2Client);
sinon.stub(oauth2Client, 'OAuth2Client').returns(oauth2ClientStubInstance);
oauth2JwtClientStubInstance = sinon.createStubInstance(oauth2JwtClient.OAuth2JWTClient);
sinon.stub(oauth2JwtClient, 'OAuth2JWTClient').returns(oauth2JwtClientStubInstance);
openIdClientStubInstance = sinon.createStubInstance(openIdClient.OpenIdClient);
sinon.stub(openIdClient, 'OpenIdClient').returns(openIdClientStubInstance);
salesforceClientStubInstance = sinon.createStubInstance(salesforceClient.SalesforceClient);
sinon.stub(salesforceClient, 'SalesforceClient').returns(salesforceClientStubInstance);
});
afterEach(() => {
sinon.restore();
cache.clear();
});
describe('findOrCreateClient', () => {
describe('should create the correct clients', () => {
it('OAuth2Client', async () => {
// Given
const env: Environment = {
httpTimeout: 4001,
issuerURI: 'https://login.salesforce.com',
type: 'OAuth2'
};
// When
await cache.findOrCreateClient(env);
/// Then
expect(oauth2Client.OAuth2Client).to.have.been.calledOnce;
expect(oauth2Client.OAuth2Client).to.have.been.calledWithNew;
expect(oauth2ClientStubInstance.init).to.have.been.calledOnce;
expect(oauth2ClientStubInstance.init).to.have.been.calledWithExactly();
expect(oauth2JwtClient.OAuth2JWTClient).to.not.have.been.called;
expect(oauth2JwtClientStubInstance.init).to.not.have.been.called;
expect(salesforceClient.SalesforceClient).to.not.have.been.called;
expect(salesforceClientStubInstance.init).to.not.have.been.called;
expect(oauth2JwtClient.OAuth2JWTClient).to.not.have.been.called;
expect(oauth2JwtClientStubInstance.init).to.not.have.been.called;
});
it('OAuth2JWTClient', async () => {
// Given
const env: Environment = {
httpTimeout: 4001,
issuerURI: 'https://login.salesforce.com',
type: 'OAuth2JWT'
};
// When
await cache.findOrCreateClient(env);
/// Then
expect(oauth2JwtClient.OAuth2JWTClient).to.have.been.calledOnce;
expect(oauth2JwtClient.OAuth2JWTClient).to.have.been.calledWithNew;
expect(oauth2JwtClientStubInstance.init).to.have.been.calledOnce;
expect(oauth2JwtClientStubInstance.init).to.have.been.calledWithExactly();
expect(oauth2Client.OAuth2Client).to.not.have.been.called;
expect(oauth2ClientStubInstance.init).to.not.have.been.called;
expect(openIdClient.OpenIdClient).to.not.have.been.called;
expect(openIdClientStubInstance.init).to.not.have.been.called;
expect(salesforceClient.SalesforceClient).to.not.have.been.called;
expect(salesforceClientStubInstance.init).to.not.have.been.called;
});
it('OpenIdClient', async () => {
// Given
const env: Environment = {
httpTimeout: 4001,
issuerURI: 'https://login.salesforce.com',
type: 'OpenID'
};
// When
await cache.findOrCreateClient(env);
/// Then
expect(openIdClient.OpenIdClient).to.have.been.calledOnce;
expect(openIdClient.OpenIdClient).to.have.been.calledWithNew;
expect(openIdClientStubInstance.init).to.have.been.calledOnce;
expect(openIdClientStubInstance.init).to.have.been.calledWithExactly();
expect(oauth2Client.OAuth2Client).to.not.have.been.called;
expect(oauth2ClientStubInstance.init).to.not.have.been.called;
expect(oauth2JwtClient.OAuth2JWTClient).to.not.have.been.called;
expect(oauth2JwtClientStubInstance.init).to.not.have.been.called;
expect(salesforceClient.SalesforceClient).to.not.have.been.called;
expect(salesforceClientStubInstance.init).to.not.have.been.called;
});
it('Salesforce', async () => {
// Given
const env: Environment = {
httpTimeout: 4001,
issuerURI: 'https://login.salesforce.<EMAIL>',
type: 'Salesforce'
};
// When
await cache.findOrCreateClient(env);
/// Then
expect(salesforceClient.SalesforceClient).to.have.been.calledOnce;
expect(salesforceClient.SalesforceClient).to.have.been.calledWithNew;
expect(salesforceClientStubInstance.init).to.have.been.calledOnce;
expect(salesforceClientStubInstance.init).to.have.been.calledWithExactly();
expect(oauth2Client.OAuth2Client).to.not.have.been.called;
expect(oauth2ClientStubInstance.init).to.not.have.been.called;
expect(oauth2JwtClient.OAuth2JWTClient).to.not.have.been.called;
expect(oauth2JwtClientStubInstance.init).to.not.have.been.called;
expect(openIdClient.OpenIdClient).to.not.have.been.called;
expect(openIdClientStubInstance.init).to.not.have.been.called;
});
});
it('should create a new client if it is not in the cache', async () => {
// Given
digestStub.returns('key');
// When
await cache.findOrCreateClient(productionEnv);
// Then
expect(createHashStub).to.have.been.calledOnce;
expect(createHashStub).to.have.been.calledWithExactly('sha1');
expect(updateStub).to.have.been.calledOnce;
expect(updateStub).to.have.been.calledWithExactly('OpenID|https://login.salesforce.com|4001');
expect(digestStub).to.have.been.calledOnce;
expect(digestStub).to.have.been.calledWithExactly('hex');
expect(openIdClient.OpenIdClient).to.have.been.calledOnce;
expect(openIdClient.OpenIdClient).to.have.been.calledWithNew;
expect(openIdClientStubInstance.init).to.have.been.calledOnce;
expect(openIdClientStubInstance.init).to.have.been.calledWithExactly();
expect(oauth2Client.OAuth2Client).to.not.have.been.called;
expect(oauth2ClientStubInstance.init).to.not.have.been.called;
expect(salesforceClient.SalesforceClient).to.not.have.been.called;
expect(salesforceClientStubInstance.init).to.not.have.been.called;
expect(oauth2JwtClient.OAuth2JWTClient).to.not.have.been.called;
expect(oauth2JwtClientStubInstance.init).to.not.have.been.called;
});
it('use the same client for subsequent calls', async () => {
// Given
digestStub.returns('key');
// When
await cache.findOrCreateClient(productionEnv);
await cache.findOrCreateClient(productionEnv);
// Then
expect(createHashStub).to.have.been.calledTwice;
expect(createHashStub).to.have.been.calledWithExactly('sha1');
expect(updateStub).to.have.been.calledTwice;
expect(updateStub).to.have.been.calledWithExactly('OpenID|https://login.salesforce.com|4001');
expect(digestStub).to.have.been.calledTwice;
expect(digestStub).to.have.been.calledWithExactly('hex');
expect(openIdClient.OpenIdClient).to.have.been.calledOnce;
expect(openIdClient.OpenIdClient).to.have.been.calledWithNew;
expect(openIdClientStubInstance.init).to.have.been.calledOnce;
expect(openIdClientStubInstance.init).to.have.been.calledWithExactly();
expect(oauth2Client.OAuth2Client).to.not.have.been.called;
expect(oauth2ClientStubInstance.init).to.not.have.been.called;
expect(salesforceClient.SalesforceClient).to.not.have.been.called;
expect(salesforceClientStubInstance.init).to.not.have.been.called;
expect(oauth2JwtClient.OAuth2JWTClient).to.not.have.been.called;
expect(oauth2JwtClientStubInstance.init).to.not.have.been.called;
});
it('use different clients for different environments', async () => {
// Given
digestStub
.onFirstCall().returns('key')
.onSecondCall().returns('key2');
// When
await cache.findOrCreateClient(productionEnv);
await cache.findOrCreateClient(sandboxEnvironment);
// Then
expect(createHashStub).to.have.been.calledTwice;
expect(createHashStub).to.have.been.calledWithExactly('sha1');
expect(updateStub).to.have.been.calledTwice;
expect(updateStub).to.have.been.calledWithExactly('OpenID|https://login.salesforce.com|4001');
expect(updateStub).to.have.been.calledWithExactly('OpenID|https://test.salesforce.com|4001');
expect(digestStub).to.have.been.calledTwice;
expect(digestStub).to.have.been.calledWithExactly('hex');
expect(openIdClient.OpenIdClient).to.have.been.calledTwice;
expect(openIdClient.OpenIdClient).to.have.been.calledWithNew;
expect(openIdClientStubInstance.init).to.have.been.calledTwice;
expect(openIdClientStubInstance.init).to.have.been.calledWithExactly();
expect(oauth2Client.OAuth2Client).to.not.have.been.called;
expect(oauth2ClientStubInstance.init).to.not.have.been.called;
expect(salesforceClient.SalesforceClient).to.not.have.been.called;
expect(salesforceClientStubInstance.init).to.not.have.been.called;
expect(oauth2JwtClient.OAuth2JWTClient).to.not.have.been.called;
expect(oauth2JwtClientStubInstance.init).to.not.have.been.called;
});
});
});
|
financialforcedev/orizuru-auth
|
src/index/middleware/common/fail.ts
|
/*
* Copyright (c) 2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @module middleware/common/fail
*/
import { NextFunction, Request, Response } from '@financialforcedev/orizuru';
import { EVENT_DENIED } from '../../..';
/**
* Helper function for a failed request.
*
* Emits a denied event and calls next with the access denied error.
*
* @fires EVENT_DENIED
* @param app The Orizuru server instance.
* @param error The error that caused the failed request.
* @param req The HTTP request.
* @param res The HTTP response.
* @param next Callback argument to the middleware function.
*/
export function fail(app: Orizuru.IServer, error: Error, req: Request, res: Response, next: NextFunction) {
const message = `Access denied to: ${req.ip ? req.ip : 'unknown'}. Error: ${error.message}`;
const accessDeniedError = new Error(message);
app.emit(EVENT_DENIED, message);
// Rather than returning a 401 directly, we need to call next with the error.
// This should then find the appropriate error handler.
next(accessDeniedError);
}
|
financialforcedev/orizuru-auth
|
test/index/client/openid/jwk.test.ts
|
/*
* Copyright (c) 2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
import sinon from 'sinon';
import sinonChai from 'sinon-chai';
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import { retrieveJsonWebKeysInPemFormat } from '../../../../src/index/client/openid/jwk';
const expect = chai.expect;
chai.use(chaiAsPromised);
chai.use(sinonChai);
describe('index/client/openid/jwk', () => {
let config: AxiosRequestConfig;
beforeEach(() => {
config = {
timeout: 4001,
validateStatus: () => true
};
});
afterEach(() => {
sinon.restore();
});
describe('retrieveJsonWebKeysInPemFormat', () => {
it('should throw an error for a bad request', async () => {
// Given
const response: AxiosResponse = {
config: {},
data: {},
headers: {},
request: {},
status: 400,
statusText: 'Bad Request'
};
sinon.stub(axios, 'get').resolves(response);
// When
// Then
await expect(retrieveJsonWebKeysInPemFormat('https://login.salesforce.com/id/keys', config)).to.be.rejectedWith('Failed to retrieve JWKs');
});
it('should convert a JWK to PEM', async () => {
// Given
const response: AxiosResponse = {
config: {},
data: {
keys: [{
alg: 'RS256',
e: 'AQAB',
kid: '123',
kty: 'RSA',
n: '<KEY>',
use: 'sig'
}]
},
headers: {},
request: {},
status: 200,
statusText: 'OK'
};
sinon.stub(axios, 'get').resolves(response);
// When
const jwks = await retrieveJsonWebKeysInPemFormat('https://login.salesforce.com/id/keys', config);
// Then
expect(jwks).to.have.key('123');
expect(jwks['123'].replace(/\n/g, '')).to.eql('-----BEGIN PUBLIC KEY-----<KEY>');
});
});
});
|
financialforcedev/orizuru-auth
|
test/index.test.ts
|
/*
* Copyright (c) 2017-2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import chai from 'chai';
import * as index from '../src';
const expect = chai.expect;
describe('index', () => {
it('should contain the correct parts', () => {
// Given
// When
// Then
expect(index).to.have.keys([
'EVENT_AUTHORIZATION_HEADER_SET',
'EVENT_DENIED',
'EVENT_GRANT_CHECKED',
'EVENT_TOKEN_INTROSPECTED',
'EVENT_TOKEN_VALIDATED',
'EVENT_USER_IDENTITY_RETRIEVED',
'ResponseFormat',
'flow',
'grant',
'introspection',
'middleware',
'openIdClient',
'revocation',
'userInfo'
]);
expect(index.flow).to.have.keys([
'jwtBearerToken',
'refreshToken',
'webServer'
]);
expect(index.grant).to.have.keys([
'getToken'
]);
expect(index.introspection).to.have.keys([
'createTokenIntrospector'
]);
expect(index.middleware).to.have.keys([
'authCallback',
'grantChecker',
'retrieveIdentityInformation',
'tokenIntrospection',
'tokenValidator'
]);
expect(index.openIdClient).to.have.keys([
'clearCache'
]);
expect(index.revocation).to.have.keys([
'createTokenRevoker'
]);
expect(index.userInfo).to.have.keys([
'createUserInfoRequester'
]);
});
});
|
financialforcedev/orizuru-auth
|
test/index/flow/refreshToken.test.ts
|
/*
* Copyright (c) 2018-2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import chai from 'chai';
import sinon, { SinonStubbedInstance } from 'sinon';
import sinonChai from 'sinon-chai';
import { Environment, RefreshAccessTokenGrantor } from '../../../src';
import { createTokenGrantor } from '../../../src/index//flow/refreshToken';
import * as cache from '../../../src/index/client/cache';
import { OpenIdClient } from '../../../src/index/client/openid';
import * as validator from '../../../src/index/client/validator/environment';
const expect = chai.expect;
chai.use(sinonChai);
describe('index/flow/refreshToken', () => {
let env: Environment;
beforeEach(() => {
env = {
httpTimeout: 4001,
issuerURI: 'https://login.salesforce.com/',
type: 'OpenID'
};
sinon.stub(validator, 'validate').returns(env);
});
afterEach(() => {
sinon.restore();
});
it('should return a function when called with the environment', () => {
// Given
// When
const tokenGrantor = createTokenGrantor(env);
// Then
expect(tokenGrantor).to.be.a('function');
expect(validator.validate).to.have.been.calledOnce;
expect(validator.validate).to.have.been.calledWithExactly(env);
});
describe('requestAccessToken', () => {
let tokenGrantor: RefreshAccessTokenGrantor;
let openIdClientStubInstance: SinonStubbedInstance<OpenIdClient>;
beforeEach(() => {
openIdClientStubInstance = sinon.createStubInstance(OpenIdClient);
sinon.stub(cache, 'findOrCreateClient').resolves(openIdClientStubInstance);
tokenGrantor = createTokenGrantor(env);
});
it('should call the openIdClient grant method with the correct parameters', async () => {
// Given
const expectedAccessTokenResponse = {
access_token: '<KEY>',
id: 'https://login.salesforce.com/id/00Dx0000000BV7z/005x00000012Q9P',
instance_url: 'https://yourInstance.salesforce.com/',
issued_at: '1278448101416',
refresh_token: '<PASSWORD>3JKkDpB4xReb54_pZebnUG0h6Sb4KUVDpNtWEofWM39yg==',
scope: 'id api refresh_token',
signature: 'CMJ4l+CCaPQiKjoOEwEig9H4wqhpuLSk4J2urAe + fVg=',
token_type: 'Bearer'
};
openIdClientStubInstance.grant.resolves(expectedAccessTokenResponse);
// When
const accessTokenResponse = await tokenGrantor({
clientId: 'test',
clientSecret: 'test',
refreshToken: 'token'
}, { signingSecret: 'testSigningSecret' });
// Then
expect(accessTokenResponse).to.eql(expectedAccessTokenResponse);
expect(cache.findOrCreateClient).to.have.been.calledOnce;
expect(cache.findOrCreateClient).to.have.been.calledWithExactly(env);
expect(openIdClientStubInstance.grant).to.have.been.calledOnce;
expect(openIdClientStubInstance.grant).to.have.been.calledWithExactly({
clientId: 'test',
clientSecret: 'test',
grantType: 'refresh_token',
refreshToken: 'token'
}, { signingSecret: 'testSigningSecret' });
});
});
});
|
financialforcedev/orizuru-auth
|
test/index/middleware/identity.test.ts
|
/*
* Copyright (c) 2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import chai from 'chai';
import sinon, { SinonStub } from 'sinon';
import sinonChai from 'sinon-chai';
import { default as axios } from 'axios';
import { Request, RequestHandler, Response } from '@financialforcedev/orizuru';
import { EVENT_USER_IDENTITY_RETRIEVED } from '../../../src';
import * as fail from '../../../src/index/middleware/common/fail';
import { createMiddleware } from '../../../src/index/middleware/identity';
const expect = chai.expect;
const has = sinon.match.has;
chai.use(sinonChai);
describe('index/middleware/identity', () => {
let app: Orizuru.IServer;
beforeEach(() => {
const partialApp: Partial<Orizuru.IServer> = {
emit: sinon.stub()
};
app = partialApp as Orizuru.IServer;
});
afterEach(() => {
sinon.restore();
});
it('should return a function when called with the app', () => {
// Given
// When
const middleware = createMiddleware(app);
// Then
expect(middleware).to.be.a('function');
});
describe('retrieveIdentityInformation', () => {
let middleware: RequestHandler;
let req: Request;
let res: Response;
let next: SinonStub;
beforeEach(() => {
sinon.stub(fail, 'fail');
const partialRequest: Partial<Request> = {
headers: {
authorization: 'Bearer testToken'
},
ip: '1.1.1.1',
orizuru: {
salesforce: {
userInfo: {
url: 'https://login.salesforce.com/id/00Dxx0000001gPLEAY/005xx000001SwiUAAS',
validated: true
}
}
}
};
req = partialRequest as Request;
const partialResponse: Partial<Response> = {};
res = partialResponse as Response;
next = sinon.stub();
middleware = createMiddleware(app);
});
describe('should fail the request', () => {
afterEach(() => {
// Then
expect(fail.fail).to.have.been.calledOnce;
expect(next).to.not.have.been.called;
});
it('if the headers are not provided', async () => {
// Given
delete req.headers;
// When
await middleware(req, res, next);
// Then
expect(fail.fail).to.have.been.calledWithExactly(app, has('message', 'Missing required object parameter: headers.'), req, res, next);
});
it('if the authorization header is not provided', async () => {
// Given
delete req.headers.authorization;
// When
await middleware(req, res, next);
// Then
expect(fail.fail).to.have.been.calledWithExactly(app, has('message', 'Missing required string parameter: headers[authorization].'), req, res, next);
});
it('if the header is empty', async () => {
// Given
req.headers.authorization = '';
// When
await middleware(req, res, next);
// Then
expect(fail.fail).to.have.been.calledWithExactly(app, has('message', 'Missing required string parameter: headers[authorization].'), req, res, next);
});
it('with no bearer', async () => {
// Given
req.headers.authorization = '12345';
// When
await middleware(req, res, next);
// Then
expect(fail.fail).to.have.been.calledWithExactly(app, has('message', 'Authorization header with \'Bearer ***...\' required.'), req, res, next);
});
it('for \'Bearer \'', async () => {
// Given
req.headers.authorization = 'Bearer ';
// When
await middleware(req, res, next);
// Then
expect(fail.fail).to.have.been.calledWithExactly(app, has('message', 'Authorization header with \'Bearer ***...\' required.'), req, res, next);
});
it('if orizuru is not on the request', async () => {
// Given
delete req.orizuru;
// When
await middleware(req, res, next);
// Then
expect(fail.fail).to.have.been.calledWithExactly(app, has('message', 'Missing required object parameter: orizuru.'), req, res, next);
});
it('if the salesforce is not on the request', async () => {
// Given
delete req.orizuru!.salesforce;
// When
await middleware(req, res, next);
// Then
expect(fail.fail).to.have.been.calledWithExactly(app, has('message', 'Missing required object parameter: orizuru[salesforce].'), req, res, next);
});
it('if the salesforce user info is not on the request', async () => {
// Given
delete req.orizuru!.salesforce!.userInfo;
// When
await middleware(req, res, next);
// Then
expect(fail.fail).to.have.been.calledWithExactly(app, has('message', 'Missing required object parameter: orizuru[salesforce][userInfo].'), req, res, next);
});
it('if the salesforce user info url is not on the request', async () => {
// Given
delete req.orizuru!.salesforce!.userInfo!.url;
// When
await middleware(req, res, next);
// Then
expect(fail.fail).to.have.been.calledWithExactly(app, has('message', 'Missing required string parameter: orizuru[salesforce][userInfo][url].'), req, res, next);
});
it('if the salesforce user info validated is not on the request', async () => {
// Given
delete req.orizuru!.salesforce!.userInfo!.validated;
// When
await middleware(req, res, next);
// Then
expect(fail.fail).to.have.been.calledWithExactly(app, has('message', 'Missing required string parameter: orizuru[salesforce][userInfo][validated].'), req, res, next);
});
it('if the salesforce user info validated is false', async () => {
// Given
req.orizuru!.salesforce!.userInfo!.validated = false;
// When
await middleware(req, res, next);
// Then
expect(fail.fail).to.have.been.calledWithExactly(app, has('message', 'The Identity URL must be validated.'), req, res, next);
});
it('if api call fails', async () => {
// Given
sinon.stub(axios, 'get').rejects(new Error('Failed to retrieve user information.'));
// When
await middleware(req, res, next);
// Then
expect(fail.fail).to.have.been.calledWithExactly(app, has('message', 'Failed to retrieve user information.'), req, res, next);
expect(axios.get).to.have.been.calledOnce;
expect(axios.get).to.have.been.calledWithExactly('https://login.salesforce.com/id/00Dxx0000001gPLEAY/005xx000001SwiUAAS', {
headers: {
Authorization: 'Bearer testToken'
}
});
});
});
describe('should call next if the code is exchanged for an access token', () => {
it('and update the request authorization header and orizuru identity property', async () => {
// Given
sinon.stub(axios, 'get').resolves({
config: {},
data: {
id: 'https://login.salesforce.com/id/00Dxx0000001gPLEAY/005xx000001SwiUAAS',
organization_id: '00Dxx0000001gPLEAY',
user_id: '005xx000001SwiUAAS',
username: '<EMAIL>'
},
headers: {},
status: 200,
statusText: 'OK'
});
// When
await middleware(req, res, next);
// Then
expect(req).to.have.property('orizuru');
expect(req.orizuru).to.have.property('salesforce');
expect(req.orizuru!.salesforce).to.have.property('userInfo').that.eqls({
url: 'https://login.salesforce.com/id/00Dxx0000001gPLEAY/005xx000001SwiUAAS',
validated: true
});
expect(req.orizuru).to.have.property('salesforce').to.have.property('identity').that.eqls({
id: 'https://login.salesforce.com/id/00Dxx0000001gPLEAY/005xx000001SwiUAAS',
organization_id: '00Dxx0000001gPLEAY',
user_id: '005xx000001SwiUAAS',
username: '<EMAIL>'
});
expect(axios.get).to.have.been.calledOnce;
expect(axios.get).to.have.been.calledWithExactly('https://login.salesforce.com/id/00Dxx0000001gPLEAY/005xx000001SwiUAAS', {
headers: {
Authorization: 'Bearer testToken'
}
});
expect(app.emit).to.have.been.calledOnce;
expect(app.emit).to.have.been.calledWithExactly(EVENT_USER_IDENTITY_RETRIEVED, 'Identity information retrieved for user (<EMAIL>) [1.1.1.1].');
expect(next).to.have.been.calledOnce;
expect(next).to.have.been.calledWithExactly();
});
});
});
});
|
financialforcedev/orizuru-auth
|
src/index/client/oauth2Jwt/jwt.ts
|
<reponame>financialforcedev/orizuru-auth
/*
* Copyright (c) 2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @module client/oauth2Jwt/jwt
*/
import { Secret, sign } from 'jsonwebtoken';
import { v4 as uuid } from 'uuid';
import { Environment } from '../cache';
import { GrantParams } from '../oauth2';
import { JWT, JwtGrantParams } from '../oauth2Jwt';
/**
* The assertion types that can be created.
*/
enum AssertionType {
CLIENT = 'client',
GRANT = 'grant'
}
/**
* Creates a [private_key_jwt](https://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication) assertion for use in the authentication process.
*
* @param params The parameters required for either the [auth](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest) or [refresh](https://openid.net/specs/openid-connect-core-1_0.html#RefreshingAccessToken) grant requests.
* @param signingSecret The secret used to sign the payload.
* @param tokenEndpoint The [OpenID token endpoint](https://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint).
*/
export async function createJwtBearerClientAssertion(params: GrantParams, signingSecret: Secret, tokenEndpoint: string) {
const payload = createPayload(tokenEndpoint, params.clientId, params.clientId);
return signClientAssertion(payload, signingSecret, AssertionType.CLIENT);
}
/**
* Creates a [private_key_jwt](https://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication) assertion for use in the authentication process.
*
* Unlike the standard client assertion, this assertion provides the username as the
* subject as defined by [Salesforce](https://help.salesforce.com/articleView?id=remoteaccess_oauth_jwt_flow.htm#create_token).
*
* @param env The auth environment parameters.
* @param params The parameters required for the [JWT Bearer](https://help.salesforce.com/articleView?id=remoteaccess_oauth_jwt_flow.htm) grant request.
* @param user The user to generate the assertion for.
*/
export async function createJwtBearerGrantAssertion(env: Environment, params: JwtGrantParams) {
const payload = createPayload(env.issuerURI, params.clientId, params.user.username);
return signClientAssertion(payload, params.signingSecret, AssertionType.GRANT);
}
/**
* Create the JWT payload.
*
* @param aud Audience(s) that this ID Token is intended for.
* @param iss Issuer.
* @param sub Subject identifier.
*/
function createPayload(aud: string, iss: string, sub: string): JWT {
const iat = Math.floor(Date.now() / 1000);
const exp = iat + (60 * 4);
return {
aud,
exp,
iat,
iss,
jti: uuid().toString(),
sub
};
}
/**
* Sign the payload using the given private key.
*
* @param payload The payload to sign.
* @param signingSecret The private key to sign the payload with.
* @param type The assertion type (either client or grant).
*/
function signClientAssertion(payload: JWT, signingSecret: Secret, type: AssertionType) {
return new Promise<string>((resolve, reject) => {
sign(payload, signingSecret, { algorithm: 'RS256' }, (err, encoded) => {
if (err) {
reject(new Error(`Failed to sign ${type} assertion.`));
} else {
resolve(encoded);
}
});
});
}
|
financialforcedev/orizuru-auth
|
test/index/middleware/common/accessToken.test.ts
|
<gh_stars>1-10
/*
* Copyright (c) 2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import chai from 'chai';
import { Request } from '@financialforcedev/orizuru';
import { extractAccessToken, setAccessTokenOnRequest } from '../../../../src/index/middleware/common/accessToken';
const expect = chai.expect;
describe('index/middleware/common/accessToken', () => {
let req: Request;
beforeEach(() => {
const partialRequest: Partial<Request> = {
ip: '1.1.1.1'
};
req = partialRequest as Request;
});
describe('extractAccessToken', () => {
it('should extract the access token from the request', () => {
// Given
req.headers = {
authorization: 'Bearer 12345'
};
// When
const accessToken = extractAccessToken(req);
// Then
expect(accessToken).to.eql(accessToken);
});
describe('should fail the request', () => {
it('if the headers are not provided', () => {
// Given
// When
// Then
expect(() => extractAccessToken(req)).to.throw('Missing required object parameter: headers.');
});
it('if the authorization header is not provided', async () => {
// Given
req.headers = {};
// When
// Then
expect(() => extractAccessToken(req)).to.throw('Missing required string parameter: headers[authorization].');
});
it('if the header is empty', async () => {
// Given
req.headers = {
authorization: ''
};
// When
// Then
expect(() => extractAccessToken(req)).to.throw('Missing required string parameter: headers[authorization].');
});
it('with no bearer', async () => {
// Given
req.headers = {
authorization: '12345'
};
// When
// Then
expect(() => extractAccessToken(req)).to.throw('Authorization header with \'Bearer ***...\' required.');
});
it('for \'Bearer \'', async () => {
// Given
req.headers = {
authorization: 'Bearer '
};
// When
// Then
expect(() => extractAccessToken(req)).to.throw('Authorization header with \'Bearer ***...\' required.');
});
});
});
describe('setAccessTokenOnRequest', () => {
describe('should do nothing', () => {
it('if setTokenOnContext is undefined', () => {
// Given
// When
setAccessTokenOnRequest(req, 'token');
// Then
expect(req).to.not.have.property('orizuru');
});
it('if setTokenOnContext is false', () => {
// Given
// When
setAccessTokenOnRequest(req, 'token', false);
// Then
expect(req).to.not.have.property('orizuru');
});
});
describe('should add the token to the context', () => {
it('if setTokenOnContext is true', () => {
// Given
// When
setAccessTokenOnRequest(req, 'token', true);
// Then
expect(req).to.have.property('orizuru');
expect(req.orizuru).to.have.property('accessToken', 'token');
});
it('if setTokenOnContext is true respecting an existing orizuru property', () => {
// Given
req.orizuru = {
grantChecked: true
};
// When
setAccessTokenOnRequest(req, 'token', true);
// Then
expect(req).to.have.property('orizuru');
expect(req.orizuru).to.have.property('accessToken', 'token');
expect(req.orizuru).to.have.property('grantChecked', true);
});
});
});
});
|
financialforcedev/orizuru-auth
|
examples/src/index.ts
|
<gh_stars>1-10
/*
* Copyright (c) 2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import { json, NextFunction, Request, Response, Server } from '@financialforcedev/orizuru';
import { flow } from '@financialforcedev/orizuru-auth';
import { Transport } from '@financialforcedev/orizuru-transport-rabbitmq';
import config from 'config';
import https from 'https';
import pem, { CertificateCreationResult } from 'pem';
// Define a function that creates a self-signed certificate
function createCertificate(): Promise<CertificateCreationResult> {
return new Promise((resolve, reject) => {
pem.createCertificate({ days: 1, selfSigned: true }, (err, result) => {
if (err) {
return reject(err);
}
process.stdout.write('Created certificate\n');
return resolve(result);
});
});
}
// Define a simple error middleware
const errorMiddleware = (error: Error | undefined, req: Request, res: Response, next: NextFunction) => {
if (error) {
server.error(error);
res.sendStatus(401);
} else {
next();
}
};
// Create the server
const server = new Server({
authProvider: {
salesforce: config.get('app.authProvider.salesforce')
},
openid: {
salesforce: config.get('app.openid.salesforce'),
salesforceConnection: config.get('app.openid.salesforceConnection')
},
port: 8080,
transport: new Transport({
prefetch: 1,
url: 'amqp://localhost'
})
});
// Add listeners for the server error and info events
server.on(Server.ERROR, (message) => {
process.stdout.write(`${message}\n`);
});
server.on(Server.INFO, (message) => {
process.stdout.write(`${message}\n`);
});
// Add the route to generate the authorization URL (in this case we use 'test' as the state parameter)
server.addRoute({
method: 'get',
middleware: [
json(),
errorMiddleware
],
responseWriter: () => async (err: Error | undefined, req: Request, res: Response) => {
const url = await flow.webServer.authorizationUrlGenerator(server.options.authProvider.salesforce)(server.options.openid.salesforce, server.options.openid.salesforce);
res.redirect(url);
},
schema: {
fields: [],
name: 'auth',
namespace: 'api.v1_0',
type: 'record'
},
synchronous: true
});
// **All code specified in the rest of the readme should be added here**
// Create a self-signed certificate and then start the server listening to connections using HTTPS
createCertificate().then((certificate) => {
const serverOptions: https.ServerOptions = {
cert: certificate.certificate,
key: certificate.clientKey
};
const httpsServer = https.createServer(serverOptions, server.serverImpl);
httpsServer.listen(server.options.port);
process.stdout.write('Started server\n');
});
|
financialforcedev/orizuru-auth
|
test/index/client/oauth2Jwt/jwt.test.ts
|
/*
* Copyright (c) 2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
import sinon, { SinonStub } from 'sinon';
import sinonChai from 'sinon-chai';
import { default as jsonwebtoken, Secret, SignCallback, SignOptions } from 'jsonwebtoken';
import { default as uuid } from 'uuid';
import { AuthCodeGrantParams, Environment, JwtGrantParams } from '../../../../src';
import { createJwtBearerClientAssertion, createJwtBearerGrantAssertion } from '../../../../src/index/client/oauth2Jwt/jwt';
const expect = chai.expect;
chai.use(chaiAsPromised);
chai.use(sinonChai);
describe('index/client/oauth2Jwt/jwt', () => {
let env: Environment;
let jwtSignStub: SinonStub<[string | object | Buffer, Secret, SignOptions, SignCallback], void>;
beforeEach(() => {
env = {
httpTimeout: 4001,
issuerURI: 'https://login.salesforce.com/',
type: 'OpenID'
};
sinon.stub(Date, 'now').returns(1551521526000);
sinon.stub(uuid, 'v4').returns('579504df-90f7-49d0-af46-647980eeb22c');
jwtSignStub = sinon.stub(jsonwebtoken, 'sign');
});
afterEach(() => {
sinon.restore();
});
describe('createJwtBearerClientAssertion', () => {
let params: AuthCodeGrantParams;
beforeEach(() => {
params = {
clientId: 'testOpenidClientId',
code: 'testCode',
grantType: 'authorization_code'
};
});
describe('should throw an error', () => {
it('if the client assertion cannot be signed', async () => {
// Given
jwtSignStub.yields(new Error('error'));
// When
await expect(createJwtBearerClientAssertion(params, 'testSigningSecret', 'https://login.salesforce.com/services/oauth2/token')).to.eventually.be.rejectedWith('Failed to sign client assertion.');
// Then
expect(jsonwebtoken.sign).to.have.been.calledOnce;
expect(jsonwebtoken.sign).to.have.been.calledWith({
aud: 'https://login.salesforce.com/services/oauth2/token',
exp: 1551521766,
iat: 1551521526,
iss: 'testOpenidClientId',
jti: '579504df-90f7-49d0-af46-647980eeb22c',
sub: 'testOpenidClientId'
}, 'testSigningSecret', { algorithm: 'RS256' }, sinon.match.func);
});
it('should return the signed client assertion', async () => {
// Given
jwtSignStub.yields(undefined, 'signed');
// When
const result = await createJwtBearerClientAssertion(params, 'testSigningSecret', 'https://login.salesforce.com/services/oauth2/token');
// Then
expect(result).to.eql('signed');
expect(jsonwebtoken.sign).to.have.been.calledOnce;
expect(jsonwebtoken.sign).to.have.been.calledWith({
aud: 'https://login.salesforce.com/services/oauth2/token',
exp: 1551521766,
iat: 1551521526,
iss: 'testOpenidClientId',
jti: '579504df-90f7-49d0-af46-647980eeb22c',
sub: 'testOpenidClientId'
}, 'testSigningSecret', { algorithm: 'RS256' }, sinon.match.func);
});
});
});
describe('createJwtBearerGrantAssertion', () => {
let params: JwtGrantParams;
beforeEach(() => {
params = {
clientId: 'testOpenidClientId',
grantType: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
signingSecret: 'testSigningSecret',
user: {
username: '<EMAIL>'
}
};
});
describe('should throw an error', () => {
it('if the grant assertion cannot be signed', async () => {
// Given
jwtSignStub.yields(new Error('error'));
// When
await expect(createJwtBearerGrantAssertion(env, params)).to.eventually.be.rejectedWith('Failed to sign grant assertion.');
// Then
expect(jsonwebtoken.sign).to.have.been.calledOnce;
expect(jsonwebtoken.sign).to.have.been.calledWith({
aud: 'https://login.salesforce.com/',
exp: 1551521766,
iat: 1551521526,
iss: 'testOpenidClientId',
jti: '579504df-90f7-49d0-af46-647980eeb22c',
sub: '<EMAIL>'
}, 'testSigningSecret', { algorithm: 'RS256' }, sinon.match.func);
});
it('should return the signed grant assertion', async () => {
// Given
jwtSignStub.yields(undefined, 'signed');
// When
const result = await createJwtBearerGrantAssertion(env, params);
// Then
expect(result).to.eql('signed');
expect(jsonwebtoken.sign).to.have.been.calledOnce;
expect(jsonwebtoken.sign).to.have.been.calledWith({
aud: 'https://login.salesforce.com/',
exp: 1551521766,
iat: 1551521526,
iss: 'testOpenidClientId',
jti: '579504df-90f7-49d0-af46-647980eeb22c',
sub: '<EMAIL>'
}, 'testSigningSecret', { algorithm: 'RS256' }, sinon.match.func);
});
});
});
});
|
financialforcedev/orizuru-auth
|
test/index/middleware/tokenValidator.test.ts
|
<gh_stars>1-10
/*
* Copyright (c) 2017-2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import chai from 'chai';
import sinon, { SinonStub } from 'sinon';
import sinonChai from 'sinon-chai';
import { Request, RequestHandler, Response } from '@financialforcedev/orizuru';
import { Environment, EVENT_TOKEN_VALIDATED, OpenIdOptions, ResponseFormat, UserInfoOptions } from '../../../src';
import * as accessToken from '../../../src/index/middleware/common/accessToken';
import * as fail from '../../../src/index/middleware/common/fail';
import * as userInfo from '../../../src/index/userInfo/userinfo';
import { createMiddleware } from '../../../src/index/middleware/tokenValidator';
const expect = chai.expect;
const has = sinon.match.has;
chai.use(sinonChai);
describe('index/middleware/tokenValidator', () => {
let app: Orizuru.IServer;
let env: Environment;
let requestUserInfoStub: SinonStub;
beforeEach(() => {
env = {
httpTimeout: 4001,
issuerURI: 'https://login.salesforce.com/',
type: 'OpenID'
};
const openIdOptions: Partial<OpenIdOptions> = {
clientId: 'testClientId',
clientSecret: 'testClientSecret',
signingSecret: 'testSigningSecret'
};
const partialApp: Partial<Orizuru.IServer> = {
emit: sinon.stub(),
options: {
authProvider: {
salesforce: env
},
openid: {
salesforce: openIdOptions as OpenIdOptions
}
}
};
app = partialApp as Orizuru.IServer;
requestUserInfoStub = sinon.stub();
sinon.stub(userInfo, 'createUserInfoRequester').returns(requestUserInfoStub);
sinon.stub(accessToken, 'extractAccessToken').returns('12345');
sinon.stub(fail, 'fail');
});
afterEach(() => {
// Then
expect(userInfo.createUserInfoRequester).to.have.been.calledOnce;
expect(userInfo.createUserInfoRequester).to.have.been.calledWithExactly(app.options.authProvider.salesforce);
sinon.restore();
});
it('should return a function when called with the app', () => {
// Given
// When
const middleware = createMiddleware(app);
// Then
expect(middleware).to.be.a('function');
});
describe('validateToken', () => {
let middleware: RequestHandler;
let req: Request;
let res: Response;
let next: SinonStub;
beforeEach(() => {
const partialRequest: Partial<Request> = {
ip: '1.1.1.1'
};
req = partialRequest as Request;
const partialResponse: Partial<Response> = {};
res = partialResponse as Response;
next = sinon.stub();
const opts: UserInfoOptions = {
responseFormat: ResponseFormat.JSON
};
middleware = createMiddleware(app, 'salesforce', opts);
});
describe('should fail the request', () => {
afterEach(() => {
// Then
expect(fail.fail).to.have.been.calledOnce;
expect(next).to.not.have.been.called;
});
it('if validateAccessToken rejects', async () => {
// Given
req.headers = {
authorization: 'Bearer 12345'
};
requestUserInfoStub.rejects(new Error('Failed to retrieve user information.'));
// When
await middleware(req, res, next);
// Then
expect(fail.fail).to.have.been.calledWithExactly(app, has('message', 'Failed to retrieve user information.'), req, res, next);
expect(requestUserInfoStub).to.have.been.calledOnce;
expect(requestUserInfoStub).to.have.been.calledWithExactly('12345', {
responseFormat: ResponseFormat.JSON
});
});
});
describe('should call next if the token is validated', () => {
beforeEach(() => {
req.headers = {
authorization: 'Bearer 12345'
};
requestUserInfoStub.resolves({
preferred_username: '<EMAIL>'
});
});
afterEach(() => {
// Then
expect(requestUserInfoStub).to.have.been.calledOnce;
expect(app.emit).to.have.been.calledOnce;
expect(app.emit).to.have.been.calledWithExactly(EVENT_TOKEN_VALIDATED, 'Token validated for user (<EMAIL>) [1.1.1.1].');
expect(next).to.have.been.calledOnce;
expect(next).to.have.been.calledWithExactly();
});
it('and set orizuru on the request', async () => {
// Given
// When
await middleware(req, res, next);
// Then
expect(req.orizuru).to.have.property('user').that.eqls({
username: '<EMAIL>'
});
expect(requestUserInfoStub).to.have.been.calledWithExactly('12345', {
responseFormat: ResponseFormat.JSON
});
expect(req.orizuru).to.not.have.property('accessToken');
});
it('adding the orizuru access token property for a salesforce access token', async () => {
// Given
sinon.resetHistory();
middleware = createMiddleware(app, 'salesforce', {
responseFormat: ResponseFormat.JSON,
setTokenOnContext: true
});
// When
await middleware(req, res, next);
// Then
expect(req.headers).to.have.property('authorization', 'Bearer 12345');
expect(req).to.have.property('orizuru');
expect(req.orizuru).to.have.property('accessToken', '12345');
expect(req.orizuru).to.have.property('user').that.eqls({
username: '<EMAIL>'
});
expect(requestUserInfoStub).to.have.been.calledWithExactly('12345', {
responseFormat: ResponseFormat.JSON
});
});
it('and respect an existing orizuru object', async () => {
// Given
req.orizuru = {
grantChecked: true
};
// When
await middleware(req, res, next);
// Then
expect(req.orizuru).to.have.property('grantChecked', true);
expect(requestUserInfoStub).to.have.been.calledWithExactly('12345', {
responseFormat: ResponseFormat.JSON
});
});
it('and set organization id on the request if available', async () => {
// Given
requestUserInfoStub.resolves({
organization_id: 'orgid',
preferred_username: '<EMAIL>'
});
// When
await middleware(req, res, next);
// Then
expect(req.orizuru).to.have.property('user').that.eqls({
organizationId: 'orgid',
username: '<EMAIL>'
});
expect(requestUserInfoStub).to.have.been.calledWithExactly('12345', {
responseFormat: ResponseFormat.JSON
});
expect(req.orizuru).to.not.have.property('salesforce');
});
it('and set the instance url on the request if available', async () => {
// Given
requestUserInfoStub.resolves({
organization_id: 'orgid',
preferred_username: '<EMAIL>',
urls: {
enterprise: '',
rest: 'https://yourInstance.salesforce.com/services/data/v{version}/',
sobjects: 'https://yourInstance.salesforce.com/services/data/v{version}/sobjects/'
}
});
// When
await middleware(req, res, next);
// Then
expect(req.orizuru).to.have.property('salesforce').that.has.property('instanceUrl', 'https://yourInstance.salesforce.com');
expect(req.orizuru).to.have.property('user').that.eqls({
organizationId: 'orgid',
username: '<EMAIL>'
});
expect(requestUserInfoStub).to.have.been.calledWithExactly('12345', {
responseFormat: ResponseFormat.JSON
});
});
it('and not set the instance URL if none of the urls match the regex', async () => {
// Given
requestUserInfoStub.resolves({
organization_id: 'orgid',
preferred_username: '<EMAIL>',
urls: {
enterprise: 'enterprise',
rest: 'rest',
sobjects: 'sobjects'
}
});
// When
await middleware(req, res, next);
// Then
expect(req.orizuru).to.have.property('user').that.eqls({
organizationId: 'orgid',
username: '<EMAIL>'
});
expect(requestUserInfoStub).to.have.been.calledWithExactly('12345', {
responseFormat: ResponseFormat.JSON
});
expect(req.orizuru).to.have.property('salesforce').that.does.not.have.property('instanceUrl');
});
});
});
});
|
financialforcedev/orizuru-auth
|
test/index/client/oauth2Jwt.test.ts
|
/*
* Copyright (c) 2019, FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
import sinon, { SinonStub } from 'sinon';
import sinonChai from 'sinon-chai';
import { AxiosRequestConfig, AxiosResponse, default as axios } from 'axios';
import { AuthCodeGrantParams, AuthOptions, AuthUrlParams, Environment, GrantOptions, RefreshGrantParams } from '../../../src';
import * as jwt from '../../../src/index/client/oauth2Jwt/jwt';
import { JwtGrantParams, OAuth2JWTClient } from '../../../src/index/client/oauth2Jwt';
const expect = chai.expect;
chai.use(chaiAsPromised);
chai.use(sinonChai);
describe('index/client/oauth2Jwt', () => {
let env: Environment;
let client: OAuth2JWTClient;
let axiosGetStub: SinonStub<[string, (AxiosRequestConfig | undefined)?]>;
beforeEach(() => {
env = {
authorizationEndpoint: 'https://login.salesforce.com/services/oauth2/authorize',
httpTimeout: 4001,
issuerURI: 'https://login.salesforce.com',
revocationEndpoint: 'https://login.salesforce.com/services/oauth2/revoke',
tokenEndpoint: 'https://login.salesforce.com/services/oauth2/token',
type: 'OAuth2JWT'
};
client = new OAuth2JWTClient(env);
axiosGetStub = sinon.stub(axios, 'get');
});
afterEach(() => {
sinon.restore();
});
describe('createAuthorizationUrl', () => {
let params: AuthUrlParams;
beforeEach(() => {
params = {
clientId: 'testClientId',
redirectUri: 'https://test.app.com/auth/callback',
scope: 'api'
};
});
describe('should throw an error', () => {
it('if the client has not been initialised', () => {
// Given
// When
// Then
expect(() => client.createAuthorizationUrl(params)).to.throw('OAuth2JWT client has not been initialized');
});
it('if the clientId has not been provided', async () => {
// Given
delete params.clientId;
client = new OAuth2JWTClient(env);
await client.init();
// When
// Then
expect(() => client.createAuthorizationUrl(params)).to.throw('Missing required string parameter: clientId');
});
it('if the redirectUri has not been provided', async () => {
// Given
delete params.redirectUri;
client = new OAuth2JWTClient(env);
await client.init();
// When
// Then
expect(() => client.createAuthorizationUrl(params)).to.throw('Missing required string parameter: redirectUri');
});
});
it('should return an authorization url excluding the state', async () => {
// Given
await client.init();
// When
const authorizationUrl = client.createAuthorizationUrl(params);
// Then
expect(authorizationUrl).to.eql('https://login.salesforce.com/services/oauth2/authorize?client_id=testClientId&redirect_uri=https%3A%2F%2Ftest.app.com%2Fauth%2Fcallback&response_type=code&scope=api');
});
it('should return an authorization url including the state', async () => {
// Given
await client.init();
const opts: AuthOptions = {
state: 'testState'
};
// When
const authorizationUrl = client.createAuthorizationUrl(params, opts);
// Then
expect(authorizationUrl).to.eql('https://login.salesforce.com/services/oauth2/authorize?client_id=testClientId&redirect_uri=https%3A%2F%2Ftest.app.com%2Fauth%2Fcallback&response_type=code&scope=api&state=testState');
});
it('should handle spaces in the scopes parameter', async () => {
// Given
await client.init();
params.scope = 'api id';
// When
const authorizationUrl = client.createAuthorizationUrl(params);
// Then
expect(authorizationUrl).to.eql('https://login.salesforce.com/services/oauth2/authorize?client_id=testClientId&redirect_uri=https%3A%2F%2Ftest.app.com%2Fauth%2Fcallback&response_type=code&scope=api%20id');
});
});
describe('getType', () => {
it('should return the type', () => {
// Given
// When
const type = client.getType();
// Then
expect(type).to.eql('OAuth2JWT');
});
});
describe('grant', () => {
let postResponse: AxiosResponse;
beforeEach(() => {
postResponse = {
config: {},
data: {
access_token: '2YotnFZFEjr1zCsicMWpAA',
expires_in: 3600,
refresh_token: '<PASSWORD>',
token_type: 'Bearer'
},
headers: {},
status: 200,
statusText: 'OK'
};
sinon.stub(axios, 'post').resolves(postResponse);
});
describe('should throw an error', () => {
describe('if the grant_type is authorization code', () => {
let params: AuthCodeGrantParams;
beforeEach(() => {
params = {
clientId: 'testClientId',
code: 'testCode',
grantType: 'authorization_code'
};
});
it('and the client has not been initialised', async () => {
// Given
// When
// Then
await expect(client.grant(params)).to.eventually.be.rejectedWith('OAuth2JWT client has not been initialized');
});
it('the client secret is being used and the clientId is not provided', async () => {
// Given
await client.init();
delete params.clientId;
// When
// Then
await expect(client.grant(params)).to.eventually.be.rejectedWith('Missing required string parameter: clientId');
});
it('the client secret is being used and the client_secret is not provided', async () => {
// Given
await client.init();
// When
// Then
await expect(client.grant(params)).to.eventually.be.rejectedWith('Missing required string parameter: clientSecret');
});
it('and no code is provided', async () => {
// Given
delete params.code;
await client.init();
// When
// Then
await expect(client.grant(params)).to.eventually.be.rejectedWith('Missing required string parameter: code');
});
});
describe('if the grant_type is jwt bearer', () => {
let params: JwtGrantParams;
beforeEach(() => {
params = {
clientId: 'testClientId',
grantType: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
signingSecret: 'testSigningSecret',
user: {
username: '<EMAIL>'
}
};
});
it('and the user is not provided', async () => {
// Given
delete params.signingSecret;
await client.init();
sinon.stub(jwt, 'createJwtBearerGrantAssertion');
// When
// Then
await expect(client.grant(params)).to.eventually.be.rejectedWith('Missing required object parameter: signingSecret.');
expect(jwt.createJwtBearerGrantAssertion).to.not.have.been.called;
});
it('and the user is not provided', async () => {
// Given
delete params.user;
await client.init();
sinon.stub(jwt, 'createJwtBearerGrantAssertion');
// When
// Then
await expect(client.grant(params)).to.eventually.be.rejectedWith('Missing required object parameter: user.');
expect(jwt.createJwtBearerGrantAssertion).to.not.have.been.called;
});
it('and creating the grant assertion fails', async () => {
// Given
await client.init();
sinon.stub(jwt, 'createJwtBearerGrantAssertion').rejects(new Error('Failed to sign grant assertion'));
// When
// Then
await expect(client.grant(params)).to.eventually.be.rejectedWith('Failed to sign grant assertion');
expect(jwt.createJwtBearerGrantAssertion).to.have.been.calledOnce;
expect(jwt.createJwtBearerGrantAssertion).to.have.been.calledWithExactly(env, {
clientId: 'testClientId',
grantType: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
signingSecret: 'testSigningSecret',
user: {
username: '<EMAIL>'
}
});
});
it('if the request fails', async () => {
// Given
await client.init();
sinon.stub(jwt, 'createJwtBearerGrantAssertion').resolves('signed');
postResponse.data = {
error: 'invalid_client_id',
error_description: 'client identifier invalid'
};
postResponse.status = 400;
postResponse.statusText = 'BadRequest';
// When
await expect(client.grant(params)).to.eventually.be.rejectedWith('Failed to obtain grant: invalid_client_id (client identifier invalid).');
// Then
expect(jwt.createJwtBearerGrantAssertion).to.have.been.calledOnce;
expect(jwt.createJwtBearerGrantAssertion).to.have.been.calledWithExactly(env, {
clientId: 'testClientId',
grantType: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
signingSecret: 'testSigningSecret',
user: {
username: '<EMAIL>'
}
});
expect(axios.post).to.have.been.calledOnce;
expect(axios.post).to.have.been.calledWithExactly('https://login.salesforce.com/services/oauth2/token', 'assertion=signed&grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
validateStatus: sinon.match.func
});
});
});
describe('if the grant_type is refresh token', () => {
let params: RefreshGrantParams;
beforeEach(() => {
params = {
clientId: 'testClientId',
grantType: 'refresh_token',
refreshToken: 'testRefreshToken'
};
});
it('and no refresh token is provided', async () => {
// Given
delete params.refreshToken;
await client.init();
// When
// Then
await expect(client.grant(params)).to.eventually.be.rejectedWith('Missing required string parameter: refreshToken');
});
});
});
describe('should return the access token response', () => {
describe('if the grant_type is authorization code', () => {
let params: AuthCodeGrantParams;
beforeEach(() => {
params = {
clientId: 'testClientId',
code: 'testCode',
grantType: 'authorization_code'
};
});
it('and the flow is using the client secret', async () => {
// Given
await client.init();
const opts: GrantOptions = {
clientSecret: 'testClientSecret',
redirectUri: 'https://test.app.com/auth/callback'
};
// When
await client.grant(params, opts);
// Then
expect(axios.post).to.have.been.calledOnce;
expect(axios.post).to.have.been.calledWithExactly('https://login.salesforce.com/services/oauth2/token', 'client_id=testClientId&client_secret=testClientSecret&code=testCode&grant_type=authorization_code&redirect_uri=https%3A%2F%2Ftest.app.com%2Fauth%2Fcallback', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
validateStatus: sinon.match.func
});
});
});
describe('if the grant_type is refresh token', () => {
let params: RefreshGrantParams;
beforeEach(() => {
params = {
clientId: 'testClientId',
grantType: 'refresh_token',
refreshToken: '<PASSWORD>'
};
});
it('and the flow is using the client secret', async () => {
// Given
await client.init();
const opts: GrantOptions = {
clientSecret: 'testClientSecret',
redirectUri: 'https://test.app.com/auth/callback'
};
// When
await client.grant(params, opts);
// Then
expect(axios.post).to.have.been.calledOnce;
expect(axios.post).to.have.been.calledWithExactly('https://login.salesforce.com/services/oauth2/token', 'client_id=testClientId&client_secret=testClientSecret&grant_type=refresh_token&refresh_token=<PASSWORD>RefreshToken', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
validateStatus: sinon.match.func
});
});
});
});
});
describe('init', () => {
describe('should throw an error', () => {
it('if the authorizationEndpoint is not provided', async () => {
// Given
delete env.authorizationEndpoint;
client = new OAuth2JWTClient(env);
// When
// Then
await expect(client.init()).to.eventually.be.rejectedWith('Missing required string parameter: env[authorizationEndpoint]');
});
it('if the revocationEndpoint is not provided', async () => {
// Given
delete env.revocationEndpoint;
client = new OAuth2JWTClient(env);
// When
// Then
await expect(client.init()).to.eventually.be.rejectedWith('Missing required string parameter: env[revocationEndpoint]');
});
it('if the tokenEndpoint is not provided', async () => {
// Given
delete env.tokenEndpoint;
client = new OAuth2JWTClient(env);
// When
// Then
await expect(client.init()).to.eventually.be.rejectedWith('Missing required string parameter: env[tokenEndpoint]');
});
});
});
describe('revoke', () => {
it('should throw an error if the client has not been initialised', async () => {
// Given
// When
// Then
await expect(client.revoke('testToken')).to.eventually.be.rejectedWith('OAuth2JWT client has not been initialized');
});
it('should revoke the given token using the post method by default', async () => {
// Given
await client.init();
sinon.stub(axios, 'post').resolves({
config: {},
data: {},
headers: {},
status: 200,
statusText: 'OK'
});
// When
const result = await client.revoke('testToken');
// Then
expect(result).to.be.true;
expect(axios.post).to.have.been.calledOnce;
expect(axios.post).to.have.been.calledWithExactly('https://login.salesforce.com/services/oauth2/revoke', 'token=testToken', {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
validateStatus: sinon.match.func
});
});
it('should revoke the given token using the get method if the options set useGet to true', async () => {
// Given
await client.init();
axiosGetStub.withArgs('https://login.salesforce.com/services/oauth2/revoke?token=testToken').resolves({
config: {},
data: {},
headers: {},
status: 200,
statusText: 'OK'
});
// When
const result = await client.revoke('testToken', { useGet: true });
// Then
expect(result).to.be.true;
expect(axios.get).to.have.been.calledOnce;
expect(axios.get).to.have.been.calledWithExactly('https://login.salesforce.com/services/oauth2/revoke?token=testToken', {
validateStatus: sinon.match.func
});
});
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.