Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

doc: implemented Appwrite auth functionalities with Vuejs #301

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/routes/docs/tutorials/vue-auth/+layout.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<script lang="ts">
import { globToTutorial } from '$lib/utils/tutorials.js';
import { setContext } from 'svelte';

export let data;
const tutorials = globToTutorial(data);
setContext('tutorials', tutorials);
</script>

<slot />
11 changes: 11 additions & 0 deletions src/routes/docs/tutorials/vue-auth/+layout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import type { LayoutLoad } from './$types';

export const load: LayoutLoad = ({ url }) => {
const tutorials = import.meta.glob('./**/*.markdoc', {
eager: true
});
return {
tutorials,
pathname: url.pathname
};
};
6 changes: 6 additions & 0 deletions src/routes/docs/tutorials/vue-auth/+page.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { redirect } from '@sveltejs/kit';
import type { PageLoad } from './$types';

export const load: PageLoad = async () => {
throw redirect(303, '/docs/tutorials/vue-auth/step-1');
};
20 changes: 20 additions & 0 deletions src/routes/docs/tutorials/vue-auth/step-1/+page.markdoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
layout: tutorial
title: Authentication with Vue
description: Add Authentication to a Vue project using Appwrite.
step: 1
difficulty: intermediate
readtime: 40
---
## Appwrite: The backend you'll never have to build or maintain.
Copy link
Contributor

@gewenyu99 gewenyu99 Oct 31, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please follow convention from other published tutorials for what should be in this first page.

I understand you followed the auth deep dive we have, but that is still a draft. This page should be more similar to /tutorials/sveltekit


Appwrite is a self-hosted backend platform that takes away the stress of building and maintaining a backend. With Appwrite, you can implement authentication, databases, file storage, and real-time events with secure APIs out of the box.

This means that you can focus on what you do best: building great Vue apps. You don't have to worry about managing servers, databases, or security. Appwrite takes care of all that for you. Even if you're a beginner, you can get started with Appwrite and Vue in no time.


## Before you start

Even if you've never tried Appwrite, you will get an idea of what it'll feel like to build with Vue and Appwrite.

