diff --git a/package.json b/package.json index 85b9a2b..a9893af 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "sidedrawer-javascript-sdk", "author": "Juan Matias Doder", "description": "This is a sdk of SideDrawer to help to build development quickly.", - "version": "0.1.18", + "version": "0.1.19", "license": "MIT", "main": "dist/index.js", "typings": "dist/index.d.ts", diff --git a/src/index.ts b/src/index.ts index 41d13f2..b7c6068 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,12 +1,27 @@ -import * as authservice from './services/auth-service'; -import * as networkservice from './services/network-service'; +import AuthClient, { createAuthClient, IAuthClient } from './services/auth-service'; + +import RecordService, { IRecordService } from './services/record-service'; + +import SidedrawerSevice, { ISidedrawerSevice } from './services/sidedrawer-service'; + +import UserSevice, { IUserSevice } from './services/user-service'; + +import NetworkService, { INetworkService } from './services/network-service'; + +export const authClient: IAuthClient = new AuthClient(); + +export const networks: INetworkService = new NetworkService(); + +export const records: IRecordService = new RecordService(); + +export const sidedrawers: ISidedrawerSevice = new SidedrawerSevice(); + +export const users: IUserSevice = new UserSevice(); export const createAuthSidedrawerClient = async (client_id: string) => { - return await authservice.createAuthClient(client_id); + return await createAuthClient(client_id); }; -export const getSidedrawersOwned = async (token: string) => { - return networkservice.getOwned(token); -}; + diff --git a/src/services/auth-service.ts b/src/services/auth-service.ts index 902e112..99f8dde 100644 --- a/src/services/auth-service.ts +++ b/src/services/auth-service.ts @@ -1,10 +1,12 @@ import config from '../config.json'; -import createAuth0Client from '@auth0/auth0-spa-js'; +import createAuth0Client, { Auth0Client, GetTokenSilentlyOptions, GetUserOptions, LogoutOptions, RedirectLoginOptions, RedirectLoginResult, User } from '@auth0/auth0-spa-js'; +export var auth: Auth0Client | null = null; export const createAuthClient = async (client_id: string) => { - return await createAuth0Client({ + + auth = await createAuth0Client({ domain: config.auth0Domain, client_id: client_id, scope: 'openid profile offline_access', @@ -14,5 +16,147 @@ export const createAuthClient = async (client_id: string) => { }); }; +export interface IAuthClient { + /** + * ```js + * const isAuthenticated = await authClient.isAuthenticated(); + * ``` + * + * Returns `true` if there's valid information stored, + * otherwise returns `false`. + * + */ + isAuthenticated(): Promise; + + /** + * After the browser redirects back to the callback page, + * call `handleRedirectCallback` to handle success and error + * responses from Auth. If the response is successful, results + * will be valid according to their expiration times. + */ + handleRedirectCallback(url?: string): Promise; + + /** + * ```js + * const user = await auth.getUser(); + * ``` + * + * Returns the user information if available (decoded + * from the `id_token`). + * + * If you provide an audience or scope, they should match an existing Access Token + * (the SDK stores a corresponding ID Token with every Access Token, and uses the + * scope and audience to look up the ID Token) + * + * @typeparam TUser The type to return, has to extend {@link User}. + * @param options + */ + getUser(options?: GetUserOptions): Promise; + + /** + * ```js + * await authClient.loginWithRedirect(options); + * ``` + * + * Performs a redirect to `/authorize` using the parameters + * provided as arguments. Random and secure `state` and `nonce` + * parameters will be auto-generated. + * + * @param options + */ + loginWithRedirect(options?: RedirectLoginOptions): Promise; + + /** + * ```js + * const token = await authClient.getTokenSilently(options); + * ``` + * + * If there's a valid token stored, return it. Otherwise, opens an + * iframe with the `/authorize` URL using the parameters provided + * as arguments. Random and secure `state` and `nonce` parameters + * will be auto-generated. If the response is successful, results + * will be valid according to their expiration times. + * + * If refresh tokens are used, the token endpoint is called directly with the + * 'refresh_token' grant. If no refresh token is available to make this call, + * the SDK falls back to using an iframe to the '/authorize' URL. + * + * This method may use a web worker to perform the token call if the in-memory + * cache is used. + * + * If an `audience` value is given to this function, the SDK always falls + * back to using an iframe to make the token exchange. + * + * Note that in all cases, falling back to an iframe requires access to + * the `auth0` cookie. + * + * @param options + */ + getTokenSilently(options?: GetTokenSilentlyOptions): Promise; + + /** + * ```js + * authClient.logout(); + * ``` + * + * Clears the application session and performs a redirect to `/v2/logout`, using + * the parameters provided as arguments, to clear the Auth session. + + * [Read more about how Logout works at Auth](https://auth0.com/docs/logout). + * + * @param options + */ + logout(options?: LogoutOptions): Promise; + +} + +export default class AuthClient implements IAuthClient { + + isAuthenticated = async (): Promise => { + + return auth != null ? auth.isAuthenticated() : false; + }; + + handleRedirectCallback = async (url?: string): Promise => { + checkAuthClient(); + + return auth!.handleRedirectCallback(url); + + }; + + getUser = async (options?: GetUserOptions): Promise => { + checkAuthClient(); + return auth!.getUser(options); + }; + + loginWithRedirect = async (options?: RedirectLoginOptions): Promise => { + checkAuthClient(); + return auth!.loginWithRedirect(options); + + }; + + + getTokenSilently = async (options?: GetTokenSilentlyOptions): Promise => { + checkAuthClient(); + return auth!.getTokenSilently(options); + + }; + + logout = async (options?: LogoutOptions): Promise => { + checkAuthClient(); + return await auth!.logout(options); + + }; + + +} + + + +const checkAuthClient = async () => { + if (!auth) + throw new Error('The Auth Client have not been initialized'); + +}; diff --git a/src/services/network-service.ts b/src/services/network-service.ts index 1204bed..4fcd115 100644 --- a/src/services/network-service.ts +++ b/src/services/network-service.ts @@ -1,23 +1,45 @@ import config from '../config.json'; import axios from 'axios'; -//import { Auth0Client } from '@auth0/auth0-spa-js'; - +import { auth } from './auth-service'; const instance = axios.create({ baseURL: config.apiNetwork }); -export const getTimeline = async (sidedrawer_id: string, type: string) => { - return instance.get(`sidedrawer/sidedrawer-id/${sidedrawer_id}/log?locale=en-CA&page=1&entityType=${type}`); -}; +export interface INetworkService { -export const getShared = async () => { - return instance.get(`sidedrawer/shared`); -}; + getTimeline(sidedrawer_id: string, type: string): Promise; + getShared(): Promise; + getOwned(): Promise; + +} + +export default class NetworkService implements INetworkService { + + getTimeline = async (sidedrawer_id: string, type: string) => { + await setToken(); + return instance.get(`sidedrawer/sidedrawer-id/${sidedrawer_id}/log?locale=en-CA&page=1&entityType=${type}`); + }; + + getShared = async () => { + await setToken(); + return instance.get(`sidedrawer/shared`); + }; -export const getOwned = async (token: string) => { - console.log(`Bearer nuevo ${token}`); - instance.defaults.headers.common['Authorization'] = `Bearer ${token}`; - return instance.get(`sidedrawer/owned`); + getOwned = async () => { + await setToken(); + return instance.get(`sidedrawer/owned`); + }; + + +} + + +const setToken = async () => { + if (!auth) + throw new Error('The Auth Client have not been initialized'); + + instance.defaults.headers.common['Authorization'] = `Bearer ${await auth.getTokenSilently()}`; }; + diff --git a/src/services/record-service.ts b/src/services/record-service.ts index a43ed2b..a24cfd4 100644 --- a/src/services/record-service.ts +++ b/src/services/record-service.ts @@ -1,18 +1,35 @@ import config from '../config.json'; import axios from 'axios'; +import { auth } from './auth-service'; const instance = axios.create({ baseURL: config.apiRecord }); +export interface IRecordService { + getBySidedrawer(sidedrawer_id: string): Promise; + getUserSetting(user_id: string): Promise; -export const getBySidedrawer = async (sidedrawer_id: string) => { - return instance.get(`sidedrawer/sidedrawer-id/${sidedrawer_id}/records`); -}; +} +export default class RecordService implements IRecordService { -export const getUserSetting = async (user_id: string) => { - return instance.get(`/accounts/account-id/${user_id}/settings`); -}; + getBySidedrawer = async (sidedrawer_id: string) => { + await setToken(); + return instance.get(`sidedrawer/sidedrawer-id/${sidedrawer_id}/records`); + }; + + getUserSetting = async (user_id: string) => { + await setToken(); + return instance.get(`/accounts/account-id/${user_id}/settings`); + }; +} + +const setToken = async () => { + if (!auth) + throw new Error('The Auth Client have not been initialized'); + + instance.defaults.headers.common['Authorization'] = `Bearer ${await auth.getTokenSilently()}`; +}; diff --git a/src/services/sidedrawer-service.ts b/src/services/sidedrawer-service.ts index 41d013e..edfc20d 100644 --- a/src/services/sidedrawer-service.ts +++ b/src/services/sidedrawer-service.ts @@ -1,15 +1,36 @@ import config from '../config.json'; import axios from 'axios'; +import { auth } from './auth-service'; const instance = axios.create({ baseURL: config.apiRecord }); +export interface ISidedrawerSevice { -export const getHome = async (sidedrawer_id: string) => { - return instance.get(`sidedrawer/sidedrawer-id/${sidedrawer_id}/home?locale=en-CA`); + getHome(sidedrawer_id: string): Promise; + getById(user_id: string): Promise; + +} + +export default class SidedrawerSevice implements ISidedrawerSevice { + + getHome = async (sidedrawer_id: string) => { + await setToken(); + return instance.get(`sidedrawer/sidedrawer-id/${sidedrawer_id}/home?locale=en-CA`); + }; + + getById = async (sidedrawer_id: string) => { + await setToken(); + return instance.get(`sidedrawer/sidedrawer-id/${sidedrawer_id}`); + }; + +} + +const setToken = async () => { + if (!auth) + throw new Error('The Auth Client have not been initialized'); + + instance.defaults.headers.common['Authorization'] = `Bearer ${await auth.getTokenSilently()}`; }; -export const getById = async (sidedrawer_id: string) => { - return instance.get(`sidedrawer/sidedrawer-id/${sidedrawer_id}`); -}; \ No newline at end of file diff --git a/src/services/user-service.ts b/src/services/user-service.ts index a087202..9331669 100644 --- a/src/services/user-service.ts +++ b/src/services/user-service.ts @@ -1,16 +1,36 @@ import config from '../config.json'; import axios from 'axios'; +import { auth } from './auth-service'; const instance = axios.create({ baseURL: config.apiUser }); +export interface IUserSevice { -export const getUserBy = async (auth: string) => { - return instance.get(`/accounts/open-id/${auth}`); -}; + getUserBy(auth: string): Promise; + getSetting(user_id: string): Promise; -export const getUserSetting = async (user_id: string) => { - return instance.get(`/accounts/account-id/${user_id}/settings`); -}; +} + +export default class UserSevice implements IUserSevice { + + getUserBy = async (auth: string) => { + await setToken(); + return instance.get(`/accounts/open-id/${auth}`); + }; + + getSetting = async (user_id: string) => { + await setToken(); + return instance.get(`/accounts/account-id/${user_id}/settings`); + }; +} + + +const setToken = async () => { + if (!auth) + throw new Error('The Auth Client have not been initialized'); + + instance.defaults.headers.common['Authorization'] = `Bearer ${await auth.getTokenSilently()}`; +}; diff --git a/test/createAuthSidedrawerClient.test.ts b/test/createAuthSidedrawerClient.test.ts index a0b7526..ef78f8c 100644 --- a/test/createAuthSidedrawerClient.test.ts +++ b/test/createAuthSidedrawerClient.test.ts @@ -1,7 +1,9 @@ -//import { createAuthSidedrawerClient } from '../src'; +//import { authClient } from '../src'; describe('createAuthSidedrawerClient', () => { it('works', () => { + + //authClient. //expect(createAuthSidedrawerClient("clientId")).toEqual; }); });