E
E
Eartho Docs
Eartho. Docs - Infrastructure
Search
K
Links

Step 3 - Integrating Eartho into your app

This document describes how to complete a basic Eartho integration in a web app.

1. Before we start, you need to import Eartho into your app.

2. Integrating Eartho into your app

JS
Vue
Angular
React
Kotlin
Swift
Flutter
React Native
Chrome
Need example project? https://github.com/eartho-group/one-client-js 1. Copy the code below to your code 2. After you copied the code, don't forget to change the values of 2.1. YOUR_EARTHO_CLIENT_ID 2.2. redirect_uri 2.3. YOUR_EARTHO_ACCESS_ID You can find this values in https://creator.eartho.world/
If you are using Web version 9/8:
//1. Loading our sdk
import { createEarthoOne, connectWithPopup } from "@eartho/one-client-js";
const earthoOneConfig = {
client_id: "YOUR_EARTHO_CLIENT_ID",
redirect_uri: 'https://your.website',
};
const earthoOne = createEarthoOne(earthoOneConfig);
//2. On clicking on this div, Eartho dialog will pop up.
<div onClick="connectToAccess">
</div>
//3. Defining a function to trigger the flow
function connectToAccess() {
const accessID = "YOUR_EARTHO_ACCESS_ID";
earthoOne.connectWithPopup({access_id:accessID})
.then(async (earthoMember) => {
//4. The ID token you need to pass to your backend:
const idToken = await earthoMember.getIdToken();
console.log("ID Token: " + idToken);
// Useful data for your client-side scripts:
const profile = earthoMember.getUser();
console.log('ID: ' + profile.uid); // Don't send this directly to your server!
console.log('Full Name: ' + profile.displayName);
console.log('Given Name: ' + profile.firstName);
console.log('Family Name: ' + profile.lastName);
console.log('Image URL: ' + profile.photoURL);
console.log('Email: ' + profile.email);
}).catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
});
}
function printCurrentMember(){
//You can also fetch the member in any time this way:
const earthoMember = earthoOne.getUser();
console.log(earthoMember);
}
If you are using JS vanilla:
document.getElementById('login').addEventListener('click', async () => {
await earthoOne.loginWithPopup({access_id:"YOUR_EARTHO_CLIENT_ID"});
});
//in your callback route (<MY_CALLBACK_URL>)
window.addEventListener('load', async () => {
earthoOne = await createEarthoOne({
client_id: '<EARTHO_CLIENT_ID>',
});
const user = await earthoOne.getUser();
console.log(user);
});

Add login to your application

In order to add login to your application you can use the connectWithRedirect function that is exposed on the return value of useEartho, which you can access in your component's setup function.
<script>
import { useEartho } from '@eartho/one-client-vue';
export default {
setup() {
const { connectWithPopup, logout, getUser } = useEartho();
return {
login: () => {
connectWithPopup({access_id:"YOUR_EARTHO_ACCESS_ID"});
}
};
}
};
</script>
Calling an API
<script>
import { useEarthoOne } from '@eartho/one-client-vue';
export default {
setup() {
const { getIdToken } = useEarthoOne();
return {
doSomethingWithToken: async () => {
const token = await getIdToken();
const response = await fetch('https://api.example.com/posts', {
headers: {
Authorization: `Bearer ${token}`
}
});
const data = await response.json();
}
};
}
};
</script>
Next, inject the AuthService service into a component where you intend to provide the functionality to log in, by adding the AuthService type to your constructor. Then, provide a connectWithRedirect() method and call this.auth.connectWithRedirect() to log the user into the application.
import { Component } from '@angular/core';
// Import the AuthService type from the SDK
import { AuthService } from '@eartho/one-client-angular';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
title = 'My App';
// Inject the authentication service into your component through the constructor
constructor(public auth: AuthService) {}
connectWithRedirect(): void {
// Call this to redirect the user to the login page
this.auth.connectWithPopup({access_id:"YOUR_EARTHO_ACCESS_ID"});
}
}
Need example project? https://github.com/eartho-group/one-client-react Use the useEarthoOne hook in your components to access authentication state (isLoading, isConnected and user) and authentication methods (connectWithPopup and logout):
// src/App.js
import React from 'react';
import { useEarthoOne } from '@eartho/one-client-react';
function App() {
const {
isLoading,
isConnected,
error,
user,
connectWithPopup,
logout,
} = useEarthoOne();
if (isLoading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Oops... {error.message}</div>;
}
if (isConnected) {
return (
<div>
Hello {user.displayName}{' '}
<button onClick={() => logout({ returnTo: window.location.origin })}>
Log out
</button>
</div>
);
} else {
return <button
className="btn btn-outline-success"
id="login"
onClick={() => connectWithPopup({ access_id: "YOUR_EARTHO_ACCESS_ID" })}
>
Log in
</button>;
}
}
export default App;

