Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ability to test OAuthPrompt and mock OAuth APIs #759

Merged
merged 2 commits into from
Feb 7, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions libraries/botbuilder-core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,4 @@ export * from './testAdapter';
export * from './transcriptLogger';
export * from './turnContext';
export * from './userState';
export * from './userTokenProvider';
138 changes: 136 additions & 2 deletions libraries/botbuilder-core/src/testAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@
*/
// tslint:disable-next-line:no-require-imports
import assert = require('assert');
import { Activity, ActivityTypes, ConversationReference, ResourceResponse } from 'botframework-schema';
import { Activity, ActivityTypes, ConversationReference, ResourceResponse, TokenResponse } from 'botframework-schema';
import { BotAdapter } from './botAdapter';
import { TurnContext } from './turnContext';
import { IUserTokenProvider } from './userTokenProvider';

/**
* Signature for a function that can be used to inspect individual activities returned by a bot
Expand Down Expand Up @@ -41,7 +42,7 @@ export type TestActivityInspector = (activity: Partial<Activity>, description: s
* .then(() => done());
* ```
*/
export class TestAdapter extends BotAdapter {
export class TestAdapter extends BotAdapter implements IUserTokenProvider {
/**
* @private
* INTERNAL: used to drive the promise chain forward when running tests.
Expand Down Expand Up @@ -265,6 +266,120 @@ export class TestAdapter extends BotAdapter {
new TestFlow(Promise.resolve(), this));
}

private _userTokens: UserToken[] = [];
private _magicCodes: TokenMagicCode[] = [];

/**
* Adds a fake user token so it can later be retrieved.
* @param connectionName The connection name.
* @param channelId The channel id.
* @param userId The user id.
* @param token The token to store.
* @param magicCode (Optional) The optional magic code to associate with this token.
*/
public addUserToken(connectionName: string, channelId: string, userId: string, token: string, magicCode: string = undefined) {
const key: UserToken = new UserToken();
key.ChannelId = channelId;
key.ConnectionName = connectionName;
key.UserId = userId;
key.Token = token;

if (!magicCode)
{
this._userTokens.push(key);
}
else
{
const mc = new TokenMagicCode();
mc.Key = key;
mc.MagicCode = magicCode;
this._magicCodes.push(mc);
}
}

/**
* Retrieves the OAuth token for a user that is in a sign-in flow.
* @param context Context for the current turn of conversation with the user.
* @param connectionName Name of the auth connection to use.
* @param magicCode (Optional) Optional user entered code to validate.
*/
public async getUserToken(context: TurnContext, connectionName: string, magicCode?: string): Promise<TokenResponse> {
const key: UserToken = new UserToken();
key.ChannelId = context.activity.channelId;
key.ConnectionName = connectionName;
key.UserId = context.activity.from.id;

if (magicCode) {
var magicCodeRecord = this._magicCodes.filter(x => key.EqualsKey(x.Key));
if (magicCodeRecord && magicCodeRecord.length > 0 && magicCodeRecord[0].MagicCode === magicCode) {
// move the token to long term dictionary
this.addUserToken(connectionName, key.ChannelId, key.UserId, magicCodeRecord[0].Key.Token);

// remove from the magic code list
const idx = this._magicCodes.indexOf(magicCodeRecord[0]);
this._magicCodes = this._magicCodes.splice(idx, 1);
}
}

var match = this._userTokens.filter(x => key.EqualsKey(x));

if (match && match.length > 0)
{
return {
connectionName: match[0].ConnectionName,
token: match[0].Token,
expiration: undefined
};
}
else
{
// not found
return undefined;
}
}

/**
* Signs the user out with the token server.
* @param context Context for the current turn of conversation with the user.
* @param connectionName Name of the auth connection to use.
*/
public async signOutUser(context: TurnContext, connectionName: string): Promise<void> {
var channelId = context.activity.channelId;
var userId = context.activity.from.id;

var newRecords: UserToken[] = [];
for (var i = 0; i < this._userTokens.length; i++) {
var t = this._userTokens[i];
if (t.ChannelId !== channelId ||
t.UserId !== userId ||
(connectionName && connectionName !== t.ConnectionName))
{
newRecords.push(t);
}
}
this._userTokens = newRecords;
}

/**
* Gets a signin link from the token server that can be sent as part of a SigninCard.
* @param context Context for the current turn of conversation with the user.
* @param connectionName Name of the auth connection to use.
*/
public async getSignInLink(context: TurnContext, connectionName: string): Promise<string> {
return `https://fake.com/oauthsignin/${connectionName}/${context.activity.channelId}/${context.activity.from.id}`;
}

/**
* Signs the user out with the token server.
* @param context Context for the current turn of conversation with the user.
* @param connectionName Name of the auth connection to use.
*/
public async getAadTokens(context: TurnContext, connectionName: string, resourceUrls: string[]): Promise<{
[propertyName: string]: TokenResponse;
}> {
return undefined;
}

/**
* Indicates if the activity is a reply from the bot (role == 'bot')
*
Expand All @@ -282,6 +397,25 @@ export class TestAdapter extends BotAdapter {
}
}

class UserToken {
public ConnectionName: string;
public UserId: string;
public ChannelId: string;
public Token: string;

public EqualsKey(rhs: UserToken): boolean {
return rhs != null &&
this.ConnectionName === rhs.ConnectionName &&
this.UserId === rhs.UserId &&
this.ChannelId === rhs.ChannelId;
}
}

class TokenMagicCode {
public Key: UserToken;
public MagicCode: string;
}

/**
* Support class for `TestAdapter` that allows for the simple construction of a sequence of tests.
*
Expand Down
47 changes: 47 additions & 0 deletions libraries/botbuilder-core/src/userTokenProvider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/**
* @module botbuilder
*/
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/

import { TurnContext } from './turnContext';
import { TokenResponse } from 'botframework-schema';

/**
* Interface for User Token OAuth APIs for BotAdapters
*/
export interface IUserTokenProvider {
/**
* Retrieves the OAuth token for a user that is in a sign-in flow.
* @param context Context for the current turn of conversation with the user.
* @param connectionName Name of the auth connection to use.
* @param magicCode (Optional) Optional user entered code to validate.
*/
getUserToken(context: TurnContext, connectionName: string, magicCode?: string): Promise<TokenResponse>;

/**
* Signs the user out with the token server.
* @param context Context for the current turn of conversation with the user.
* @param connectionName Name of the auth connection to use.
*/
signOutUser(context: TurnContext, connectionName: string): Promise<void>;

/**
* Gets a signin link from the token server that can be sent as part of a SigninCard.
* @param context Context for the current turn of conversation with the user.
* @param connectionName Name of the auth connection to use.
*/
getSignInLink(context: TurnContext, connectionName: string): Promise<string>;

/**
* Signs the user out with the token server.
* @param context Context for the current turn of conversation with the user.
* @param connectionName Name of the auth connection to use.
*/
getAadTokens(context: TurnContext, connectionName: string, resourceUrls: string[]): Promise<{
[propertyName: string]: TokenResponse;
}>;
}

110 changes: 110 additions & 0 deletions libraries/botbuilder-core/tests/testAdapter.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -348,4 +348,114 @@ describe(`TestAdapter`, function () {
}
throw new Error(`TestAdapter.testActivities() should not have succeeded without activities argument.`);
});

it(`getUserToken returns null`, function (done) {
const adapter = new TestAdapter((context) => {
context.adapter.getUserToken(context, 'myConnection').then(token => {
assert(!token);
done();
});
});
adapter.send('hi');
});

it(`getUserToken returns null with code`, function (done) {
const adapter = new TestAdapter((context) => {
context.adapter.getUserToken(context, 'myConnection', '123456').then(token => {
assert(!token);
done();
});
});
adapter.send('hi');
});

it(`getUserToken returns token`, function (done) {
const adapter = new TestAdapter((context) => {
context.adapter.getUserToken(context, 'myConnection').then(token => {
assert(token);
assert(token.token);
assert(token.connectionName);
done();
});
});
adapter.addUserToken('myConnection', 'test', 'user', '123abc');
adapter.send('hi');
});

it(`getUserToken returns token with code`, function (done) {
const adapter = new TestAdapter((context) => {
context.adapter.getUserToken(context, 'myConnection').then(token => {
assert(!token);
context.adapter.getUserToken(context, 'myConnection', '888777').then(token2 => {
assert(token2);
assert(token2.token);
assert(token2.connectionName);
context.adapter.getUserToken(context, 'myConnection').then(token3 => {
assert(token3);
assert(token3.token);
assert(token3.connectionName);
done();
});
});
});
});
adapter.addUserToken('myConnection', 'test', 'user', '123abc', '888777');
adapter.send('hi');
});

it(`getSignInLink returns token with code`, function (done) {
const adapter = new TestAdapter((context) => {
context.adapter.getSignInLink(context, 'myConnection').then(link => {
assert(link);
done();
});
});
adapter.send('hi');
});

it(`signOutUser is noop`, function (done) {
const adapter = new TestAdapter((context) => {
context.adapter.signOutUser(context, 'myConnection').then(x => {
done();
});
});
adapter.send('hi');
});

it(`signOutUser logs out user`, function (done) {
const adapter = new TestAdapter((context) => {
context.adapter.getUserToken(context, 'myConnection').then(token => {
assert(token);
assert(token.token);
assert(token.connectionName);
context.adapter.signOutUser(context, 'myConnection').then(x => {
context.adapter.getUserToken(context, 'myConnection').then(token2 => {
assert(!token2);
done();
});
});
});
});
adapter.addUserToken('myConnection', 'test', 'user', '123abc');
adapter.send('hi');
});

it(`signOutUser with no connectionName signs all out`, function (done) {
const adapter = new TestAdapter((context) => {
context.adapter.getUserToken(context, 'myConnection').then(token => {
assert(token);
assert(token.token);
assert(token.connectionName);
context.adapter.signOutUser(context, undefined).then(x => {
context.adapter.getUserToken(context, 'myConnection').then(token2 => {
assert(!token2);
done();
});
});
});
});
adapter.addUserToken('myConnection', 'test', 'user', '123abc');
adapter.addUserToken('myConnection2', 'test', 'user', 'def456');
adapter.send('hi');
});
});
6 changes: 3 additions & 3 deletions libraries/botbuilder-dialogs/src/prompts/oauthPrompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* Licensed under the MIT License.
*/
import { Token } from '@microsoft/recognizers-text-date-time';
import { Activity, ActivityTypes, Attachment, CardFactory, InputHints, MessageFactory, TokenResponse, TurnContext } from 'botbuilder-core';
import { Activity, ActivityTypes, Attachment, CardFactory, InputHints, MessageFactory, TokenResponse, TurnContext, IUserTokenProvider } from 'botbuilder-core';
import { Dialog, DialogTurnResult } from '../dialog';
import { DialogContext } from '../dialogContext';
import { PromptOptions, PromptRecognizerResult, PromptValidator } from './prompt';
Expand Down Expand Up @@ -196,7 +196,7 @@ export class OAuthPrompt extends Dialog {
}

// Get the token and call validator
const adapter: any = context.adapter as any; // cast to BotFrameworkAdapter
const adapter: IUserTokenProvider = context.adapter as IUserTokenProvider;

return await adapter.getUserToken(context, this.settings.connectionName, code);
}
Expand All @@ -223,7 +223,7 @@ export class OAuthPrompt extends Dialog {
}

// Sign out user
const adapter: any = context.adapter as any; // cast to BotFrameworkAdapter
const adapter: IUserTokenProvider = context.adapter as IUserTokenProvider;

return adapter.signOutUser(context, this.settings.connectionName);
}
Expand Down
Loading