Back

[SOLVED] How do I get sessionId for api endpoint

  • 0
  • Self Hosted
Binyamin
3 May, 2023, 03:09

You want to be able to set document permission for the current user is that right?

TL;DR
The user was asking for help on how to get the sessionId for an API endpoint. It was determined that in this specific use case, the user doesn't need to use JWT. The solution provided includes code examples for both the client and server-side, using the appwrite SDK. The code logic is explained and changes to the existing code are suggested. The suggested solution involves sending either the JWT or the userID to the backend.
BloodThermic
3 May, 2023, 03:09

yes

BloodThermic
3 May, 2023, 03:10

I am having trouble figuring out how to hand off the info to the server side once its created on the client side

Binyamin
3 May, 2023, 03:10

Then the easiest solution would be send the either the JWT or the userID to the backend. Other option it's only what Steven suggested to fully managed the session in the backend

Binyamin
3 May, 2023, 03:11

Can you show the code example of when you're sending the data from the front to the back?

BloodThermic
3 May, 2023, 03:11

Im using svelte so it weird

Binyamin
3 May, 2023, 03:11

It's a bit different, yes

BloodThermic
3 May, 2023, 03:13

/login/+page.svelte (client Side)

TypeScript
import "../../app.css";
  import loginimg from "$lib/assets/login.jpg";

  import { Client, Account } from "appwrite";
  import { enhance } from "$app/forms";
  import { goto } from "$app/navigation";
  import { accountId } from "$lib/stores.js";
  const client = new Client();
  const accountClient = new Client();
  const account = new Account(client);

  client
    .setEndpoint("http://localhost:3080/v1") // Your API Endpoint
    .setProject("63db6c4c0a25ec0b287d"); // Your project ID

  async function handleSubmit() {
    const createJWT = account.createJWT();
    const formData = new FormData(event.target);
    const email = formData.get("email");
    const password = formData.get("password");

    accountClient
      .setEndpoint("http://localhost:3080/v1")
      .setProject("63db6c4c0a25ec0b287d")
      .setJWT(createJWT);

    const accountDetails = await account.get();
    accountId.set(accountDetails.$id);

    // Form Input

    try {
      const response = await account.createEmailSession(email, password);
      console.log(response); // Success
      goto("/msform");
      return response;
    } catch (error) {
      console.log(error); // Failure
      console.log(email, password);
      throw error;
    }
  }```

/msfrom/+page.server.js (Server Side)

import sdk, { ID } from 'node-appwrite'; import { accountId } from '$lib/stores';

// Init SDK const client = new sdk.Client();

const databases = new sdk.Databases(client);

client .setEndpoint('http://localhost:3080/v1') // Your API Endpoint .setProject('63db6c4c0a25ec0b287d') // Your project ID .setKey(' ') // Your secret API key ;

export const actions = { default: async ({request}) => {

TypeScript
    const fromData = await request.formData();
    const name = fromData.get('name');
    const DOB = fromData.get('DOB');
    const feet = fromData.get('feet');
    const inch = fromData.get('inch');
    const weight = fromData.get('weight');
    const school = fromData.get('school');
    const sport = fromData.get('sport');
    const position = fromData.get('position');
    const age = fromData.get('age');
    const better = fromData.get('better');

    const input = {
        Name: name,
        DOB: DOB,
        Feet: feet,
        Inch: inch,
        Weight: weight,
        School: school,
        Sport: sport,
        Position: position,
        Age: age,
        Better: better
    };

    const promise = databases.createDocument('64502243369b884d71f8', '6450225bbca140600f16', ID.unique(), input, );
    console.log(JSON.stringify(accountId));


}

}```

Binyamin
3 May, 2023, 03:15

Okay, I see

BloodThermic
3 May, 2023, 03:15

I was trying to use svelte stores but it was not working

Binyamin
3 May, 2023, 03:17

You need to change a few thing in your code logic, I can point them to you.

