-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
94 lines (86 loc) · 2.29 KB
/
index.ts
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
import express, { Request, Response } from "express";
import CORS from "cors";
import mongoose from "mongoose";
import { User } from "./model/user";
import jwt from "jsonwebtoken";
import dotenv from "dotenv";
import path from "path";
import { decodedTextSpanIntersectsWith } from "typescript";
dotenv.config({ path: "./config.env" });
const app = express();
const url = process.env.URL;
const token_key = process.env.TOKEN_KEY;
export type FormDataType = {
name?: string;
mail: string;
password: string;
token: string;
};
try {
mongoose
.connect(url as string)
.then(() => {
console.log("Connected to the database ");
})
.catch((err) => {
throw err;
});
} catch (error) {
console.log("error message: ", error);
}
app.use(CORS());
app.use(express.json());
if (process.env.NODE_ENV == "production") {
app.use(express.static(path.join(__dirname, "dist/public")));
}
app.all("*", (req: Request, res: Response) => {
res.sendFile(path.join(__dirname, "./dist/public/static/index.html"));
});
app.post("/signup", (req: Request, res: Response) => {
const signUpFormData: FormDataType = req.body;
const query = User.where({ mail: signUpFormData.mail });
query.findOne((err: any, doc: any) => {
if (!doc) {
const token = jwt.sign(
{ id: signUpFormData.mail },
token_key as string,
{
algorithm: "HS256",
expiresIn: "2h",
}
);
const userData = { ...signUpFormData, token: token };
const newUser: any = User.create(userData);
console.log("form data", signUpFormData);
res.status(201).send(token);
} else {
console.log(signUpFormData);
res.status(400).send("<h1> Mail exists </h1>");
}
});
});
app.post("/login", (req: Request, res: Response) => {
const logInFormData: FormDataType = req.body;
const query = User.where({ mail: logInFormData.mail });
query.findOne((err: any, doc: any) => {
if (doc) {
console.log(doc);
if (doc.password === logInFormData.password) {
try {
const token = jwt.verify(
logInFormData.token,
token_key as string
);
res.status(201).send(token);
} catch (err) {
res.status(400).send("Token required or Expired token");
}
}
} else {
res.status(400).send("<h1>Login failed</h1>");
}
});
});
app.listen(process.env.PORT || 3000, () => {
console.log("Server is listening!");
});