diff options
| author | Vidhu Kant Sharma <vidhukant@vidhukant.com> | 2025-04-13 18:26:41 +0530 | 
|---|---|---|
| committer | Vidhu Kant Sharma <vidhukant@vidhukant.com> | 2025-04-13 18:26:41 +0530 | 
| commit | 13bf1d14499e9cbb9d99c8bbc350e3cb5a7a4fd2 (patch) | |
| tree | 3b6a3aba7543f38b142fc4ab52870ad88b46ff99 /src | |
first commit
Diffstat (limited to 'src')
| -rw-r--r-- | src/controller/auth.ts | 117 | ||||
| -rw-r--r-- | src/controller/friend.ts | 110 | ||||
| -rw-r--r-- | src/controller/transaction.ts | 57 | ||||
| -rw-r--r-- | src/controller/user.ts | 40 | ||||
| -rw-r--r-- | src/index.ts | 31 | ||||
| -rw-r--r-- | src/middleware/auth.ts | 34 | ||||
| -rw-r--r-- | src/route/api.ts | 34 | ||||
| -rw-r--r-- | src/route/auth.ts | 27 | ||||
| -rw-r--r-- | src/route/friend.ts | 28 | ||||
| -rw-r--r-- | src/route/transaction.ts | 27 | ||||
| -rw-r--r-- | src/route/user.ts | 25 | ||||
| -rw-r--r-- | src/service/budget.ts | 20 | ||||
| -rw-r--r-- | src/service/friend.ts | 72 | ||||
| -rw-r--r-- | src/service/transaction.ts | 48 | ||||
| -rw-r--r-- | src/service/user.ts | 56 | ||||
| -rw-r--r-- | src/util/auth.ts | 39 | ||||
| -rw-r--r-- | src/util/prisma.ts | 22 | 
17 files changed, 787 insertions, 0 deletions
diff --git a/src/controller/auth.ts b/src/controller/auth.ts new file mode 100644 index 0000000..13196fb --- /dev/null +++ b/src/controller/auth.ts @@ -0,0 +1,117 @@ +/* Financer - Pocket Money Tracker + * Copyright (C) 2025  Vidhu Kant Sharma <vidhukant@vidhukant.com> + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <https://www.gnu.org/licenses/>. + */ + +import { Request, Response } from "express"; +import bcrypt from "bcrypt"; + +import { create, readByEmail, readById } from "../service/user"; +import { getAccessToken, getRefreshToken, verifyRefreshToken } from "../util/auth"; + +const signup = async (req: Request, res: Response) => { +    bcrypt.hash(req.body.password, 10, async (err, hash) => { +        try { +            if (err != undefined) { +                res.status(500).json({ error: "Internal Server Error" }); +                console.error(err); +            } + +            const user = await create({ +                ...req.body, +                "password": hash, +            }); + +            // @ts-ignore +            delete user["password"]; +            // @ts-ignore +            delete user["refreshTokenVersion"] + +            res.status(201).json({ +                user: user, +                accessToken: getAccessToken(user.id), +                refreshToken: getRefreshToken(user.id, user.refreshTokenVersion) +            }); +        } catch (error) { +            res.status(500).json({ error: "Internal Server Error" }); +            console.error(error); +        } +    }); +} + +const login = async (req: Request, res: Response) => { +    try { +        const user = await readByEmail(req.body.email); + +        bcrypt.compare(req.body.password, user.password, (err, isMatch) => { +            if (err != undefined) { +                res.status(500).json({ error: "Internal Server Error" }); +                console.error(err); +            } + +            if (isMatch) { +                // @ts-ignore +                delete user["password"]; +                // @ts-ignore +                delete user["refreshTokenVersion"] + +                res.status(200).json({ +                    user: user, +                    accessToken: getAccessToken(user.id), +                    refreshToken: getRefreshToken(user.id, user.refreshTokenVersion) +                }); +            } else { +                res.status(400).json({ error: "Invalid Credentials" }); +            } +        }) +    } catch (error) { +        res.status(500).json({ error: "Internal Server Error" }); +        console.error(error); +    } +} + +const refresh = async (req: Request, res: Response) => { +    try { +        const claims = verifyRefreshToken(req.body.refreshToken); +        const user = await readById(claims.userId); + +        if (!user) { +            res.status(404).json({ error: "Not Found" }) +        } else { +            // @ts-ignore +            if (claims.version == user.refreshTokenVersion) { +                // @ts-ignore +                res.status(200).json({ accessToken: getAccessToken(user.id), refreshToken: getRefreshToken(user.id, user.refreshTokenVersion) }); +            } else { +                res.status(401).json({ error: "Session Expired" }) +            } +        } +    } catch (error) { +        // @ts-ignore +        switch (error.message) { +            case "invalid signature": +                res.status(401).json({ error: "Invalid Credentials" }); +                break; +            case "jwt expired": +                res.status(401).json({ error: "Token Expired" }); +                break; +            default: +                res.status(500).json({ error: "Internal Server Error" }); +                console.error(error); +        } +    } +} + +export { login, signup, refresh };
\ No newline at end of file diff --git a/src/controller/friend.ts b/src/controller/friend.ts new file mode 100644 index 0000000..e98f1e6 --- /dev/null +++ b/src/controller/friend.ts @@ -0,0 +1,110 @@ +/* Financer - Pocket Money Tracker + * Copyright (C) 2025  Vidhu Kant Sharma <vidhukant@vidhukant.com> + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <https://www.gnu.org/licenses/>. + */ + +import { Request, Response } from "express"; +import { getFriendToken } from "../util/auth"; +import { friend, unfriend, list } from "../service/friend"; +import jwt from "jsonwebtoken"; + +const friendRequest = async (req: Request, res: Response) => { +    try { +        // @ts-ignore +        res.status(200).json({ token: getFriendToken(req.userId) }) +    } catch (error) { +        res.status(500).json({ error: "Internal Server Error" }); +        console.error(error); +    } +} + +const addFriend = async (req: Request, res: Response) => { +    try { +        // @ts-ignore +        jwt.verify(req.body.token as string, process.env.FRIEND_TOKEN_SECRET, async (err, claims) => { +            if (err) { +                // @ts-ignore +                switch (err.message) { +                    case "jwt expired": +                        res.status(401).json({ error: "Request Expired" }); +                        break; +                    case "invalid signature": +                        res.status(401).json({ error: "Request Invalid" }); +                        break; +                    default: +                        res.status(500).json({ error: "Internal Server Error" }); +                        console.error(err) +                        break; +                } +            } else { +                // @ts-ignore +                if (claims.userId == req.userId) { +                    res.status(400).json({ message: "Attempted to become friends with self" }); +                } else { +                    try { +                        // @ts-ignore +                        const _ = await friend(claims.userId, req.userId); +                        res.status(200).json({ message: "success" }); +                    } catch (error) { +                        // @ts-ignore +                        if (error.code == "P2002") { +                            res.status(409).json({ error: "Already friends" }); +                        } else { +                            console.error(error); +                            res.status(500).json({ error: "Internal Server Error" }); +                        } +                    } +                } +            } +        }); +    } catch(error) { +        res.status(500).json({ error: "Internal Server Error" }); +        console.error(error); +    } +} + +const removeFriend = async (req: Request, res: Response) => { +    try { +        // @ts-ignore +        const { count } = await unfriend(req.userId, req.body.friendId) +        if (count > 0) { +            res.status(200).json({ message: "success" }); +        } else { +            res.status(404).json({ error: "Friend not found" }); +        } +    } catch(error) { +        res.status(500).json({ error: "Internal Server Error" }); +        console.error(error); +    } +} + +const listFriends = async (req: Request, res: Response) => { +    try { +        // @ts-ignore +        const friends = await list(req.userId) +        // @ts-ignore +        res.status(200).json({ friends: friends }); +    } catch(error) { +        res.status(500).json({ error: "Internal Server Error" }); +        console.error(error); +    } +} + +export { +    friendRequest, +    addFriend, +    removeFriend, +    listFriends +} diff --git a/src/controller/transaction.ts b/src/controller/transaction.ts new file mode 100644 index 0000000..b5fcf99 --- /dev/null +++ b/src/controller/transaction.ts @@ -0,0 +1,57 @@ +/* Financer - Pocket Money Tracker + * Copyright (C) 2025  Vidhu Kant Sharma <vidhukant@vidhukant.com> + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <https://www.gnu.org/licenses/>. + */ + +import { Request, Response } from "express"; +import { create, read } from "../service/transaction"; + +const addNew = async (req: Request, res: Response) => { +    try { +        // @ts-ignore +        const transaction = await create({ ...req.body, userId: req.userId }); +        res.status(201).json({ transaction }) +    } catch(error) { +        res.status(500).json({ error: "Internal Server Error" }); +        console.error(error); +    } +} + +const get = async (req: Request, res: Response) => { +    try { +        // @ts-ignore +        const transactions = await read(req.userId, req.body.type); +        res.status(transactions.length > 0 ? 200 : 204).json({ transactions }) +    } catch(error) { +        res.status(500).json({ error: "Internal Server Error" }); +        console.error(error); +    } +} + +const remove = async (req: Request, res: Response) => { +    try { +        // TODO: check ownership before deletion +        res.status(200).json({ "message": "work in progress" }) +    } catch(error) { +        res.status(500).json({ error: "Internal Server Error" }); +        console.error(error); +    } +} + +export { +    addNew, +    get, +    remove +} diff --git a/src/controller/user.ts b/src/controller/user.ts new file mode 100644 index 0000000..7948c06 --- /dev/null +++ b/src/controller/user.ts @@ -0,0 +1,40 @@ +/* Financer - Pocket Money Tracker + * Copyright (C) 2025  Vidhu Kant Sharma <vidhukant@vidhukant.com> + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <https://www.gnu.org/licenses/>. + */ + +import { Request, Response } from "express"; +import { readById } from "../service/user"; + +const profile = async (req: Request, res: Response) => { +    try { +        // @ts-ignore +        const user = await readById(req.userId); + +        // @ts-ignore +        delete user["password"] +        // @ts-ignore +        delete user["refreshTokenVersion"] + +        res.status(200).json({ user: user }) +    } catch(error) { +        res.status(500).json({ error: "Internal Server Error" }); +        console.error(error); +    } +} + +export { +    profile, +}
\ No newline at end of file diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..ca1c0c4 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,31 @@ +/* Financer - Pocket Money Tracker + * Copyright (C) 2025  Vidhu Kant Sharma <vidhukant@vidhukant.com> + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <https://www.gnu.org/licenses/>. + */ + +import "dotenv/config" +import express, { Express } from "express"; + +import api from "./route/api"; + +const app: Express = express(); + +app.use(express.json()); + +app.use("/api", api); + +app.listen(process.env.PORT, () => { +    console.info(`Financer started on port ${process.env.PORT}.`); +})
\ No newline at end of file diff --git a/src/middleware/auth.ts b/src/middleware/auth.ts new file mode 100644 index 0000000..ee10218 --- /dev/null +++ b/src/middleware/auth.ts @@ -0,0 +1,34 @@ +import { Request, Response, NextFunction } from "express"; +import jwt from "jsonwebtoken"; + +const authenticate = () => (req: Request, res: Response, next: NextFunction) => { +    const authHeader = req.headers.authorization; +    const token = authHeader && authHeader.split(" ")[1]; + +    if (!token) res.status(401).json({ error: "Unauthorized" }); + +    // @ts-ignore +    jwt.verify(token as string, process.env.ACCESS_TOKEN_SECRET, (err, claims) => { +        if (err) { +            // @ts-ignore +            switch (err.message) { +                case "jwt expired": +                    res.status(401).json({ error: "Token Expired" }); +                    break; +                case "invalid signature": +                    res.status(401).json({ error: "Invalid Credentials" }); +                    break; +                default: +                    res.status(500).json({ error: "Internal Server Error" }); +                    console.error(err) +                    break; +            } +        } else { +            // @ts-ignore +            req.userId = claims.userId; +            next(); +        } +    }); +} + +export default authenticate;
\ No newline at end of file diff --git a/src/route/api.ts b/src/route/api.ts new file mode 100644 index 0000000..e669052 --- /dev/null +++ b/src/route/api.ts @@ -0,0 +1,34 @@ +/* Financer - Pocket Money Tracker + * Copyright (C) 2025  Vidhu Kant Sharma <vidhukant@vidhukant.com> + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <https://www.gnu.org/licenses/>. + */ + +import { Router } from "express"; +import authorize from "../middleware/auth"; + +import authRouter from "./auth"; +import userRouter from "./user"; +import transactionRouter from "./transaction"; +import friendRouter from "./friend"; + +const allRoutes: Router = Router(); + +allRoutes.use("/auth", authRouter); + +allRoutes.use("/user", authorize(), userRouter) +allRoutes.use("/transaction", authorize(), transactionRouter) +allRoutes.use("/friend", authorize(), friendRouter) + +export default allRoutes;
\ No newline at end of file diff --git a/src/route/auth.ts b/src/route/auth.ts new file mode 100644 index 0000000..cbead4c --- /dev/null +++ b/src/route/auth.ts @@ -0,0 +1,27 @@ +/* Financer - Pocket Money Tracker + * Copyright (C) 2025  Vidhu Kant Sharma <vidhukant@vidhukant.com> + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <https://www.gnu.org/licenses/>. + */ + +import { Router } from "express"; +import { login, signup, refresh } from "../controller/auth"; + +const router: Router = Router(); + +router.post("/login", login); +router.post("/refresh", refresh); +router.post("/signup", signup); + +export default router;
\ No newline at end of file diff --git a/src/route/friend.ts b/src/route/friend.ts new file mode 100644 index 0000000..9245bca --- /dev/null +++ b/src/route/friend.ts @@ -0,0 +1,28 @@ +/* Financer - Pocket Money Tracker + * Copyright (C) 2025  Vidhu Kant Sharma <vidhukant@vidhukant.com> + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <https://www.gnu.org/licenses/>. + */ + +import { Router } from "express"; +import { listFriends, friendRequest, addFriend, removeFriend } from "../controller/friend"; + +const router: Router = Router(); + +router.get("/", listFriends); +router.post("/initiate", friendRequest); +router.post("/", addFriend); +router.delete("/", removeFriend); + +export default router; diff --git a/src/route/transaction.ts b/src/route/transaction.ts new file mode 100644 index 0000000..d42f94b --- /dev/null +++ b/src/route/transaction.ts @@ -0,0 +1,27 @@ +/* Financer - Pocket Money Tracker + * Copyright (C) 2025  Vidhu Kant Sharma <vidhukant@vidhukant.com> + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <https://www.gnu.org/licenses/>. + */ + +import { Router } from "express"; +import { get, addNew, remove } from "../controller/transaction"; + +const router: Router = Router(); + +router.get("/", get); +router.post("/", addNew); +router.delete("/", remove); + +export default router; diff --git a/src/route/user.ts b/src/route/user.ts new file mode 100644 index 0000000..c3a625c --- /dev/null +++ b/src/route/user.ts @@ -0,0 +1,25 @@ +/* Financer - Pocket Money Tracker + * Copyright (C) 2025  Vidhu Kant Sharma <vidhukant@vidhukant.com> + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <https://www.gnu.org/licenses/>. + */ + +import { Router } from "express"; +import { profile } from "../controller/user"; + +const router: Router = Router(); + +router.get("/profile", profile); + +export default router; diff --git a/src/service/budget.ts b/src/service/budget.ts new file mode 100644 index 0000000..2790b62 --- /dev/null +++ b/src/service/budget.ts @@ -0,0 +1,20 @@ +/* Financer - Pocket Money Tracker + * Copyright (C) 2025  Vidhu Kant Sharma <vidhukant@vidhukant.com> + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <https://www.gnu.org/licenses/>. + */ + +// import prisma from "../util/prisma"; +//import {  } from "@prisma/client"; + diff --git a/src/service/friend.ts b/src/service/friend.ts new file mode 100644 index 0000000..c7f4b6b --- /dev/null +++ b/src/service/friend.ts @@ -0,0 +1,72 @@ +/* Financer - Pocket Money Tracker + * Copyright (C) 2025  Vidhu Kant Sharma <vidhukant@vidhukant.com> + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <https://www.gnu.org/licenses/>. + */ + +import prisma from "../util/prisma"; + +const friend = async (userId: Number, friendId: Number) => { +    // will return error P2002 if already friends +    return prisma.friend.createMany({ +        data: [ +            // @ts-ignore +            { userId: userId, friendId: friendId }, + +            // @ts-ignore +            { userId: friendId, friendId: userId } +        ] +    }) +} + +const unfriend = async (userId: Number, friendId: Number) => { +    return prisma.friend.deleteMany({ +        where: { +            OR: [ +                // @ts-ignore +                { userId: userId }, + +                // @ts-ignore +                { userId: friendId }, +            ] +        } +    }) +} + +const list = async (userId: Number) => { +    const friendsRaw = await prisma.friend.findMany({ +        // @ts-ignore +        where: { userId: userId }, +        include: { friend: true } +    }) + +    // TODO: check if no friends + +    // @ts-ignore +    return friendsRaw.map((x: any) => { +        const friend = x.friend; +        delete friend["password"]; +        delete friend["refreshTokenVersion"]; +        delete friend["createdAt"]; +        delete friend["updatedAt"]; + +        return friend; +    }) +} + +export { +    friend, +    unfriend, +    list +}
\ No newline at end of file diff --git a/src/service/transaction.ts b/src/service/transaction.ts new file mode 100644 index 0000000..29a9faa --- /dev/null +++ b/src/service/transaction.ts @@ -0,0 +1,48 @@ +/* Financer - Pocket Money Tracker + * Copyright (C) 2025  Vidhu Kant Sharma <vidhukant@vidhukant.com> + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <https://www.gnu.org/licenses/>. + */ + +import prisma from "../util/prisma"; +import { Transaction, TransactionType } from "@prisma/client"; + +const create = async (transaction: Transaction) => { +    // TODO: validate +    return prisma.transaction.create({ +        data: { +            ...transaction, +        } +    }) +} + +const read = async (userId: Number, type: String) => { +    const hasFilter = [ +        TransactionType.LENT, +        TransactionType.BORROWED, +        TransactionType.SPENT, +        TransactionType.RECEIVED +    ].includes(type as TransactionType) +    const filter = hasFilter ? { type: type } : {} + +    return prisma.transaction.findMany({ +        // @ts-ignore +        where: { userId: userId, ...filter } +    }) +} + +export { +    create, +    read +} diff --git a/src/service/user.ts b/src/service/user.ts new file mode 100644 index 0000000..712e6f4 --- /dev/null +++ b/src/service/user.ts @@ -0,0 +1,56 @@ +/* Financer - Pocket Money Tracker + * Copyright (C) 2025  Vidhu Kant Sharma <vidhukant@vidhukant.com> + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <https://www.gnu.org/licenses/>. + */ + +import prisma from "../util/prisma"; +import {User} from "@prisma/client"; + +const create = async (user: User) => { +    // TODO: validate +    return prisma.user.create({ +        data: { +            ...user, +        } +    }) +} + +const readById = async (id: Number) => { +    return prisma.user.findUnique({ +        // @ts-ignore +        where: { id: id } +    }) +} + +const readByEmail = async (email: String) => { +    return prisma.user.findUniqueOrThrow({ +        // @ts-ignore +        where: { email: email } +    }) +} + +const readByUsername = async (username: String) => { +    return prisma.user.findUnique({ +        // @ts-ignore +        where: { userName: username } +    }) +} + +export { +    create, +    readById, +    readByEmail, +    readByUsername, +};
\ No newline at end of file diff --git a/src/util/auth.ts b/src/util/auth.ts new file mode 100644 index 0000000..d892bc3 --- /dev/null +++ b/src/util/auth.ts @@ -0,0 +1,39 @@ +import jwt from 'jsonwebtoken'; + +const getAccessToken = (userId: Number) => +    // @ts-ignore +    jwt.sign({ userId: userId }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: "5m" }); + +const getRefreshToken = (userId: Number, version: Number) => +    // @ts-ignore +    jwt.sign({ userId: userId,  version: version, }, process.env.REFRESH_TOKEN_SECRET, { expiresIn: "15d" }); + +const verifyRefreshToken = (token: string) => { +    try { +        // @ts-ignore +        return jwt.verify(token, process.env.REFRESH_TOKEN_SECRET); +    } catch (error) { +        throw error; +    } +} + +const getFriendToken = (userId: Number) => +    // @ts-ignore +    jwt.sign({ userId: userId }, process.env.FRIEND_TOKEN_SECRET, { expiresIn: "2m" }); + +const verifyFriendToken = (token: string) => { +    try { +        // @ts-ignore +        return jwt.verify(token, process.env.FRIEND_TOKEN_SECRET); +    } catch (error) { +        throw error; +    } +} + +export { +    getAccessToken, +    getRefreshToken, +    verifyRefreshToken, +    getFriendToken, +    verifyFriendToken, +};
\ No newline at end of file diff --git a/src/util/prisma.ts b/src/util/prisma.ts new file mode 100644 index 0000000..ca27020 --- /dev/null +++ b/src/util/prisma.ts @@ -0,0 +1,22 @@ +/* Financer - Pocket Money Tracker + * Copyright (C) 2025  Vidhu Kant Sharma <vidhukant@vidhukant.com> + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <https://www.gnu.org/licenses/>. + */ + +import { PrismaClient } from "@prisma/client"; + +const prisma = new PrismaClient(); + +export default prisma;
\ No newline at end of file  |