Skip to content

Commit

Permalink
add authToken class (#81)
Browse files Browse the repository at this point in the history
* add authToken class

* make account optional

* cleanup

* remove un-needed account
  • Loading branch information
acharb authored Dec 12, 2023
1 parent 69a723b commit 61b6668
Show file tree
Hide file tree
Showing 16 changed files with 105 additions and 65 deletions.
2 changes: 1 addition & 1 deletion examples/sep24/sep24.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ const createAccount = async () => {
};

// Create Deposit
let authToken: string;
let authToken: Types.AuthToken;
export const runDeposit = async (anchor: Anchor, kp: SigningKeypair) => {
console.log("\ncreating deposit ...");
const auth = await anchor.sep10();
Expand Down
4 changes: 2 additions & 2 deletions src/walletSdk/Anchor/Sep24.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ export class Sep24 {
* Initiates a withdrawal request.
* @param {Sep24PostParams} params - The SEP-24 Post params.
* @param {string} params.assetCode - The asset to withdraw.
* @param {string} params.authToken - Authentication token for the request.
* @param {AuthToken} params.authToken - Authentication token for the request.
* @param {string} [params.lang] - The language for the request (defaults to the Anchor's language).
* @param {ExtraFields} [params.extraFields] - Additional fields for the request.
* @param {string} [params.withdrawalAccount] - The withdrawal account.
Expand Down Expand Up @@ -157,7 +157,7 @@ export class Sep24 {
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${authToken}`,
Authorization: `Bearer ${authToken.token}`,
},
},
);
Expand Down
28 changes: 13 additions & 15 deletions src/walletSdk/Anchor/Sep6.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
GetTransactionParams,
GetTransactionsParams,
WatcherSepType,
AuthToken,
} from "../Types";
import {
Watcher,
Expand Down Expand Up @@ -76,7 +77,7 @@ export class Sep6 {
* the anchor are given in the response.
*
* @param {object} options - The options for the deposit.
* @param {string} options.authToken - The authentication token.
* @param {AuthToken} options.authToken - The authentication token.
* @param {Sep6DepositParams} options.params - The parameters for the deposit request.
*
* @returns {Promise<Sep6DepositResponse>} Sep6 deposit response, containing next steps if needed
Expand All @@ -88,7 +89,7 @@ export class Sep6 {
authToken,
params,
}: {
authToken: string;
authToken: AuthToken;
params: Sep6DepositParams;
}): Promise<Sep6DepositResponse> {
return this.flow({ type: "deposit", authToken, params });
Expand All @@ -98,7 +99,7 @@ export class Sep6 {
* Initiates a withdrawal using SEP-6.
*
* @param {object} options - The options for the withdrawal operation.
* @param {string} options.authToken - The authentication token.
* @param {AuthToken} options.authToken - The authentication token.
* @param {Sep6WithdrawParams} options.params - The parameters for the withdrawal request.
*
* @returns {Promise<Sep6WithdrawResponse>} Sep6 withdraw response.
Expand All @@ -107,7 +108,7 @@ export class Sep6 {
authToken,
params,
}: {
authToken: string;
authToken: AuthToken;
params: Sep6WithdrawParams;
}): Promise<Sep6WithdrawResponse> {
return this.flow({ type: "withdraw", authToken, params });
Expand All @@ -118,7 +119,7 @@ export class Sep6 {
* that require an exchange.
*
* @param {object} options - The options for the deposit exchange.
* @param {string} options.authToken - The authentication token.
* @param {AuthToken} options.authToken - The authentication token.
* @param {Sep6ExchangeParams} options.params - The parameters for the deposit request.
*
* @returns {Promise<Sep6DepositResponse>} Sep6 deposit response, containing next steps if needed
Expand All @@ -130,7 +131,7 @@ export class Sep6 {
authToken,
params,
}: {
authToken: string;
authToken: AuthToken;
params: Sep6ExchangeParams;
}): Promise<Sep6DepositResponse> {
return this.flow({ type: "deposit-exchange", authToken, params });
Expand All @@ -141,7 +142,7 @@ export class Sep6 {
* that require an exchange.
*
* @param {object} options - The options for the deposit exchange.
* @param {string} options.authToken - The authentication token.
* @param {AuthToken} options.authToken - The authentication token.
* @param {Sep6ExchangeParams} options.params - The parameters for the deposit request.
*
* @returns {Promise<Sep6WithdrawResponse>} Sep6 withdraw response, containing next steps if needed
Expand All @@ -153,7 +154,7 @@ export class Sep6 {
authToken,
params,
}: {
authToken: string;
authToken: AuthToken;
params: Sep6ExchangeParams;
}): Promise<Sep6WithdrawResponse> {
return this.flow({ type: "withdraw-exchange", authToken, params });
Expand All @@ -165,7 +166,7 @@ export class Sep6 {
params,
}: {
type: "deposit" | "withdraw" | "deposit-exchange" | "withdraw-exchange";
authToken: string;
authToken: AuthToken;
params: Sep6DepositParams | Sep6WithdrawParams | Sep6ExchangeParams;
}) {
const { transferServer } = await this.anchor.sep1();
Expand All @@ -176,7 +177,7 @@ export class Sep6 {
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${authToken}`,
Authorization: `Bearer ${authToken.token}`,
},
},
);
Expand Down Expand Up @@ -204,8 +205,6 @@ export class Sep6 {
* @param {GetTransactionsParams} params - The Get Transactions params.
* @param {AuthToken} params.authToken - The authentication token for the account authenticated with the anchor.
* @param {string} params.assetCode - The target asset to query for.
* @param {string} params.account - The stellar account public key involved in the transactions. If the service requires SEP-10
* authentication, this parameter must match the authenticated account.
* @param {string} [params.noOlderThan] - The response should contain transactions starting on or after this date & time.
* @param {string} [params.limit] - The response should contain at most 'limit' transactions.
* @param {string} [params.kind] - The kind of transaction that is desired. E.g.: 'deposit', 'withdrawal', 'depo
Expand All @@ -219,20 +218,19 @@ export class Sep6 {
async getTransactionsForAsset({
authToken,
assetCode,
account,
noOlderThan,
limit,
kind,
pagingId,
lang = this.anchor.language,
}: GetTransactionsParams & { account: string }): Promise<Sep6Transaction[]> {
}: GetTransactionsParams): Promise<Sep6Transaction[]> {
const toml = await this.anchor.sep1();
const transferServerEndpoint = toml.transferServer;

// Let's convert all params to snake case for the API call
const apiParams = camelToSnakeCaseObject({
assetCode,
account,
account: authToken.account,
noOlderThan,
limit,
kind,
Expand Down
10 changes: 5 additions & 5 deletions src/walletSdk/Anchor/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
} from "../Exceptions";
import { Sep6 } from "./Sep6";
import { Sep24 } from "./Sep24";
import { AnchorServiceInfo, TomlInfo } from "../Types";
import { AnchorServiceInfo, TomlInfo, AuthToken } from "../Types";
import { parseToml } from "../Utils";

// Let's prevent exporting this constructor type as
Expand Down Expand Up @@ -125,11 +125,11 @@ export class Anchor {

/**
* Create new customer object to handle customer records with the anchor using SEP-12.
* @param {string} authToken - The authentication token.
* @param {AuthToken} authToken - The authentication token.
* @returns {Promise<Sep12>} - A Sep12 customer instance.
* @throws {KYCServerNotFoundError} - If the KYC server information is not available.
*/
async sep12(authToken: string): Promise<Sep12> {
async sep12(authToken: AuthToken): Promise<Sep12> {
const tomlInfo = await this.sep1();
const kycServer = tomlInfo?.kycServer;
if (!kycServer) {
Expand All @@ -140,10 +140,10 @@ export class Anchor {

/**
* Create new customer object to handle customer records using the `sep12` method.
* @param {string} authToken - The authentication token.
* @param {AuthToken} authToken - The authentication token.
* @returns {Promise<Customer>} - A Customer instance.
*/
async customer(authToken: string): Promise<Customer> {
async customer(authToken: AuthToken): Promise<Customer> {
return this.sep12(authToken);
}

Expand Down
7 changes: 3 additions & 4 deletions src/walletSdk/Auth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,17 +147,16 @@ export class Sep10 {
throw new MissingTokenError();
}

const authToken: AuthToken = resp.data.token;
validateToken(authToken);
validateToken(resp.data.token);

return authToken;
return AuthToken.from(resp.data.token);
} catch (e) {
throw new ServerRequestFailedError(e);
}
}
}

const validateToken = (token: AuthToken) => {
const validateToken = (token: string) => {
const parsedToken = decode(token);
if (!parsedToken) {
throw new InvalidTokenError();
Expand Down
32 changes: 20 additions & 12 deletions src/walletSdk/Customer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
GetCustomerResponse,
AddCustomerResponse,
AddCustomerParams,
AuthToken,
} from "../Types";

/**
Expand All @@ -24,17 +25,21 @@ export class Sep12 {
/**
* Creates a new instance of the Sep12 class.
* @constructor
* @param {string} authToken - The authentication token for authenticating with the server.
* @param {AuthToken} authToken - The authentication token for authenticating with the server.
* @param {string} baseUrl - The KYC url.
* @param {AxiosInstance} httpClient - An Axios instance for making HTTP requests.
*/
constructor(authToken: string, baseUrl: string, httpClient: AxiosInstance) {
constructor(
authToken: AuthToken,
baseUrl: string,
httpClient: AxiosInstance,
) {
this.authToken = authToken;
this.baseUrl = baseUrl;
this.httpClient = httpClient;
this.headers = {
"Content-Type": "application/json",
Authorization: `Bearer ${this.authToken}`,
Authorization: `Bearer ${this.authToken.token}`,
};
}

Expand Down Expand Up @@ -66,9 +71,9 @@ export class Sep12 {
* Add a new customer. Customer info is given in sep9Info param. If it
* is binary type (eg. Buffer of an image) include it in sep9BinaryInfo.
* @param {AddCustomerParams} params - The parameters for adding a customer.
* @param {CustomerInfoMap} params.sep9Info - Customer information. What fields you should
* @param {CustomerInfoMap} [params.sep9Info] - Customer information. What fields you should
* give is indicated by the anchor.
* @param {CustomerInfoMap} params.sep9BinaryInfo - Customer information that is in binary
* @param {CustomerInfoMap} [params.sep9BinaryInfo] - Customer information that is in binary
* format (eg. Buffer of an image).
* @param {string} [params.type] - The type of the customer.
* @param {string} [params.memo] - A memo associated with the customer.
Expand Down Expand Up @@ -106,9 +111,9 @@ export class Sep12 {
* Updates an existing customer. Customer info is given in sep9Info param. If it
* is binary type (eg. Buffer of an image) include it in sep9BinaryInfo.
* @param {AddCustomerParams} params - The parameters for adding a customer.
* @param {CustomerInfoMap} params.sep9Info - Customer information. What fields you should
* @param {CustomerInfoMap} [params.sep9Info] - Customer information. What fields you should
* give is indicated by the anchor.
* @param {CustomerInfoMap} params.sep9BinaryInfo - Customer information that is in binary
* @param {CustomerInfoMap} [params.sep9BinaryInfo] - Customer information that is in binary
* format (eg. Buffer of an image).
* @param {string} [params.id] - The id of the customer.
* @param {string} [params.type] - The type of the customer.
Expand Down Expand Up @@ -157,10 +162,13 @@ export class Sep12 {
* @param {string} accountAddress - The account address of the customer to delete.
* @param {string} [memo] - An optional memo for customer identification.
*/
async delete(accountAddress: string, memo?: string) {
await this.httpClient.delete(`${this.baseUrl}/customer/${accountAddress}`, {
data: { memo },
headers: this.headers,
});
async delete(accountAddress?: string, memo?: string) {
await this.httpClient.delete(
`${this.baseUrl}/customer/${accountAddress || this.authToken.account}`,
{
data: { memo },
headers: this.headers,
},
);
}
}
2 changes: 1 addition & 1 deletion src/walletSdk/Recovery/AccountRecover.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ export abstract class AccountRecover {
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${auth.authToken}`,
Authorization: `Bearer ${auth.authToken.token}`,
},
},
);
Expand Down
4 changes: 2 additions & 2 deletions src/walletSdk/Recovery/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ export class Recovery extends AccountRecover {
const resp = await this.httpClient.get(requestUrl, {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${authToken}`,
Authorization: `Bearer ${authToken.token}`,
},
});

Expand Down Expand Up @@ -288,7 +288,7 @@ export class Recovery extends AccountRecover {
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${authToken}`,
Authorization: `Bearer ${authToken.token}`,
},
},
);
Expand Down
6 changes: 4 additions & 2 deletions src/walletSdk/Types/anchor.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { MemoType } from "stellar-sdk";
import { Optional } from "utility-types";

import { AuthToken } from "./auth";

export interface AnchorServiceInfo {
deposit: AssetInfoMap;
withdraw: AssetInfoMap;
Expand Down Expand Up @@ -101,15 +103,15 @@ export interface Payment {
}

export type GetTransactionParams = {
authToken: string;
authToken: AuthToken;
id?: string;
stellarTransactionId?: string;
externalTransactionId?: string;
lang?: string;
};

export type GetTransactionsParams = {
authToken: string;
authToken: AuthToken;
assetCode: string;
noOlderThan?: string;
limit?: number;
Expand Down
36 changes: 35 additions & 1 deletion src/walletSdk/Types/auth.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { Transaction } from "stellar-sdk";
import { decode } from "jws";

import { WalletSigner } from "../Auth/WalletSigner";
import { AccountKeypair } from "../Horizon/Account";

Expand All @@ -9,7 +11,39 @@ export type AuthenticateParams = {
clientDomain?: string;
};

export type AuthToken = string;
export class AuthToken {
public token: string;
public issuer: string;
public issuedAt: string;
public expiresAt: string;
public clientDomain: string;
private principalAccount: string;

get account(): string {
return this.principalAccount.split(":")[0];
}

get memo(): string {
const split = this.principalAccount.split(":");
if (split.length !== 2) {
return null;
}
return split[1];
}

static from = (str: string): AuthToken => {
const authToken = new AuthToken();

const decoded = decode(str);
authToken.issuer = decoded.payload.iss;
authToken.principalAccount = decoded.payload.sub;
authToken.issuedAt = decoded.payload.iat;
authToken.expiresAt = decoded.payload.exp;
authToken.clientDomain = decoded.payload.client_domain;
authToken.token = str;
return authToken;
};
}

export type ChallengeParams = {
accountKp: AccountKeypair;
Expand Down
Loading

0 comments on commit 61b6668

Please sign in to comment.