aboutsummaryrefslogtreecommitdiff
path: root/src/controller/auth.ts
blob: 13196fba228f91de5317cbe4ed70e3da3e447d06 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
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 };