1678161059
Learn how to set up user authentication in React using Appwrite and the GraphQL API. Learn how to use Appwrite Web SDK to interact with Appwrite’s new Graphql API to set up user authentication in a React application.
User authentication is an essential part of any web application, and setting it up can be a daunting task for many developers. However, with the help of Appwrite, this process can become much easier and more streamlined.
This tutorial will cover how to use Appwrite Web SDK to interact with Appwrite’s new Graphql API to set up user authentication in a React application. We will discuss how to implement signup functionality, handle user login and logout, and implement an email verification feature.
Table of contents:
Profile
componentTo follow along with this tutorial, you should have a basic understanding of React and its concepts. This tutorial also requires a basic understanding of GraphQL, including how to write queries and mutations.
So, let’s get started!
In this blog, we will be discussing how to use Appwrite to implement user authentication in your React application easily. But before diving into the details, let’s briefly discuss what Appwrite is.
Appwrite is an open source, self-hosted, backend-as-a-service platform. It provides all the core APIs that allow developers to easily manage and interact with various services, such as user authentication, database management, and file storage.
By using Appwrite, developers can focus on building their core application logic while leaving the backend infrastructure to Appwrite.
The first step in setting up Appwrite is to install it using Docker. To do so, you need to have the Docker CLI installed on your host machine. Then, you can run one of the following commands according to your OS to install Appwrite.
Before running the command, make sure Docker is running on your machine.
To install Appwrite on a Mac or Linux device, use the following command:
docker run -it --rm \
--volume /var/run/docker.sock:/var/run/docker.sock \
--volume "$(pwd)"/appwrite:/usr/src/code/appwrite:rw \
--entrypoint="install" \
appwrite/appwrite:1.2.0
To install Appwrite on a Windows device, run the following command using Command Prompt:
docker run -it --rm ^
--volume //var/run/docker.sock:/var/run/docker.sock ^
--volume "%cd%"/appwrite:/usr/src/code/appwrite:rw ^
--entrypoint="install" ^
appwrite/appwrite:1.2.0
After running the command, you will be prompted with a series of configuration questions. These questions will ask for information such as the HTTP port, hostname, and other settings. You can choose the default options by pressing the enter key or modify the options if you prefer.
For more detailed instructions on installing Appwrite, you can refer to the official installation documentation on the Appwrite website.
Now that you have Appwrite installed and running on your machine, you can access the Appwrite console by navigating to http://localhost.
You will be prompted to create a new account. This account will be used to access the Appwrite console and manage your projects and services.
To create a project, click the “Create Project” button on the Appwrite dashboard, enter the project name, and click “Create.”
Once you have created a project, you will need to add a web platform to your project to init the Appwrite SDK and interact with the Appwrite APIs. You can do this by clicking the “Web App” button on the Appwrite console.
You will be prompted to enter a project name and hostname. For development purposes, you can use localhost
as your hostname. Once you have added the web platform, you will be able to use the Appwrite SDK to interact with the Appwrite services.
To get started quickly, I have created a starter code repository that contains all the necessary code. To clone the starter code, open up a terminal and run the following command:
git clone https://github.com/rishipurwar1/appwrite-graphql-authentication.git
Once you have cloned the starter code repository, you will find all the components
inside the src/components
folder. These components include:
Navbar.js
— responsible for displaying the navbar at the top of the applicationHome.js
— the main landing page of the sample applicationLogin.js
— contains the code for the login formSignup.js
— contains the code for the signup formProfile.js
— contains the code for the profile pageIn addition to the components mentioned earlier, the starter code repository also includes the routing setup for React Router in the src/App.js
file. For example, the /
URL is mapped to the Home
component, the /login
URL is mapped to the Login
component, and so on.
You will also find the CSS code in the src/App.css
file for all the components, which is imported into the App.js
file.
After cloning the starter code repository, you must install all the dependencies before running the application. To do this, you need to navigate to the appwrite-graphql-authentication
directory and run the following command:
npm install
Once the dependencies are installed, you can run the application by using the command:
npm start
This command will start the application, which you can access by navigating to http://localhost:3000 in your web browser.
Now that our sample application is up and running, we can proceed to install the appwrite
package in order to interact with Appwrite services using the Appwrite Web SDK easily. To do this, install the appwrite
package by running the following command:
npm install appwrite
Once the package is installed, create an appwrite
folder inside the src
folder, and inside it, create a config.js
file. This file will be used to import and initialize the Appwrite SDK.
In the config.js
file, you can import the Appwrite modules and initialize the Appwrite SDK by adding the following code to the file:
import { Client, Graphql } from "appwrite";
// initialize SDK
const client = new Client();
client
.setEndpoint("YOUR_API_ENDPOINT") // Replace this
.setProject("YOUR_PROJECT_ID"); // Replace this
export const graphql = new Graphql(client);
Make sure to replace “YOUR_API_ENDPOINT” and “YOUR_PROJECT_ID” with your project’s API endpoint and project ID. You can find this information on your Appwrite project settings page:
In the last line of the code, we created and exported the graphql
instance we will use it in other components to interact with the Appwrite Graphql API.
In this section, we will implement the signup functionality for our React application. To do this, we will create a custom Hook, which will contain functions for login
, signup
, and logout
actions. This Hook will also have one state variable to keep track of the logged-in user.
By creating a custom Hook, we can easily manage the state and functionality related to user authentication in one place. This will make it easy to reuse the code across different components and keep the application organized.
Now, let’s create a hooks
folder inside the src
folder, then create a useAuth.js
file. At the top of this file, import graphql
from the config.js
. You will then need to create a useAuth
function by adding the following code:
import { graphql } from "../appwrite/config";
const useAuth = () => {
// useAuth hook code goes here
};
export default useAuth;
Let’s create a signup
function inside the useAuth
. We can do that by adding the following code:
import { graphql } from "../appwrite/config";
const useAuth = () => {
// sign up functionality
const signup = async (email, password, username) => {
const response = await graphql.mutation({
query: `mutation (
$email: String!,
$password: String!,
$name: String
) {
accountCreate(
userId: "unique()",
email: $email,
password: $password,
name: $name
) {
_id
}
}`,
variables: {
email: email,
password: password,
name: username,
},
});
if (response.errors) {
throw response.errors[0].message;
}
};
return {
signup,
};
};
export default useAuth;
The signup
function we created in the code above takes in three parameters — email
, password
, and username
. Inside the function, there is a method called graphql.mutation
that is used to make changes to the data. In this case, the method creates a new account with the provided email, password, and username.
The mutation
method takes in an object that contains two properties — the query
property and the variables
object.
The query
property uses the accountCreate
mutation to create a new user account with the provided email, password, and username.
The variables
object is used to pass the values of the email
, password
, and username
to the accountCreate
mutation dynamically. If the mutation is successful, it will return the _id
of the created account.
The if
block is added to check for any errors while creating the account.
Finally, the Hook returns an object that contains the signup
function, which can be used in other components.
signup
function in our Appwrite projectNow that we have created the signup
function inside our useAuth
hook, we can use it in our Signup
component to create a new account. Before we do that, let me explain the Signup
component code.
In this component, we have two functions — handleChange
and handleSubmit
.
The handleChange
function is used to update the user
state variable with the values entered by the user in the form input fields.
The handleSubmit
function is used to handle the form submission event, and prevent the default form submission behaviour. In this example, this function only logs the user object to the console, but later on, we will use the signup
function to create a new account.
The form has three input fields for email
, username
, and password
. Each input field has the onChange
event that calls the handleChange
function to update the user
state variable with the values entered by the user.
The form
element also has an onSubmit
event that calls the handleSubmit
function when a user clicks the submit button.
Let’s use the signup
function to create a new user account when a user signs up using the Signup
form.
To do this, first, we need to import the useAuth
hook in the Signup
component, then call the useAuth
hook and destructure the signup
function from it. Then, call the signup
function inside the handleSubmit
function with the values of the email
, password
, and username
entered by the user.
Your code should look like this:
import { useState } from "react";
import { Link } from "react-router-dom";
import { useAuth } from "../hooks/useAuth"; // import useAuth
const Signup = () => {
const [user, setUser] = useState({});
const { signup } = useAuth();
const handleChange = (e) => {
setUser({ ...user, [e.target.name]: e.target.value });
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
await signup(user.email, user.password, user.username);
alert("Account created successfully!");
} catch (error) {
console.log(error);
}
};
// rest of the code
}
To test the signup feature, open the signup page of your application. Fill in the form with your email, username, and password. Remember that the password should be at least eight characters long.
Once you have filled in the form, click the “Sign Up” button to submit the form. If the account creation is successful, you should see an alert message. If the account creation fails, an error message will be printed on the console.
You can also verify that the user has been created by checking your Appwrite project dashboard. Log in to your Appwrite account, navigate to the project dashboard, and select the “Auth” tab on the sidebar. Here, you will be able to see the new user account that you just created:
Congratulations! You have successfully implemented signup functionality in your React application using Appwrite.
To implement login functionality in our React app with Appwrite, we will follow a similar approach as we did for the signup functionality. First, create a login
function inside the useAuth
hook by adding the following code:
import { graphql } from "../appwrite/config";
const useAuth = () => {
const signup = async (email, password, username) => {
// signup function code
};
const login = async (email, password) => {
const response = await graphql.mutation({
query: `mutation (
$email: String!,
$password: String!,
) {
accountCreateEmailSession(
email: $email,
password: $password,
) {
_id
}
}`,
variables: {
email: email,
password: password,
},
});
if (response.errors) {
throw response.errors[0].message;
}
};
return {
signup,
login, // return it
};
};
export default useAuth;
The above query property uses the accountCreateEmailSession
mutation to allow users to log in to their accounts by providing a valid email and password. This will create a new session for the user.
login
function in our Appwrite projectLet’s import the useAuth
hook in the Login.js
file and call it inside the Login
component. Then, destructure the login
function from the useAuth
hook. Finally, call the login
function inside the handleSubmit
function, passing in the values of the email
and password
entered by the user.
The code should look similar to this:
import { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import useAuth from "../hooks/useAuth";
const Login = () => {
const [user, setUser] = useState({});
const navigate = useNavigate();
const { login } = useAuth();
const handleChange = (e) => {
setUser({ ...user, [e.target.name]: e.target.value });
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
await login(user.email, user.password);
navigate("/profile");
} catch (error) {
console.log(error);
}
};
// rest of the code
};
export default Login;
To test the login feature, open the login page of your application. Fill in the form with your email and password. Once you have filled in the form, click the “Log In” button to submit the form.
If the login is successful, the user will be navigated to the /profile
page. If the login fails, an error message will be printed on the console.
Currently, the information displayed on the profile page is hardcoded, but we will make it dynamic by fetching the logged-in user’s data using the Appwrite API in the next section.
In this section, I will show you how to fetch a logged-in user’s data and display it on the Profile
component. First, let’s create a user state using the useState
Hook in the useAuth
hook and set it to null
:
import { useState } from "react"; // import useState
const useAuth = () => {
const [user, setUser] = useState(null); // create a user state
// rest of the code
}
Next, we will create the getCurrentUser
function inside the useAuth
Hook. The getCurrentUser
function uses the accountGet
query provided by the Appwrite GraphQL API to fetch the currently logged-in user’s data.
Below is the code for the getCurrentUser
function:
const getCurrentUser = async () => {
const response = await graphql.query({
query: `query {
accountGet {
_id
name
emailVerification
email
}
}`,
});
return response.data.accountGet;
};
As you can see, this query returns an object that contains the user’s ID, name, email address, and email verification status.
Next, we will use the useEffect
Hook to call the getCurrentUser
function and update the user
state with the returned data.
Finally, we will return the user
state from the useAuth
hook so it can be accessed in other components.
Your useAuth
code should look like this:
import { useEffect, useState } from "react"; // import useEffect
import { graphql } from "../appwrite/config";
const useAuth = () => {
const [user, setUser] = useState(null);
const signup = async (email, password, username) => {
// signup code
};
const login = async (email, password) => {
// login code
};
const getCurrentUser = async () => {
// getCurrentUser code
};
// fetching the logged user data
useEffect(() => {
const fetchUser = async () => {
const userDetails = await getCurrentUser();
setUser(userDetails);
};
fetchUser();
}, []);
return {
signup,
login,
user, // return it
};
};
export default useAuth;
Profile
componentIn the Profile
component, you can import the useAuth
hook and destructure the user
state. Then, you can use the user
data to display the user’s name, email, and other information on the profile page.
Below is the updated code for the Profile
component:
import useAuth from "../hooks/useAuth"; // import useAuth
const Profile = () => {
const { user } = useAuth(); // destructure user
return (
<div className="profile">
<h1 className="name">Welcome, {user?.name}</h1>
<h2 className="email">Email: {user?.email}</h2>
</div>
);
};
export default Profile;
Once you have updated the code, you should see the currently logged-in user’s name and email displayed on the /profile
page:
To implement logout functionality in our React app with Appwrite, first create a logout
function inside the useAuth
Hook by adding the following code:
const logout = async () => {
const response = await graphql.mutation({
query: `mutation {
accountDeleteSession(
sessionId: "current"
) {
status
}
}`,
});
if (response.errors) {
throw response.errors[0].message;
}
};
As you can see, the accountDeleteSession
mutation takes in the “current” as the session ID, which logs out the currently logged-in user from the current device session.
Finally, we will return the logout
function from the useAuth
hook so it can be accessed in other components.
Your useAuth
code should look like this:
import { useEffect, useState } from "react";
import { graphql } from "../appwrite/config";
const useAuth = () => {
const [user, setUser] = useState(null);
const signup = async (email, password, username) => {
// signup code
};
const login = async (email, password) => {
// login code
};
const getCurrentUser = async () => {
// getCurrentUser code
};
// logout function
const logout = async () => {
// logout code
};
useEffect(() => {
// code
}, []);
return {
signup,
login,
logout, // return logout
user
};
};
export default useAuth;
Let’s import the useAuth
hook in the Profile.js
file and call it inside the Profile
component. Then, destructure the logout
function from the useAuth
hook.
Next, create a handleLogout
function inside the Profile
component by adding the following code:
const handleLogout = async () => {
try {
await logout();
navigate("/login");
} catch (error) {
console.log(error);
}
};
Finally, add an onClick
event listener to the “Log Out” button. Your Profile
component code should look like this:
import { useNavigate } from "react-router-dom"; // import useNavigate
import useAuth from "../hooks/useAuth";
const Profile = () => {
const { logout, user } = useAuth();
const navigate = useNavigate();
const handleLogout = async () => {
try {
await logout();
navigate("/login");
} catch (error) {
console.log(error);
}
};
return (
<div className="profile">
<h1 className="name">Welcome, {user?.name}</h1>
<h2 className="email">Email: {user?.email}</h2>
<button className="logOut-btn" onClick={handleLogout}>
Log Out
</button>
</div>
);
};
export default Profile;
To test the logout
feature, open the profile page and click the “Log Out” button. If the logout action is successful, the user will be redirected to the /login
page. If the logout action fails, an error message will be printed on the console.
In this section, we will learn how to implement email verification functionality in our application using Appwrite’s GraphQL API. To verify the user’s email address, we need to accomplish two steps:
But before we begin, it is important to note that in order to send verification emails, we will need to set up a third-party SMTP provider such as SendGrid or MailGun. For this tutorial, we will be using MailGun.
To set up MailGun, first go to the MailGun website and sign up for a free account. After signing up, you will be taken to the dashboard, where you need to verify your email address by following MailGun’s instructions.
After that, select the “SMTP” option on the “Overview” page. Here, you’ll find your SMTP credentials such as hostname, port, username, and password:
.env
file with your SMTP credentialsNow, open the appwrite
folder that was created when you installed Appwrite, not the one that we created inside the project folder. Inside this folder, you will find a file named .env
that needs to be updated with your SMTP credentials.
Open the .env
file and update the following fields with the respective information for your project:
_APP_SMTP_HOST
— your SMTP hostname_APP_SMTP_PORT
— your SMTP port_APP_SMTP_SECURE
— SMTP secure connection protocol (you can set it to ‘tls’ if running on a secure connection)_APP_SMTP_USERNAME
— your SMTP username_APP_SMTP_PASSWORD
— your SMTP password_APP_SYSTEM_EMAIL_ADDRESS
— your SMTP email addressOnce you have updated the .env
file, save it and restart your Appwrite server by running the following command:
docker compose up -d
Now that we have set up the SMTP configuration, we can move on to implementing the email verification feature.
Create a sendVerificationEmail
function inside the useAuth
Hook by using the following code:
const useAuth = () => {
// other functions and state
const sendVerificationEmail = async () => {
const response = await graphql.mutation({
query: `mutation {
accountCreateVerification(
url: "http://localhost:3000/profile"
) {
_id
_createdAt
userId
secret
expire
}
}`,
});
if (response.errors) {
throw response.errors[0].message;
}
};
return {
signup,
login,
logout,
user,
sendVerificationEmail // return this
};
};
This function will be responsible for sending verification emails. Note that the accountCreateVerification
mutation in this function takes in a url
property, which is the URL that the user will be redirected to after they click on the verification link sent to their email address.
Before we use this function, it is important to note that you can only send verification emails after creating a login session for the user. To do that, you need to call the login
function right after calling the signup
function in the handleSubmit
function of the Signup
component, like this:
const Signup = () => {
const [user, setUser] = useState({});
const { signup, login } = useAuth(); // add login function
const handleChange = (e) => {
setUser({ ...user, [e.target.name]: e.target.value });
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
await signup(user.email, user.password, user.username);
await login(user.email, user.password); // call login function
alert("Account created successfully!");
} catch (error) {
console.log(error);
}
};
// rest of the code
};
Let’s call the sendVerificationEmail
function after the login
function call to send verification emails:
const Signup = () => {
const [user, setUser] = useState({});
const { signup, login, sendVerificationEmail } = useAuth(); // add sendVerificationEmail function
const handleChange = (e) => {
setUser({ ...user, [e.target.name]: e.target.value });
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
await signup(user.email, user.password, user.username);
await login(user.email, user.password);
await sendVerificationEmail(); // call sendVerificationEmail function
alert("Account created and verification email sent successfully!");
} catch (error) {
console.log(error);
}
};
// rest of the code
};
To test this feature, go ahead and sign up for an account in your app using the email that you verified on MailGun. You should receive a verification link in your email. Be sure to check your spam folder as well:
In the verification link you receive, you’ll see userId
and secret
parameters attached. We’ll use these parameters to make another API request to verify the user’s email address. Let’s create a function for that in the useAuth
hook by using the following code:
const useAuth = () => {
// other functions and state
const confirmEmailVerification = async (userId, secret) => {
const response = await graphql.mutation({
query: `mutation (
$userId: String!,
$secret: String!,
) {
accountUpdateVerification(
userId: $userId,
secret: $secret
) {
_id
}
}`,
variables: {
userId: userId,
secret: secret,
},
});
if (response.errors) {
throw response.errors[0].message;
}
};
return {
// rest of the functions and state
confirmEmailVerification
};
};
In the Profile
component, we need to extract the parameters from the redirected URL and pass them to the confirmEmailVerification
function as parameters when the user is on the profile page after redirection. This can be done by using the following code:
import { useNavigate } from "react-router-dom";
import useAuth from "../hooks/useAuth";
const Profile = () => {
const { logout, user, confirmEmailVerification } = useAuth(); // add confirmEmailVerification
// rest of the code
const handleLogout = async () => {
// code
};
const urlParams = new URLSearchParams(window.location.search);
const userId = urlParams.get("userId"); // extract userId
const secret = urlParams.get("secret"); // extract secret
const handleConfirmEmailVerification = async () => {
try {
await confirmEmailVerification(userId, secret);
alert("Email verified successfully!");
navigate("/profile");
} catch (err) {
console.log(err);
}
};
if (!user?.emailVerification && userId && secret) {
handleConfirmEmailVerification();
}
// rest of the code
};
export default Profile;
You should be able to verify the user’s email address. And with that, this tutorial is finished!
This concludes our tutorial on setting up user authentication in React using Appwrite and the GraphQL API. We covered installing and setting up Appwrite, creating a project, implementing signup and login functionality, fetching the logged-in user’s information, and setting up email verification functionality.
I hope you enjoyed this article! Thanks for taking the time to read it. If you have any issues while following the article or have further questions, let me know in the comments section.
If you like what I’m doing here and want to help me keep doing it, don’t forget to hit that share button. Happy coding!
Source: https://blog.logrocket.com
#react #appwrite #graphql
1651383480
This serverless plugin is a wrapper for amplify-appsync-simulator made for testing AppSync APIs built with serverless-appsync-plugin.
Install
npm install serverless-appsync-simulator
# or
yarn add serverless-appsync-simulator
Usage
This plugin relies on your serverless yml file and on the serverless-offline
plugin.
plugins:
- serverless-dynamodb-local # only if you need dynamodb resolvers and you don't have an external dynamodb
- serverless-appsync-simulator
- serverless-offline
Note: Order is important serverless-appsync-simulator
must go before serverless-offline
To start the simulator, run the following command:
sls offline start
You should see in the logs something like:
...
Serverless: AppSync endpoint: http://localhost:20002/graphql
Serverless: GraphiQl: http://localhost:20002
...
Configuration
Put options under custom.appsync-simulator
in your serverless.yml
file
| option | default | description | | ------------------------ | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | | apiKey | 0123456789
| When using API_KEY
as authentication type, the key to authenticate to the endpoint. | | port | 20002 | AppSync operations port; if using multiple APIs, the value of this option will be used as a starting point, and each other API will have a port of lastPort + 10 (e.g. 20002, 20012, 20022, etc.) | | wsPort | 20003 | AppSync subscriptions port; if using multiple APIs, the value of this option will be used as a starting point, and each other API will have a port of lastPort + 10 (e.g. 20003, 20013, 20023, etc.) | | location | . (base directory) | Location of the lambda functions handlers. | | refMap | {} | A mapping of resource resolutions for the Ref
function | | getAttMap | {} | A mapping of resource resolutions for the GetAtt
function | | importValueMap | {} | A mapping of resource resolutions for the ImportValue
function | | functions | {} | A mapping of external functions for providing invoke url for external fucntions | | dynamoDb.endpoint | http://localhost:8000 | Dynamodb endpoint. Specify it if you're not using serverless-dynamodb-local. Otherwise, port is taken from dynamodb-local conf | | dynamoDb.region | localhost | Dynamodb region. Specify it if you're connecting to a remote Dynamodb intance. | | dynamoDb.accessKeyId | DEFAULT_ACCESS_KEY | AWS Access Key ID to access DynamoDB | | dynamoDb.secretAccessKey | DEFAULT_SECRET | AWS Secret Key to access DynamoDB | | dynamoDb.sessionToken | DEFAULT_ACCESS_TOKEEN | AWS Session Token to access DynamoDB, only if you have temporary security credentials configured on AWS | | dynamoDb.* | | You can add every configuration accepted by DynamoDB SDK | | rds.dbName | | Name of the database | | rds.dbHost | | Database host | | rds.dbDialect | | Database dialect. Possible values (mysql | postgres) | | rds.dbUsername | | Database username | | rds.dbPassword | | Database password | | rds.dbPort | | Database port | | watch | - *.graphql
- *.vtl | Array of glob patterns to watch for hot-reloading. |
Example:
custom:
appsync-simulator:
location: '.webpack/service' # use webpack build directory
dynamoDb:
endpoint: 'http://my-custom-dynamo:8000'
Hot-reloading
By default, the simulator will hot-relad when changes to *.graphql
or *.vtl
files are detected. Changes to *.yml
files are not supported (yet? - this is a Serverless Framework limitation). You will need to restart the simulator each time you change yml files.
Hot-reloading relies on watchman. Make sure it is installed on your system.
You can change the files being watched with the watch
option, which is then passed to watchman as the match expression.
e.g.
custom:
appsync-simulator:
watch:
- ["match", "handlers/**/*.vtl", "wholename"] # => array is interpreted as the literal match expression
- "*.graphql" # => string like this is equivalent to `["match", "*.graphql"]`
Or you can opt-out by leaving an empty array or set the option to false
Note: Functions should not require hot-reloading, unless you are using a transpiler or a bundler (such as webpack, babel or typescript), un which case you should delegate hot-reloading to that instead.
Resource CloudFormation functions resolution
This plugin supports some resources resolution from the Ref
, Fn::GetAtt
and Fn::ImportValue
functions in your yaml file. It also supports some other Cfn functions such as Fn::Join
, Fb::Sub
, etc.
Note: Under the hood, this features relies on the cfn-resolver-lib package. For more info on supported cfn functions, refer to the documentation
You can reference resources in your functions' environment variables (that will be accessible from your lambda functions) or datasource definitions. The plugin will automatically resolve them for you.
provider:
environment:
BUCKET_NAME:
Ref: MyBucket # resolves to `my-bucket-name`
resources:
Resources:
MyDbTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: myTable
...
MyBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: my-bucket-name
...
# in your appsync config
dataSources:
- type: AMAZON_DYNAMODB
name: dynamosource
config:
tableName:
Ref: MyDbTable # resolves to `myTable`
Sometimes, some references cannot be resolved, as they come from an Output from Cloudformation; or you might want to use mocked values in your local environment.
In those cases, you can define (or override) those values using the refMap
, getAttMap
and importValueMap
options.
refMap
takes a mapping of resource name to value pairsgetAttMap
takes a mapping of resource name to attribute/values pairsimportValueMap
takes a mapping of import name to values pairsExample:
custom:
appsync-simulator:
refMap:
# Override `MyDbTable` resolution from the previous example.
MyDbTable: 'mock-myTable'
getAttMap:
# define ElasticSearchInstance DomainName
ElasticSearchInstance:
DomainEndpoint: 'localhost:9200'
importValueMap:
other-service-api-url: 'https://other.api.url.com/graphql'
# in your appsync config
dataSources:
- type: AMAZON_ELASTICSEARCH
name: elasticsource
config:
# endpoint resolves as 'http://localhost:9200'
endpoint:
Fn::Join:
- ''
- - https://
- Fn::GetAtt:
- ElasticSearchInstance
- DomainEndpoint
In some special cases you will need to use key-value mock nottation. Good example can be case when you need to include serverless stage value (${self:provider.stage}
) in the import name.
This notation can be used with all mocks - refMap
, getAttMap
and importValueMap
provider:
environment:
FINISH_ACTIVITY_FUNCTION_ARN:
Fn::ImportValue: other-service-api-${self:provider.stage}-url
custom:
serverless-appsync-simulator:
importValueMap:
- key: other-service-api-${self:provider.stage}-url
value: 'https://other.api.url.com/graphql'
This plugin only tries to resolve the following parts of the yml tree:
provider.environment
functions[*].environment
custom.appSync
If you have the need of resolving others, feel free to open an issue and explain your use case.
For now, the supported resources to be automatically resovled by Ref:
are:
Feel free to open a PR or an issue to extend them as well.
External functions
When a function is not defined withing the current serverless file you can still call it by providing an invoke url which should point to a REST method. Make sure you specify "get" or "post" for the method. Default is "get", but you probably want "post".
custom:
appsync-simulator:
functions:
addUser:
url: http://localhost:3016/2015-03-31/functions/addUser/invocations
method: post
addPost:
url: https://jsonplaceholder.typicode.com/posts
method: post
Supported Resolver types
This plugin supports resolvers implemented by amplify-appsync-simulator
, as well as custom resolvers.
From Aws Amplify:
Implemented by this plugin
#set( $cols = [] )
#set( $vals = [] )
#foreach( $entry in $ctx.args.input.keySet() )
#set( $regex = "([a-z])([A-Z]+)")
#set( $replacement = "$1_$2")
#set( $toSnake = $entry.replaceAll($regex, $replacement).toLowerCase() )
#set( $discard = $cols.add("$toSnake") )
#if( $util.isBoolean($ctx.args.input[$entry]) )
#if( $ctx.args.input[$entry] )
#set( $discard = $vals.add("1") )
#else
#set( $discard = $vals.add("0") )
#end
#else
#set( $discard = $vals.add("'$ctx.args.input[$entry]'") )
#end
#end
#set( $valStr = $vals.toString().replace("[","(").replace("]",")") )
#set( $colStr = $cols.toString().replace("[","(").replace("]",")") )
#if ( $valStr.substring(0, 1) != '(' )
#set( $valStr = "($valStr)" )
#end
#if ( $colStr.substring(0, 1) != '(' )
#set( $colStr = "($colStr)" )
#end
{
"version": "2018-05-29",
"statements": ["INSERT INTO <name-of-table> $colStr VALUES $valStr", "SELECT * FROM <name-of-table> ORDER BY id DESC LIMIT 1"]
}
#set( $update = "" )
#set( $equals = "=" )
#foreach( $entry in $ctx.args.input.keySet() )
#set( $cur = $ctx.args.input[$entry] )
#set( $regex = "([a-z])([A-Z]+)")
#set( $replacement = "$1_$2")
#set( $toSnake = $entry.replaceAll($regex, $replacement).toLowerCase() )
#if( $util.isBoolean($cur) )
#if( $cur )
#set ( $cur = "1" )
#else
#set ( $cur = "0" )
#end
#end
#if ( $util.isNullOrEmpty($update) )
#set($update = "$toSnake$equals'$cur'" )
#else
#set($update = "$update,$toSnake$equals'$cur'" )
#end
#end
{
"version": "2018-05-29",
"statements": ["UPDATE <name-of-table> SET $update WHERE id=$ctx.args.input.id", "SELECT * FROM <name-of-table> WHERE id=$ctx.args.input.id"]
}
{
"version": "2018-05-29",
"statements": ["UPDATE <name-of-table> set deleted_at=NOW() WHERE id=$ctx.args.id", "SELECT * FROM <name-of-table> WHERE id=$ctx.args.id"]
}
#set ( $index = -1)
#set ( $result = $util.parseJson($ctx.result) )
#set ( $meta = $result.sqlStatementResults[1].columnMetadata)
#foreach ($column in $meta)
#set ($index = $index + 1)
#if ( $column["typeName"] == "timestamptz" )
#set ($time = $result["sqlStatementResults"][1]["records"][0][$index]["stringValue"] )
#set ( $nowEpochMillis = $util.time.parseFormattedToEpochMilliSeconds("$time.substring(0,19)+0000", "yyyy-MM-dd HH:mm:ssZ") )
#set ( $isoDateTime = $util.time.epochMilliSecondsToISO8601($nowEpochMillis) )
$util.qr( $result["sqlStatementResults"][1]["records"][0][$index].put("stringValue", "$isoDateTime") )
#end
#end
#set ( $res = $util.parseJson($util.rds.toJsonString($util.toJson($result)))[1][0] )
#set ( $response = {} )
#foreach($mapKey in $res.keySet())
#set ( $s = $mapKey.split("_") )
#set ( $camelCase="" )
#set ( $isFirst=true )
#foreach($entry in $s)
#if ( $isFirst )
#set ( $first = $entry.substring(0,1) )
#else
#set ( $first = $entry.substring(0,1).toUpperCase() )
#end
#set ( $isFirst=false )
#set ( $stringLength = $entry.length() )
#set ( $remaining = $entry.substring(1, $stringLength) )
#set ( $camelCase = "$camelCase$first$remaining" )
#end
$util.qr( $response.put("$camelCase", $res[$mapKey]) )
#end
$utils.toJson($response)
Variable map support is limited and does not differentiate numbers and strings data types, please inject them directly if needed.
Will be escaped properly: null
, true
, and false
values.
{
"version": "2018-05-29",
"statements": [
"UPDATE <name-of-table> set deleted_at=NOW() WHERE id=:ID",
"SELECT * FROM <name-of-table> WHERE id=:ID and unix_timestamp > $ctx.args.newerThan"
],
variableMap: {
":ID": $ctx.args.id,
## ":TIMESTAMP": $ctx.args.newerThan -- This will be handled as a string!!!
}
}
Requires
Author: Serverless-appsync
Source Code: https://github.com/serverless-appsync/serverless-appsync-simulator
License: MIT License
1598839687
If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?
In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.
Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.
React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.
Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.
Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.
The popularity of React Native comes from its advantages. Some of its advantages are as follows:
Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.
React Native is very close to native. Consider the following aspects as described on the React Native website:
Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.
#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native
1595396220
As more and more data is exposed via APIs either as API-first companies or for the explosion of single page apps/JAMStack, API security can no longer be an afterthought. The hard part about APIs is that it provides direct access to large amounts of data while bypassing browser precautions. Instead of worrying about SQL injection and XSS issues, you should be concerned about the bad actor who was able to paginate through all your customer records and their data.
Typical prevention mechanisms like Captchas and browser fingerprinting won’t work since APIs by design need to handle a very large number of API accesses even by a single customer. So where do you start? The first thing is to put yourself in the shoes of a hacker and then instrument your APIs to detect and block common attacks along with unknown unknowns for zero-day exploits. Some of these are on the OWASP Security API list, but not all.
Most APIs provide access to resources that are lists of entities such as /users
or /widgets
. A client such as a browser would typically filter and paginate through this list to limit the number items returned to a client like so:
First Call: GET /items?skip=0&take=10
Second Call: GET /items?skip=10&take=10
However, if that entity has any PII or other information, then a hacker could scrape that endpoint to get a dump of all entities in your database. This could be most dangerous if those entities accidently exposed PII or other sensitive information, but could also be dangerous in providing competitors or others with adoption and usage stats for your business or provide scammers with a way to get large email lists. See how Venmo data was scraped
A naive protection mechanism would be to check the take count and throw an error if greater than 100 or 1000. The problem with this is two-fold:
skip = 0
while True: response = requests.post('https://api.acmeinc.com/widgets?take=10&skip=' + skip), headers={'Authorization': 'Bearer' + ' ' + sys.argv[1]}) print("Fetched 10 items") sleep(randint(100,1000)) skip += 10
To secure against pagination attacks, you should track how many items of a single resource are accessed within a certain time period for each user or API key rather than just at the request level. By tracking API resource access at the user level, you can block a user or API key once they hit a threshold such as “touched 1,000,000 items in a one hour period”. This is dependent on your API use case and can even be dependent on their subscription with you. Like a Captcha, this can slow down the speed that a hacker can exploit your API, like a Captcha if they have to create a new user account manually to create a new API key.
Most APIs are protected by some sort of API key or JWT (JSON Web Token). This provides a natural way to track and protect your API as API security tools can detect abnormal API behavior and block access to an API key automatically. However, hackers will want to outsmart these mechanisms by generating and using a large pool of API keys from a large number of users just like a web hacker would use a large pool of IP addresses to circumvent DDoS protection.
The easiest way to secure against these types of attacks is by requiring a human to sign up for your service and generate API keys. Bot traffic can be prevented with things like Captcha and 2-Factor Authentication. Unless there is a legitimate business case, new users who sign up for your service should not have the ability to generate API keys programmatically. Instead, only trusted customers should have the ability to generate API keys programmatically. Go one step further and ensure any anomaly detection for abnormal behavior is done at the user and account level, not just for each API key.
APIs are used in a way that increases the probability credentials are leaked:
If a key is exposed due to user error, one may think you as the API provider has any blame. However, security is all about reducing surface area and risk. Treat your customer data as if it’s your own and help them by adding guards that prevent accidental key exposure.
The easiest way to prevent key exposure is by leveraging two tokens rather than one. A refresh token is stored as an environment variable and can only be used to generate short lived access tokens. Unlike the refresh token, these short lived tokens can access the resources, but are time limited such as in hours or days.
The customer will store the refresh token with other API keys. Then your SDK will generate access tokens on SDK init or when the last access token expires. If a CURL command gets pasted into a GitHub issue, then a hacker would need to use it within hours reducing the attack vector (unless it was the actual refresh token which is low probability)
APIs open up entirely new business models where customers can access your API platform programmatically. However, this can make DDoS protection tricky. Most DDoS protection is designed to absorb and reject a large number of requests from bad actors during DDoS attacks but still need to let the good ones through. This requires fingerprinting the HTTP requests to check against what looks like bot traffic. This is much harder for API products as all traffic looks like bot traffic and is not coming from a browser where things like cookies are present.
The magical part about APIs is almost every access requires an API Key. If a request doesn’t have an API key, you can automatically reject it which is lightweight on your servers (Ensure authentication is short circuited very early before later middleware like request JSON parsing). So then how do you handle authenticated requests? The easiest is to leverage rate limit counters for each API key such as to handle X requests per minute and reject those above the threshold with a 429 HTTP response.
There are a variety of algorithms to do this such as leaky bucket and fixed window counters.
APIs are no different than web servers when it comes to good server hygiene. Data can be leaked due to misconfigured SSL certificate or allowing non-HTTPS traffic. For modern applications, there is very little reason to accept non-HTTPS requests, but a customer could mistakenly issue a non HTTP request from their application or CURL exposing the API key. APIs do not have the protection of a browser so things like HSTS or redirect to HTTPS offer no protection.
Test your SSL implementation over at Qualys SSL Test or similar tool. You should also block all non-HTTP requests which can be done within your load balancer. You should also remove any HTTP headers scrub any error messages that leak implementation details. If your API is used only by your own apps or can only be accessed server-side, then review Authoritative guide to Cross-Origin Resource Sharing for REST APIs
APIs provide access to dynamic data that’s scoped to each API key. Any caching implementation should have the ability to scope to an API key to prevent cross-pollution. Even if you don’t cache anything in your infrastructure, you could expose your customers to security holes. If a customer with a proxy server was using multiple API keys such as one for development and one for production, then they could see cross-pollinated data.
#api management #api security #api best practices #api providers #security analytics #api management policies #api access tokens #api access #api security risks #api access keys
1678161059
Learn how to set up user authentication in React using Appwrite and the GraphQL API. Learn how to use Appwrite Web SDK to interact with Appwrite’s new Graphql API to set up user authentication in a React application.
User authentication is an essential part of any web application, and setting it up can be a daunting task for many developers. However, with the help of Appwrite, this process can become much easier and more streamlined.
This tutorial will cover how to use Appwrite Web SDK to interact with Appwrite’s new Graphql API to set up user authentication in a React application. We will discuss how to implement signup functionality, handle user login and logout, and implement an email verification feature.
Table of contents:
Profile
componentTo follow along with this tutorial, you should have a basic understanding of React and its concepts. This tutorial also requires a basic understanding of GraphQL, including how to write queries and mutations.
So, let’s get started!
In this blog, we will be discussing how to use Appwrite to implement user authentication in your React application easily. But before diving into the details, let’s briefly discuss what Appwrite is.
Appwrite is an open source, self-hosted, backend-as-a-service platform. It provides all the core APIs that allow developers to easily manage and interact with various services, such as user authentication, database management, and file storage.
By using Appwrite, developers can focus on building their core application logic while leaving the backend infrastructure to Appwrite.
The first step in setting up Appwrite is to install it using Docker. To do so, you need to have the Docker CLI installed on your host machine. Then, you can run one of the following commands according to your OS to install Appwrite.
Before running the command, make sure Docker is running on your machine.
To install Appwrite on a Mac or Linux device, use the following command:
docker run -it --rm \
--volume /var/run/docker.sock:/var/run/docker.sock \
--volume "$(pwd)"/appwrite:/usr/src/code/appwrite:rw \
--entrypoint="install" \
appwrite/appwrite:1.2.0
To install Appwrite on a Windows device, run the following command using Command Prompt:
docker run -it --rm ^
--volume //var/run/docker.sock:/var/run/docker.sock ^
--volume "%cd%"/appwrite:/usr/src/code/appwrite:rw ^
--entrypoint="install" ^
appwrite/appwrite:1.2.0
After running the command, you will be prompted with a series of configuration questions. These questions will ask for information such as the HTTP port, hostname, and other settings. You can choose the default options by pressing the enter key or modify the options if you prefer.
For more detailed instructions on installing Appwrite, you can refer to the official installation documentation on the Appwrite website.
Now that you have Appwrite installed and running on your machine, you can access the Appwrite console by navigating to http://localhost.
You will be prompted to create a new account. This account will be used to access the Appwrite console and manage your projects and services.
To create a project, click the “Create Project” button on the Appwrite dashboard, enter the project name, and click “Create.”
Once you have created a project, you will need to add a web platform to your project to init the Appwrite SDK and interact with the Appwrite APIs. You can do this by clicking the “Web App” button on the Appwrite console.
You will be prompted to enter a project name and hostname. For development purposes, you can use localhost
as your hostname. Once you have added the web platform, you will be able to use the Appwrite SDK to interact with the Appwrite services.
To get started quickly, I have created a starter code repository that contains all the necessary code. To clone the starter code, open up a terminal and run the following command:
git clone https://github.com/rishipurwar1/appwrite-graphql-authentication.git
Once you have cloned the starter code repository, you will find all the components
inside the src/components
folder. These components include:
Navbar.js
— responsible for displaying the navbar at the top of the applicationHome.js
— the main landing page of the sample applicationLogin.js
— contains the code for the login formSignup.js
— contains the code for the signup formProfile.js
— contains the code for the profile pageIn addition to the components mentioned earlier, the starter code repository also includes the routing setup for React Router in the src/App.js
file. For example, the /
URL is mapped to the Home
component, the /login
URL is mapped to the Login
component, and so on.
You will also find the CSS code in the src/App.css
file for all the components, which is imported into the App.js
file.
After cloning the starter code repository, you must install all the dependencies before running the application. To do this, you need to navigate to the appwrite-graphql-authentication
directory and run the following command:
npm install
Once the dependencies are installed, you can run the application by using the command:
npm start
This command will start the application, which you can access by navigating to http://localhost:3000 in your web browser.
Now that our sample application is up and running, we can proceed to install the appwrite
package in order to interact with Appwrite services using the Appwrite Web SDK easily. To do this, install the appwrite
package by running the following command:
npm install appwrite
Once the package is installed, create an appwrite
folder inside the src
folder, and inside it, create a config.js
file. This file will be used to import and initialize the Appwrite SDK.
In the config.js
file, you can import the Appwrite modules and initialize the Appwrite SDK by adding the following code to the file:
import { Client, Graphql } from "appwrite";
// initialize SDK
const client = new Client();
client
.setEndpoint("YOUR_API_ENDPOINT") // Replace this
.setProject("YOUR_PROJECT_ID"); // Replace this
export const graphql = new Graphql(client);
Make sure to replace “YOUR_API_ENDPOINT” and “YOUR_PROJECT_ID” with your project’s API endpoint and project ID. You can find this information on your Appwrite project settings page:
In the last line of the code, we created and exported the graphql
instance we will use it in other components to interact with the Appwrite Graphql API.
In this section, we will implement the signup functionality for our React application. To do this, we will create a custom Hook, which will contain functions for login
, signup
, and logout
actions. This Hook will also have one state variable to keep track of the logged-in user.
By creating a custom Hook, we can easily manage the state and functionality related to user authentication in one place. This will make it easy to reuse the code across different components and keep the application organized.
Now, let’s create a hooks
folder inside the src
folder, then create a useAuth.js
file. At the top of this file, import graphql
from the config.js
. You will then need to create a useAuth
function by adding the following code:
import { graphql } from "../appwrite/config";
const useAuth = () => {
// useAuth hook code goes here
};
export default useAuth;
Let’s create a signup
function inside the useAuth
. We can do that by adding the following code:
import { graphql } from "../appwrite/config";
const useAuth = () => {
// sign up functionality
const signup = async (email, password, username) => {
const response = await graphql.mutation({
query: `mutation (
$email: String!,
$password: String!,
$name: String
) {
accountCreate(
userId: "unique()",
email: $email,
password: $password,
name: $name
) {
_id
}
}`,
variables: {
email: email,
password: password,
name: username,
},
});
if (response.errors) {
throw response.errors[0].message;
}
};
return {
signup,
};
};
export default useAuth;
The signup
function we created in the code above takes in three parameters — email
, password
, and username
. Inside the function, there is a method called graphql.mutation
that is used to make changes to the data. In this case, the method creates a new account with the provided email, password, and username.
The mutation
method takes in an object that contains two properties — the query
property and the variables
object.
The query
property uses the accountCreate
mutation to create a new user account with the provided email, password, and username.
The variables
object is used to pass the values of the email
, password
, and username
to the accountCreate
mutation dynamically. If the mutation is successful, it will return the _id
of the created account.
The if
block is added to check for any errors while creating the account.
Finally, the Hook returns an object that contains the signup
function, which can be used in other components.
signup
function in our Appwrite projectNow that we have created the signup
function inside our useAuth
hook, we can use it in our Signup
component to create a new account. Before we do that, let me explain the Signup
component code.
In this component, we have two functions — handleChange
and handleSubmit
.
The handleChange
function is used to update the user
state variable with the values entered by the user in the form input fields.
The handleSubmit
function is used to handle the form submission event, and prevent the default form submission behaviour. In this example, this function only logs the user object to the console, but later on, we will use the signup
function to create a new account.
The form has three input fields for email
, username
, and password
. Each input field has the onChange
event that calls the handleChange
function to update the user
state variable with the values entered by the user.
The form
element also has an onSubmit
event that calls the handleSubmit
function when a user clicks the submit button.
Let’s use the signup
function to create a new user account when a user signs up using the Signup
form.
To do this, first, we need to import the useAuth
hook in the Signup
component, then call the useAuth
hook and destructure the signup
function from it. Then, call the signup
function inside the handleSubmit
function with the values of the email
, password
, and username
entered by the user.
Your code should look like this:
import { useState } from "react";
import { Link } from "react-router-dom";
import { useAuth } from "../hooks/useAuth"; // import useAuth
const Signup = () => {
const [user, setUser] = useState({});
const { signup } = useAuth();
const handleChange = (e) => {
setUser({ ...user, [e.target.name]: e.target.value });
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
await signup(user.email, user.password, user.username);
alert("Account created successfully!");
} catch (error) {
console.log(error);
}
};
// rest of the code
}
To test the signup feature, open the signup page of your application. Fill in the form with your email, username, and password. Remember that the password should be at least eight characters long.
Once you have filled in the form, click the “Sign Up” button to submit the form. If the account creation is successful, you should see an alert message. If the account creation fails, an error message will be printed on the console.
You can also verify that the user has been created by checking your Appwrite project dashboard. Log in to your Appwrite account, navigate to the project dashboard, and select the “Auth” tab on the sidebar. Here, you will be able to see the new user account that you just created:
Congratulations! You have successfully implemented signup functionality in your React application using Appwrite.
To implement login functionality in our React app with Appwrite, we will follow a similar approach as we did for the signup functionality. First, create a login
function inside the useAuth
hook by adding the following code:
import { graphql } from "../appwrite/config";
const useAuth = () => {
const signup = async (email, password, username) => {
// signup function code
};
const login = async (email, password) => {
const response = await graphql.mutation({
query: `mutation (
$email: String!,
$password: String!,
) {
accountCreateEmailSession(
email: $email,
password: $password,
) {
_id
}
}`,
variables: {
email: email,
password: password,
},
});
if (response.errors) {
throw response.errors[0].message;
}
};
return {
signup,
login, // return it
};
};
export default useAuth;
The above query property uses the accountCreateEmailSession
mutation to allow users to log in to their accounts by providing a valid email and password. This will create a new session for the user.
login
function in our Appwrite projectLet’s import the useAuth
hook in the Login.js
file and call it inside the Login
component. Then, destructure the login
function from the useAuth
hook. Finally, call the login
function inside the handleSubmit
function, passing in the values of the email
and password
entered by the user.
The code should look similar to this:
import { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import useAuth from "../hooks/useAuth";
const Login = () => {
const [user, setUser] = useState({});
const navigate = useNavigate();
const { login } = useAuth();
const handleChange = (e) => {
setUser({ ...user, [e.target.name]: e.target.value });
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
await login(user.email, user.password);
navigate("/profile");
} catch (error) {
console.log(error);
}
};
// rest of the code
};
export default Login;
To test the login feature, open the login page of your application. Fill in the form with your email and password. Once you have filled in the form, click the “Log In” button to submit the form.
If the login is successful, the user will be navigated to the /profile
page. If the login fails, an error message will be printed on the console.
Currently, the information displayed on the profile page is hardcoded, but we will make it dynamic by fetching the logged-in user’s data using the Appwrite API in the next section.
In this section, I will show you how to fetch a logged-in user’s data and display it on the Profile
component. First, let’s create a user state using the useState
Hook in the useAuth
hook and set it to null
:
import { useState } from "react"; // import useState
const useAuth = () => {
const [user, setUser] = useState(null); // create a user state
// rest of the code
}
Next, we will create the getCurrentUser
function inside the useAuth
Hook. The getCurrentUser
function uses the accountGet
query provided by the Appwrite GraphQL API to fetch the currently logged-in user’s data.
Below is the code for the getCurrentUser
function:
const getCurrentUser = async () => {
const response = await graphql.query({
query: `query {
accountGet {
_id
name
emailVerification
email
}
}`,
});
return response.data.accountGet;
};
As you can see, this query returns an object that contains the user’s ID, name, email address, and email verification status.
Next, we will use the useEffect
Hook to call the getCurrentUser
function and update the user
state with the returned data.
Finally, we will return the user
state from the useAuth
hook so it can be accessed in other components.
Your useAuth
code should look like this:
import { useEffect, useState } from "react"; // import useEffect
import { graphql } from "../appwrite/config";
const useAuth = () => {
const [user, setUser] = useState(null);
const signup = async (email, password, username) => {
// signup code
};
const login = async (email, password) => {
// login code
};
const getCurrentUser = async () => {
// getCurrentUser code
};
// fetching the logged user data
useEffect(() => {
const fetchUser = async () => {
const userDetails = await getCurrentUser();
setUser(userDetails);
};
fetchUser();
}, []);
return {
signup,
login,
user, // return it
};
};
export default useAuth;
Profile
componentIn the Profile
component, you can import the useAuth
hook and destructure the user
state. Then, you can use the user
data to display the user’s name, email, and other information on the profile page.
Below is the updated code for the Profile
component:
import useAuth from "../hooks/useAuth"; // import useAuth
const Profile = () => {
const { user } = useAuth(); // destructure user
return (
<div className="profile">
<h1 className="name">Welcome, {user?.name}</h1>
<h2 className="email">Email: {user?.email}</h2>
</div>
);
};
export default Profile;
Once you have updated the code, you should see the currently logged-in user’s name and email displayed on the /profile
page:
To implement logout functionality in our React app with Appwrite, first create a logout
function inside the useAuth
Hook by adding the following code:
const logout = async () => {
const response = await graphql.mutation({
query: `mutation {
accountDeleteSession(
sessionId: "current"
) {
status
}
}`,
});
if (response.errors) {
throw response.errors[0].message;
}
};
As you can see, the accountDeleteSession
mutation takes in the “current” as the session ID, which logs out the currently logged-in user from the current device session.
Finally, we will return the logout
function from the useAuth
hook so it can be accessed in other components.
Your useAuth
code should look like this:
import { useEffect, useState } from "react";
import { graphql } from "../appwrite/config";
const useAuth = () => {
const [user, setUser] = useState(null);
const signup = async (email, password, username) => {
// signup code
};
const login = async (email, password) => {
// login code
};
const getCurrentUser = async () => {
// getCurrentUser code
};
// logout function
const logout = async () => {
// logout code
};
useEffect(() => {
// code
}, []);
return {
signup,
login,
logout, // return logout
user
};
};
export default useAuth;
Let’s import the useAuth
hook in the Profile.js
file and call it inside the Profile
component. Then, destructure the logout
function from the useAuth
hook.
Next, create a handleLogout
function inside the Profile
component by adding the following code:
const handleLogout = async () => {
try {
await logout();
navigate("/login");
} catch (error) {
console.log(error);
}
};
Finally, add an onClick
event listener to the “Log Out” button. Your Profile
component code should look like this:
import { useNavigate } from "react-router-dom"; // import useNavigate
import useAuth from "../hooks/useAuth";
const Profile = () => {
const { logout, user } = useAuth();
const navigate = useNavigate();
const handleLogout = async () => {
try {
await logout();
navigate("/login");
} catch (error) {
console.log(error);
}
};
return (
<div className="profile">
<h1 className="name">Welcome, {user?.name}</h1>
<h2 className="email">Email: {user?.email}</h2>
<button className="logOut-btn" onClick={handleLogout}>
Log Out
</button>
</div>
);
};
export default Profile;
To test the logout
feature, open the profile page and click the “Log Out” button. If the logout action is successful, the user will be redirected to the /login
page. If the logout action fails, an error message will be printed on the console.
In this section, we will learn how to implement email verification functionality in our application using Appwrite’s GraphQL API. To verify the user’s email address, we need to accomplish two steps:
But before we begin, it is important to note that in order to send verification emails, we will need to set up a third-party SMTP provider such as SendGrid or MailGun. For this tutorial, we will be using MailGun.
To set up MailGun, first go to the MailGun website and sign up for a free account. After signing up, you will be taken to the dashboard, where you need to verify your email address by following MailGun’s instructions.
After that, select the “SMTP” option on the “Overview” page. Here, you’ll find your SMTP credentials such as hostname, port, username, and password:
.env
file with your SMTP credentialsNow, open the appwrite
folder that was created when you installed Appwrite, not the one that we created inside the project folder. Inside this folder, you will find a file named .env
that needs to be updated with your SMTP credentials.
Open the .env
file and update the following fields with the respective information for your project:
_APP_SMTP_HOST
— your SMTP hostname_APP_SMTP_PORT
— your SMTP port_APP_SMTP_SECURE
— SMTP secure connection protocol (you can set it to ‘tls’ if running on a secure connection)_APP_SMTP_USERNAME
— your SMTP username_APP_SMTP_PASSWORD
— your SMTP password_APP_SYSTEM_EMAIL_ADDRESS
— your SMTP email addressOnce you have updated the .env
file, save it and restart your Appwrite server by running the following command:
docker compose up -d
Now that we have set up the SMTP configuration, we can move on to implementing the email verification feature.
Create a sendVerificationEmail
function inside the useAuth
Hook by using the following code:
const useAuth = () => {
// other functions and state
const sendVerificationEmail = async () => {
const response = await graphql.mutation({
query: `mutation {
accountCreateVerification(
url: "http://localhost:3000/profile"
) {
_id
_createdAt
userId
secret
expire
}
}`,
});
if (response.errors) {
throw response.errors[0].message;
}
};
return {
signup,
login,
logout,
user,
sendVerificationEmail // return this
};
};
This function will be responsible for sending verification emails. Note that the accountCreateVerification
mutation in this function takes in a url
property, which is the URL that the user will be redirected to after they click on the verification link sent to their email address.
Before we use this function, it is important to note that you can only send verification emails after creating a login session for the user. To do that, you need to call the login
function right after calling the signup
function in the handleSubmit
function of the Signup
component, like this:
const Signup = () => {
const [user, setUser] = useState({});
const { signup, login } = useAuth(); // add login function
const handleChange = (e) => {
setUser({ ...user, [e.target.name]: e.target.value });
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
await signup(user.email, user.password, user.username);
await login(user.email, user.password); // call login function
alert("Account created successfully!");
} catch (error) {
console.log(error);
}
};
// rest of the code
};
Let’s call the sendVerificationEmail
function after the login
function call to send verification emails:
const Signup = () => {
const [user, setUser] = useState({});
const { signup, login, sendVerificationEmail } = useAuth(); // add sendVerificationEmail function
const handleChange = (e) => {
setUser({ ...user, [e.target.name]: e.target.value });
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
await signup(user.email, user.password, user.username);
await login(user.email, user.password);
await sendVerificationEmail(); // call sendVerificationEmail function
alert("Account created and verification email sent successfully!");
} catch (error) {
console.log(error);
}
};
// rest of the code
};
To test this feature, go ahead and sign up for an account in your app using the email that you verified on MailGun. You should receive a verification link in your email. Be sure to check your spam folder as well:
In the verification link you receive, you’ll see userId
and secret
parameters attached. We’ll use these parameters to make another API request to verify the user’s email address. Let’s create a function for that in the useAuth
hook by using the following code:
const useAuth = () => {
// other functions and state
const confirmEmailVerification = async (userId, secret) => {
const response = await graphql.mutation({
query: `mutation (
$userId: String!,
$secret: String!,
) {
accountUpdateVerification(
userId: $userId,
secret: $secret
) {
_id
}
}`,
variables: {
userId: userId,
secret: secret,
},
});
if (response.errors) {
throw response.errors[0].message;
}
};
return {
// rest of the functions and state
confirmEmailVerification
};
};
In the Profile
component, we need to extract the parameters from the redirected URL and pass them to the confirmEmailVerification
function as parameters when the user is on the profile page after redirection. This can be done by using the following code:
import { useNavigate } from "react-router-dom";
import useAuth from "../hooks/useAuth";
const Profile = () => {
const { logout, user, confirmEmailVerification } = useAuth(); // add confirmEmailVerification
// rest of the code
const handleLogout = async () => {
// code
};
const urlParams = new URLSearchParams(window.location.search);
const userId = urlParams.get("userId"); // extract userId
const secret = urlParams.get("secret"); // extract secret
const handleConfirmEmailVerification = async () => {
try {
await confirmEmailVerification(userId, secret);
alert("Email verified successfully!");
navigate("/profile");
} catch (err) {
console.log(err);
}
};
if (!user?.emailVerification && userId && secret) {
handleConfirmEmailVerification();
}
// rest of the code
};
export default Profile;
You should be able to verify the user’s email address. And with that, this tutorial is finished!
This concludes our tutorial on setting up user authentication in React using Appwrite and the GraphQL API. We covered installing and setting up Appwrite, creating a project, implementing signup and login functionality, fetching the logged-in user’s information, and setting up email verification functionality.
I hope you enjoyed this article! Thanks for taking the time to read it. If you have any issues while following the article or have further questions, let me know in the comments section.
If you like what I’m doing here and want to help me keep doing it, don’t forget to hit that share button. Happy coding!
Source: https://blog.logrocket.com
#react #appwrite #graphql
1601381326
We’ve conducted some initial research into the public APIs of the ASX100 because we regularly have conversations about what others are doing with their APIs and what best practices look like. Being able to point to good local examples and explain what is happening in Australia is a key part of this conversation.
The method used for this initial research was to obtain a list of the ASX100 (as of 18 September 2020). Then work through each company looking at the following:
With regards to how the APIs are shared:
#api #api-development #api-analytics #apis #api-integration #api-testing #api-security #api-gateway