Use with a Class Component

Use the withEarthoOne higher order component to add the earthoOne property to Class components:
import React, { Component } from 'react';
import { withEarthoOne } from '@eartho/one-client-react';
class Profile extends Component {
render() {
// `this.props.earthoOne` has all the same properties as the `useEarthoOne` hook
const { user, logout } = this.props.earthoOne;
return <div>Hello {user.name}</div>;
}
}
export default withEarthoOne(Profile);
Example of use in fragment
//1. Create config
private val config: EarthoOneConfig by lazy {
// -- REPLACE this credentials with your own Eartho app credentials!
val clientId = "YOUR_EARTHO_CLIENT_ID";
val clientSecret = "YOUR_EARTHO_CLIENT_SECRET";
val account = EarthoOneConfig(clientId, clientSecret)
}
//2. Create eartho one instance
private val earthoOne: EarthoOne by lazy {
EarthoOne(requireContext(), config)
}
//3. call connectWithRedirect and the user will be redirect
earthoOne.connectWithRedirect("YOUR_EARTHO_ACCESS_ID",
onSuccess = { result ->
//4. in case you want to manage users by yourself
sendToServer(result.idToken)
});
//Fetch id token
earthoOne.getIdToken()
//Or fetch user
earthoOne.getUser(onSuccess = { result ->
activity?.runOnUiThread {
binding.result.text = "Connected\n" + result.displayName
binding.resultImage.setImageURI(Uri.parse(result.photoURL))
}
});
//1. Create eartho one instance.
// DO NOT FOREGET to change the values. https://creator.eartho.world
let earthoOne = EarthoOne(
"YOUR_EARTHO_CLIENT_ID",
"YOUR_EARTHO_CLIENT_SECRET")
//2. call connectWithRedirect and the user will be redirect
earthoOne.connectWithPopup(
accessId: "YOUR_EARTHO_ACCESS_ID",
onSuccess: { Credentials in
//4. in case you want to manage users by yourself
let idToken = earthoOne.getIdToken()
//Or get user anytime after login
let user = earthoOne.getUser()
print(user?.displayName)
},
onFailure: { WebAuthError in
})
late EarthoOne earthoOne;
//1. Create eartho one instance
// DO NOT FOREGET to change the values. https://creator.eartho.world
earthoOne = EarthoOne(
clientId: "YOUR_EARTHO_CLIENT_ID",
clientSecret: "YOUR_EARTHO_CLIENT_SECRET");
//2. Call init function
earthoOne?.init();
//3. call connectWithRedirect and the user will be redirect
ElevatedButton(
onPressed: () async {
final credentials = await earthoOne?.connectWithRedirect("YOUR_EARTHO_ACCESS_ID");
setState(() {
_credentials = credentials;
});
},
child: const Text("Login")),
4. After Login
//Get user
final user = await earthoOne?.getUser();
//Get id token
final idToken = await earthoOne?.getIdToken();
import { init as earthoInit, connectWithRedirect, getIdToken, getUser } from '@eartho/one-client-react-native';
//1. Init the sdk
React.useEffect(() => {
earthoInit(
"YOUR_EARTHO_CLIENT_ID",
"YOUR_EARTHO_CLIENT_SECRET");
}, []);
//2. open the access dialog
connectWithRedirect("access id: e.g. YOUR_EARTHO_ACCESS_ID")
//3. Get id token or user
console.log(await getIdToken());
console.log(await getUser());
function example(){
val clientId = "YOUR_EARTHO_CLIENT_ID";
val clientSecret = "YOUR_EARTHO_CLIENT_SECRET";
const config = {
client_id: clientId,
};
const earthoOne = await createEarthoOne(config);
const earthoOneExtensionBrowser = new EarthoOneExtensionBrowser({ earthoOne: earthoOne });
val loginAccessId = "YOUR_EARTHO_ACCESS_ID";
earthoOneExtensionBrowser.connectWithPopup({access_id: loginAccessId});
earthoOneExtensionBrowser.getIdToken();
earthoOneExtensionBrowser.getUser();
earthoOneExtensionBrowser.disconnect();
}

3. Want to use Firebase or AWS Amplify?