/** * @format * @flow */ import { Alert } from "react-native"; import axios from "axios"; import { AuthTypes } from "../Enums"; import { InvalidUserCredentialsError } from "../Errors"; import * as KeychainHelper from "../utils/KeychainHelper"; import { API_TIME_OUT } from "../ConfigEnum"; const base64 = require("base-64"); export default class KeycloakClient { authType: "USER_AUTH" | "CLIENT_AUTH" | "USER_ORG_AUTH" | "ORGID_USER_AUTH"; authURL: string; adminURL: string; adminUsername: string; adminPassword: string; clientID: string; clientPassword: string; orgID: string; constructor( authType: "USER_AUTH" | "CLIENT_AUTH" | "USER_ORG_AUTH" | "ORGID_USER_AUTH", authURL: string, adminURL: string, adminUsername: string, adminPassword: string, clientID: string, clientPassword: string, orgID: string ) { this.authType = authType; this.authURL = authURL; this.adminURL = adminURL; this.adminUsername = adminUsername; this.adminPassword = adminPassword; this.clientID = clientID; this.clientPassword = clientPassword; this.orgID = orgID; } /** * Log in with Keycloak and saves the access token. * * Returns the token stirng or empty string if login failed. */ async loginWithClientID(): Promise { try { const encodedAuthorization = base64.encode( `${this.clientID}:${this.clientPassword}` ); console.log(`request url is ==>`, this.authURL); const options = { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", Authorization: `Basic ${encodedAuthorization}`, }, data: "grant_type=client_credentials", url: this.authURL, }; console.log("url->", this.authURL); const response = await axios(options); const responseJSON = response.data; console.log("responseJSON->", responseJSON); if (response.status === 200) { const accessToken = `Bearer ${responseJSON.access_token}`; await KeychainHelper.saveClientToken(this.clientID, accessToken); console.log(`token ===> ${JSON.stringify(accessToken)}`); return accessToken; } return ""; } catch (error) { console.log("getting error ==> " + JSON.stringify(error)); return ""; } } /** * Log in with Keycloak and saves the access token. * * Returns the token string or empty string if login failed. * @param {string} username * @param {string} password */ async loginWithUserCredentials( username: string, password: string ): Promise { try { const bodyJSON = { username, password, grant_type: "password", client_id: "Stratagem-Application", }; // convert body parameters to query string. ex) username=john&password=doe&key=value const bodyString = Object.keys(bodyJSON) .map((key) => `${key}=${bodyJSON[key]}`) .join("&"); // console.log("auth url ==>> " + this.authURL); const options = { method: "POST", timeout: API_TIME_OUT, headers: { "Content-Type": "application/x-www-form-urlencoded", // Authorization: `Basic ${encodedAuthorization}`, }, data: bodyString, url: this.authURL, }; const response = await axios(options); const responseJSON = response.data; if (response.status === 200) { const accessToken = `Bearer ${responseJSON.access_token}`; // save credentials if login was successful await KeychainHelper.saveUserCredentials( username, password, this.authType, accessToken ); return accessToken; } // if login failed for another reason, send empty string to indicate failure return ""; } catch (error) { console.log("login error ==>" + error); if (error.response) { if (error.response.status === 401) { return error; // not a Valid User credentials } else { // 500 and other status code return ""; // not getting any response } } else { // Something happened in setting up the request and triggered an Error return ""; } } } /** * Logs in with Keycloak again using the saved credentials. * Returns the token stirng or empty string if login failed. */ async refreshToken(): Promise { try { if ( this.authType === AuthTypes.USER_AUTH || this.authType === AuthTypes.ORGID_USER_AUTH || this.authType === AuthTypes.USER_ORG_AUTH ) { const credentials = await KeychainHelper.getUserCredentials( this.authType ); if (credentials) { return this.loginWithUserCredentials( credentials.username, credentials.password ); } } if (this.authType === AuthTypes.CLIENT_AUTH) { return this.loginWithClientID(); } return ""; } catch (error) { console.log(`error refreshToken->`, error); if (error instanceof InvalidUserCredentialsError) { // let InvalidUserCredentialsError bubble up to be handled later on throw error; } else { return ""; } } } /** * Convenience method to get the saved token from KeychainHelper */ async getSavedToken(): Promise { return await KeychainHelper.getSavedToken(this.authType); } /** * Registers new user using admin token. * Parameters provided should be validated before passing into this method. * * @param {string} firstName * @param {string} lastName * @param {string} email * @param {string} username * @param {string} password */ async registerNewUser( firstName: string, lastName: string, email: string, username: string, password: string ): Promise { try { const authBodyJSON = { username: this.adminUsername, password: this.adminPassword, grant_type: "password", client_id: "admin-cli", }; // convert body parameters to query string. ex) username=john&password=doe&key=value const authBodyString = Object.keys(authBodyJSON) .map((key) => `${key}=${authBodyJSON[key]}`) .join("&"); // console.log(`register new user ==>${authBodyString}`); // fetch admin access token const authResponse = await fetch(this.authURL, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: authBodyString, }); const authResponseJSON = await authResponse.json(); // use admin token to register new user if (authResponse.status === 200) { const adminToken = `Bearer ${authResponseJSON.access_token}`; const registrationBody = JSON.stringify({ firstName, lastName, email, username, credentials: [{ type: "password", value: password }], enabled: true, }); const registrationURL = `${this.adminURL}users`; const registrationResponse = await fetch(registrationURL, { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json", Authorization: adminToken, }, body: registrationBody, }); // // console.log(registrationResponse); if (registrationResponse.status === 201) { // success return true; } // unsuccessful, so alert user with error message if any is returned const registrationResponseJSON = await registrationResponse.json(); if (registrationResponseJSON.errorMessage) { Alert.alert("Error", registrationResponseJSON.errorMessage); } } return false; } catch (error) { // // console.log(error); Alert.alert("An error occurred while registering"); return false; } } }