If you're inspired and wish to follow along, make sure you've followed [Start with Vue](https://appwrite.io/docs/quick-starts/vue) first and can later jump onto this tutorial.
22 changes: 22 additions & 0 deletions src/routes/docs/tutorials/vue-auth/step-10/+page.markdoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
---
layout: tutorial
title: Next steps
description: View your Vue.js app build on Appwrite Cloud.
step: 10
---

# Test your project {% #test-project %}
Run your project with `npm run dev` and open the URL that comes up on the terminal.


# Play with your project {% #play-project %}

Try to implement `validations` to input, make use of `phone verification`.

# Use Appwrite{% #make-project %}

Use appwrite in your projects and explore other amazing features that appwrite provides such as

- Databases
- Functions
- Storage
52 changes: 52 additions & 0 deletions src/routes/docs/tutorials/vue-auth/step-2/+page.markdoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
---
layout: tutorial
title: Create project
description: Add Authentication to a Vue project using Appwrite.
step: 2
---

# Create Vue Project

You can create a Vue project using [Vue](https://vuejs.org/guide/quick-start.html).
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing headings


```sh
npm create vue@latest
```

This command will install and execute [create-vue](https://github.com/vuejs/create-vue), the official Vue project scaffolding tool. You will be presented with prompts for several optional features such as TypeScript and testing support:

The prompt will be something similar to this.

```sh
✔ Project name: … <your-project-name>
✔ Add TypeScript? … No / Yes
✔ Add JSX Support? … No / Yes
✔ Add Vue Router for Single Page Application development? … No / Yes
✔ Add Pinia for state management? … No / Yes
✔ Add Vitest for Unit testing? … No / Yes
✔ Add an End-to-End Testing Solution? … No / Cypress / Playwright
✔ Add ESLint for code quality? … No / Yes
✔ Add Prettier for code formatting? … No / Yes

Scaffolding project in ./<your-project-name>...
Done.
```
For this project we will be using Vue router and Pinia. So, make sure to check **yes** for these.

After the prompt is finished, you can head over to the newly create project.

```sh
cd vue_appwrite
npm install
npm run dev
```

After running all these commands, you will be able to access you Vue app.

## Adding Appwrite to Your Vue App
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Headings should be sentence case.

Missing {% #id %} tags


Appwrite provides a Web SDK that can be used in your Vue apps. You can use Appwrite by installing the Web SDK as an NPM package.

```sh
npm install appwrite
```
64 changes: 64 additions & 0 deletions src/routes/docs/tutorials/vue-auth/step-3/+page.markdoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
---
layout: tutorial
title: Initialize SDK
description: Import and configure a project with Appwrite Cloud and Vue.js.
step: 3
---

# Create project {% #create-project %}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we just reuse step 2-3 from the vue tutorial. They don't need to be different other than description.


Head to the [Appwrite Console](https://cloud.appwrite.io/console).

{% only_dark %}
![Create project screen](/images/docs/quick-starts/dark/create-project.png)
{% /only_dark %}
{% only_light %}
![Create project screen](/images/docs/quick-starts/create-project.png)
{% /only_light %}

If this is your first time using Appwrite, create an account and create your first project.

Then, under **Add a platform**, add a **Web app**. The **Hostname** should be localhost.

{% only_dark %}
![Add a platform](/images/docs/quick-starts/dark/add-platform.png)
{% /only_dark %}
{% only_light %}
![Add a platform](/images/docs/quick-starts/add-platform.png)
{% /only_light %}

You can skip optional steps.

# Initialize Appwrite SDK {% #init-sdk %}

To use Appwrite in our Vue app, we'll need to find our project ID. Find your project's ID in the **Settings** page.

{% only_dark %}
![Project settings screen](/images/docs/quick-starts/dark/project-id.png)
{% /only_dark %}
{% only_light %}
![Project settings screen](/images/docs/quick-starts/project-id.png)
{% /only_light %}
Create a new file `src/lib/appwrite.js` to hold our Appwrite related code.
Only one instance of the `Client()` class should be created per app.
Add the following code to it, replacing `<YOUR_PROJECT_ID>` with your project ID.

Before you can use Appwrite, you need to instanciate the Appwrite `Client` class with the project ID and endpoint.
This tells the SDK where your Appwrite project is hosted and which one to connect to.

The client is then used to initialize services like `Databases` and `Account`, so they all point to the same Appwrite project.

You can do this by instantiating the services you need in a file like `src/lib/appwrite.js` and **exporting the instances**.

```js
import { Client, Databases, Account } from "appwrite";

const client = new Client();
client
.setEndpoint("https://cloud.appwrite.io/v1")
.setProject("<YOUR_PROJECT_ID>"); // Replace with your project ID

export const account = new Account(client);
export const databases = new Databases(client);
```
You can get the values for these variables from the Appwrite console's **Settings** page.
182 changes: 182 additions & 0 deletions src/routes/docs/tutorials/vue-auth/step-4/+page.markdoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
---
layout: tutorial
title: Check if logged in
description: Setting up a pinia store, a navigation bar for ease of navigation and routes using vue-router
step: 4
---

# Auth store {% #auth-store %}

Since, we chose pinia for state management during the installatin process. So, we have already setuped our store.
Now, We just need to declare state(data that user will have), actions (fetching of information for appwrite). We will discuss about these as we go.

```js
import { defineStore } from 'pinia';
import { ID } from 'appwrite';
import { account } from '../lib/appwrite.js';

export const useAuthenticationStore = defineStore('auth', {
state: () => ({
email: '',
password: '',
name: '',
user: {},
isAuthenticated: false,
isVerified: false,
}),
actions: {
async login() {
const loginResponse = await account.createEmailSession(this.email, this.password);
this.isAuthenticated = true;
},
async logout() {
await account.deleteSession("current");
this.user = null;
this.isAuthenticated = false;
},
async register() {
const registerResponse = await account.create(ID.unique(), this.email, this.password, this.name);
alert("Account Created and verification send")
this.user = registerResponse;
},
async getUser() {
this.user = await account.get();
this.isVerified = this.user.emailVerification;
},
async verifyUser(){
const verfication = await account.createVerification('http://localhost:5174/verify')
},
async confirmVerification(id, secret){
const confirResponse = await account.updateVerification(id, secret)
},
async UpdatePassword(email){
const update = await account.createRecovery(email, 'http://localhost:5174/forgot')
},
async UpdatePasswordConfirm(id,secret, password, passwordAgain){
const confirResponse = await account.updateRecovery(id, secret, password, passwordAgain)
}
},
});
```
Now, we can import the `auth` store in any component and use it to login, logout, verify user, recover password or register a user.

Here, we have declared all the actions that we will require in order to achieve the following things:
- `Log in`
- `Register up`
- `Logout`
- `Get user data`
- `Verify user`
- `Password Recovery`

We will be going through each of them as we move forward in the tutorial.

# Basic Navigation {% #basic-navigation %}

In `src/components` create a file called `Navbar.vue`, we will be using this in `src/App.vue` for ease of navigation.

```html
<template>
<header>
<h2>
Auth App 🗝️
</h2>
<nav>
<RouterLink to="/">Home</RouterLink>
<RouterLink v-if="isAuthenticated" to="/dashboard">Dashboard</RouterLink>
<RouterLink v-if="isAuthenticated" to="/login">Login/Register</RouterLink>
<button v-if="isAuthenticated" @click="logout()" >Logout</button>
</nav>
</header>
</template>
```
Above we are using Use the `isAuthenticated` computed property to conditionally render the Dashboard and Login/Register route links. We also have a `logout` button which utilizes the `logout action` in the auth store.

We maintain the `isAuthenticated` state in our store to enable navigation guards.

```js
<script>
import {computed, ref} from 'vue'
import { useAuthenticationStore } from '@/stores/auth.js';
import { useRouter } from 'vue-router';

export default {

components:{
Button
},
setup() {
const authenticationStore = useAuthenticationStore();
const router = useRouter();
return {
isAuthenticated: computed(() => authenticationStore.isAuthenticated),
async logout() {
await authenticationStore.logout();
},
};
},
};
</script>
```
In the script we are using `authenticationStore` and using `isAuthenticated` state.

Also, we have a logout function that will be visible only if user is logged in. This logout function is calling the `logout action` declared in our store, which will logout our user from the app.

Below is how our `src/App.vue` will look. We have a navbar and `RouterView` which renders our views/pages.

```js
<script setup>
import Navbar from './components/Navbar.vue';
</script>
```
```html
<template>
<Navbar />
<RouterView />
</template>
```

# Home page {% #home-page %}

`src/views` folder will contain all the pages that we will have in our app.

Create a new file `src/views/Home.vue` and add the following code to it.

```html
<template>
<div class="Home">
<div class="Intro">
<h2>Welcome to the Auth App 🚀</h2>
<p>Here, you will deep dive into Authenticatin with Vue using Appwrite.Appwrite is a self-hosted backend platform
that takes away the stress of building and maintaining a backend. With Appwrite, you can implement authentication,
databases, file storage, and real-time events with secure APIs out of the box.</p>
<br>
<p>This means that you can focus on what you do best: building great Vue apps. You don't have to worry about managing servers, databases, or security. Appwrite takes care of all that for you.
</p>
<br>
</div>
<RouterLink class="link" to="/login">
<button> Get started</button>
</RouterLink>
</div>
</template>
```

In the above code we have some introduction and a link to `/login` route where our login form is present.

# Routes {% #Routes %}

Last setup, we require is to setup the routes using the `vue-router`. The routes `index.js` file is present in `src/router` folder.

Now, add the code from this [index.js](https://gist.github.com/Vaibhav91one/02a2bc139625b985cc597c9fb0e7156e) file.

The code above is a `Vue Router` configuration that defines the routes for your application and a navigation guard that prevents users from accessing protected routes if they are not authenticated.

We will be having the following routes:

- `home`: This is the home page of your application. It is accessible to all users.
- `dashboard`: This is a protected route that is only accessible to authenticated users.
- `verify`: This route is used to verify the user's email address.
- `login`: This route is used to log the user in, registering and password recovery.
- `forgot`: This route is used to reset the user's password.
- `/:pathMatch(.*)*`: This is a catch-all route that matches any URL that does not match another route. It redirects the user to the home page.

Loading