@tawasal/node
v0.0.5
Published
tawasal sdk for node js
Downloads
63
Readme
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
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
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
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
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
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.