added jwt token
This commit is contained in:
34
src/trpc.ts
34
src/trpc.ts
@@ -1,6 +1,9 @@
|
||||
import { initTRPC } from "@trpc/server";
|
||||
import type { CreateHTTPContextOptions } from "@trpc/server/adapters/standalone";
|
||||
import { db } from "./db";
|
||||
import * as jwt from "jsonwebtoken";
|
||||
import { Config } from "./config";
|
||||
import { z } from "zod";
|
||||
const t = initTRPC.context<Context>().create();
|
||||
|
||||
export const router = t.router;
|
||||
@@ -35,8 +38,10 @@ type Context = Awaited<ReturnType<typeof createContext>>;
|
||||
|
||||
export const createContext = async (opts: CreateHTTPContextOptions) => {
|
||||
const authorizationHeader = opts.req.headers.authorization || "";
|
||||
|
||||
const bearerToken = authorizationHeader.split(" ")[1];
|
||||
const phone = verifyToken(bearerToken);
|
||||
console.log(authorizationHeader, bearerToken);
|
||||
const phone = await verifyToken(bearerToken);
|
||||
if (phone !== null) {
|
||||
let user = await db.query.user.findFirst({
|
||||
where: (user, { eq }) => eq(user.phone, phone),
|
||||
@@ -53,7 +58,28 @@ export const createContext = async (opts: CreateHTTPContextOptions) => {
|
||||
}
|
||||
};
|
||||
|
||||
function verifyToken(token: string): string | null {
|
||||
//TODO: Implement token verification
|
||||
return "08999";
|
||||
async function verifyToken(token: string): Promise<string | null> {
|
||||
try {
|
||||
let rs = await new Promise((resolve, reject) => {
|
||||
jwt.verify(token, Config.jwt_secret, (err, decoded) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
} else {
|
||||
resolve(decoded);
|
||||
}
|
||||
});
|
||||
});
|
||||
let data = z
|
||||
.object({
|
||||
phone: z.string(),
|
||||
})
|
||||
.safeParse(rs);
|
||||
if (data.success) {
|
||||
return data.data.phone;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user