npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@tawasal/node

v0.0.5

Published

tawasal sdk for node js

Downloads

63

Readme

npm npm Bundle Size Bundle Size

This SDK provides functionalities to interact with the Tawasal SuperApp from a Node.js environment. The SDK allows you to extract user information, authorization tokens, and device tokens from cookies.

Installation

npm i @tawasal/node

Usage

Cookie

getUser(cookie: object): User

This function extracts and decodes the user information from a provided cookie.

  • Parameters:
    • cookie: An raw string representing the cookie from which user information is to be extracted.
  • Returns: An object containing the user information.

Example:

import { getUser } from '@tawasal/node';

const user = getUser(req.cookies.get("tawasal"));
console.log(user);

getAuthorization(cookie: object)

This function generates an authorization token from the provided cookie.

  • Parameters:
    • cookie: An raw string representing the cookie from which the authorization token is to be extracted.
  • Returns: A base64 encoded string representing the authorization token, or null if the token is not available.

Example:

import { getAuthorization } from '@tawasal/node';

const authToken = getAuthorization(req.cookies.get("tawasal"));
console.log(authToken);

getDeviceToken(cookie: object)

This function extracts the device token from the provided cookie.

  • Parameters:
    • cookie: An raw string representing the cookie from which the device token is to be extracted.
  • Returns: A string representing the device token, or null if the token is not available.

Example:

import { getDeviceToken } from '@tawasal/node';

const deviceToken = getDeviceToken(req.cookies.get("tawasal"));
console.log(deviceToken);

checkSignature( userId: number, authKeyId: string, deviceToken: string, signatureBase64: string, publicKey: string)

This function verifies user.

  • Parameters:
    • userId: id of the tawasal user,
    • authKeyId: key of authorisation, second part of user token,
    • deviceToken: the token describing session on given device,
    • signatureBase64: first part od user token,
    • publicKey: the key that will be obtained in Dev Management
  • Returns: A boolean that says if session are legit.

Example:

import { getUser } from "@tawasal/node";
import { cookies } from "next/headers";

const store = cookies();
const cookie = store.get("tawasal");
const tawasal = getUser(cookie.value);
const tawasal = getTawasal();
const rawCookie = getRawCookie();

if (tawasal.userToken) {
    const [signature, auth_key_id, device_token, device_token_expires_at] =
        tawasal.userToken.split(":");

    const result = checkSignature(
        tawasal.userId,
        auth_key_id,
        device_token,
        signature,
        publicKey // obtain in Dev Management,
    );
    console.log(result) // true | false
}

Usage with Different Frameworks

Express.js

check out cookie-parser.

To use the SDK with an Express.js application:

// server.js or index.js
import express from 'express';
import cookieParser from 'cookie-parser';
import { getUser, getAuthorization, getDeviceToken } from '@tawasal/node';

const app = express();
app.use(cookieParser());

app.get('/user', (req, res) => {
  const tawasalCookie = req.cookies.tawasal;
  const user = getUser(tawasalCookie);
  res.json(user);
});

app.get('/auth', (req, res) => {
  const tawasalCookie = req.cookies.tawasal;
  const authToken = getAuthorization(tawasalCookie);
  res.send(authToken);
});

app.get('/device-token', (req, res) => {
  const tawasalCookie = req.cookies.tawasal;
  const deviceToken = getDeviceToken(tawasalCookie);
  res.send(deviceToken);
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Hono.dev

check out hono dev docs.

To use the SDK with Hono

hono/cookie + _middleware flow:

// name/app/routes/_middleware.ts)
import { getCookie } from "hono/cookie";

export default createRoute(async (c, next) => {
  if (!c.get("cookie")) {
    const rawCookie = getCookie(
        c, 
        "tawasal"
    )
    try {
      c.set("cookie", tawasal.getUser(rawCookie));
    } catch (e) {
      console.error(e);
    }
  }
})

Next.js

check out next js docs. To use the SDK with a Next.js

API route:

import { getUser, getAuthorization, getDeviceToken } from '@tawasal/node';

export default function handler(req, res) {
  const user = getUser(req.cookies.tawasal);
  const authToken = getAuthorization(req.cookies.tawasal);
  const deviceToken = getDeviceToken(req.cookies.tawasal);

  res.status(200).json({ user, authToken, deviceToken });
}

next/headers:

import { cookies } from "next/headers";

export default async function Page () {
  const store = cookies();

  return(
        <div>
          {JSON.stringify(getUser(store.get("tawasal").value))}
        </div>
    )
}

NestJS

check out nest js docs.

To use the SDK with a NestJS controller:

import { Controller, Get, Req } from '@nestjs/common';
import { Request } from 'express';
import { getUser, getAuthorization, getDeviceToken } from '@tawasal/node';

@Controller('tawasal')
export class TawasalController {
  @Get('user')
  getUser(@Req() req: Request) {
    return getUser(req.cookies["tawasal"]);
  }

  @Get('auth')
  getAuthorization(@Req() req: Request) {
    return getAuthorization(req.cookies["tawasal"]);
  }

  @Get('device-token')
  getDeviceToken(@Req() req: Request) {
    return getDeviceToken(req.cookies["tawasal"]);
  }
}

Fastify

check out fastify cookie.

To use the SDK with a Fastify application:

import Fastify from 'fastify';
import cookie from '@fastify/cookie';
import { getUser, getAuthorization, getDeviceToken } from '@tawasal/node';

const fastify = Fastify();
fastify.register(cookie);

fastify.get('/user', (request, reply) => {
  const user = getUser(request.cookies.tawasal);
  reply.send(user);
});

fastify.get('/auth', (request, reply) => {
  const authToken = getAuthorization(request.cookies.tawasal);
  reply.send(authToken);
});

fastify.get('/device-token', (request, reply) => {
  const deviceToken = getDeviceToken(request.cookies.tawasal);
  reply.send(deviceToken);
});

fastify.listen(3000, (err, address) => {
  if (err) {
    console.error(err);
    process.exit(1);
  }
  console.log(`Server is running at ${address}`);
});

React Router

check out react router.

To use the SDK with a React Router application:

// src/router.js
import { createBrowserRouter } from 'react-router-dom';
import App from './App';
import UserPage from './pages/UserPage';
import { getUser, getAuthorization } from 'tawasal-superapp-sdk';

// Define loaders
async function userLoader({ request }) {
  const cookies = request.headers.get('Cookie');
  const cookieValue = cookies
          .split('; ')
          .find((row) => row
                  .startsWith('tawasal='))?.split('=')[1];
  const user = getUser(cookieValue);
  const authToken = getAuthorization(cookieValue);
  return { user, authToken };
}

const router = createBrowserRouter([
  {
    path: '/',
    element: <App />,
    children: [
      {
        path: 'user',
        element: <UserPage />,
        loader: userLoader,
      },
    ],
  },
]);
export default router;

License

Distributed under the MIT License. See LICENSE for more information.