BloodThermic
3 May, 2023, 03:24

Ok

Binyamin
3 May, 2023, 03:24

In the /login/+page.svelte page

  1. You don't need to have more then on client.
  2. account.creaeJWT returns a promise.
  3. account.get will throw error in case the user is not logged in. and in case the user indeed logged in then you don't need to use the createEmailSession function as the user already exist.
  4. the setJWT need to be used only in the server side of the SDK, although you can set it in the client side, it's not necessary as the session will be handled for you.

So this file can be something like this

TypeScript
import "../../app.css";
import loginimg from "$lib/assets/login.jpg";

import {Client, Account} from "appwrite";
import {enhance} from "$app/forms";
import {goto} from "$app/navigation";
import {accountId} from "$lib/stores.js";

const client = new Client();
const accountClient = new Client();
const account = new Account(client);

client
    .setEndpoint("http://localhost:3080/v1") // Your API Endpoint
    .setProject("63db6c4c0a25ec0b287d"); // Your project ID

async function handleSubmit() {
    let userLoggedIn = false;
    try {
        // Get account if logged in
        const accountDetails = await account.get();
        accountId.set(accountDetails.$id);
        userLoggedIn = true;
    } catch (e) {

    }

    if (!userLoggedIn) {
        try {
            const formData = new FormData(event.target);
            const email = formData.get("email");
            const password = formData.get("password");

            const response = await account.createEmailSession(email, password);
            console.log(response); // Success
        } catch (e) {
            console.log(error); // Failure
            console.log(email, password);
            throw error;

        }
    }

    const createJWT = await account.createJWT();

    try {
        goto("/msform");
        return response;
    } catch (error) {
    }
}
Binyamin
3 May, 2023, 03:28

And in your server side

Binyamin
3 May, 2023, 03:28

You can get the user ID also from the form data, and you won't need to use store

TypeScript
import sdk, {ID} from 'node-appwrite';

// Init SDK
const client = new sdk.Client();

const databases = new sdk.Databases(client);

client
    .setEndpoint('http://localhost:3080/v1')
    .setProject('63db6c4c0a25ec0b287d')
    .setKey(''); // Create and API key from the console.

export const actions = {
    default: async ({request}) => {


        const fromData = await request.formData();
        const name = fromData.get('name');
        const DOB = fromData.get('DOB');
        const feet = fromData.get('feet');
        const inch = fromData.get('inch');
        const weight = fromData.get('weight');
        const school = fromData.get('school');
        const sport = fromData.get('sport');
        const position = fromData.get('position');
        const age = fromData.get('age');
        const better = fromData.get('better');

        //TODO: Add the user in the client side
        const userID = fromData.get('user_id');

        const input = {
            Name: name,
            DOB: DOB,
            Feet: feet,
            Inch: inch,
            Weight: weight,
            School: school,
            Sport: sport,
            Position: position,
            Age: age,
            Better: better,
        };

        const promise = databases.createDocument(
            '64502243369b884d71f8',
            '6450225bbca140600f16',
            ID.unique(),
            input,
            [
                Permission.write(Role.user(userID)),
            ]
        );
    }
}
BloodThermic
3 May, 2023, 03:28
Binyamin
3 May, 2023, 03:29

Yes you can use this to check if the user is logged in

BloodThermic
3 May, 2023, 03:30

So I dont need the jwt?

BloodThermic
3 May, 2023, 03:30

to do what I am doing

Binyamin
3 May, 2023, 03:30

In this specific use case you don't have to use the JWT way.

BloodThermic
3 May, 2023, 03:41

So I have to do now it export it correct? to the serverside?

Binyamin
3 May, 2023, 03:41

I think so, yes

BloodThermic
3 May, 2023, 22:21

@Steven This is solved thank you

Drake
3 May, 2023, 22:36

FYI, you can update the post title to prefix with [SOLVED]

Drake
3 May, 2023, 22:47

[SOLVED] How do I get sessionId for api endpoint

Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more