-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
108 lines (91 loc) · 2.83 KB
/
Copy pathindex.js
File metadata and controls
108 lines (91 loc) · 2.83 KB
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
/**
* Responds to any HTTP request.
*
* @param {!express:Request} req HTTP request context.
* @param {!express:Response} res HTTP response context.
*/
const APP_ENDPOINT = process.env.APP_ENDPOINT || "https://localhost";
const admin = require("firebase-admin");
admin.initializeApp();
exports.authUser = async (req, res) => {
const contentType = req.headers["content-type"];
if (!contentType) {
return res.status(403).send({ message: "Content-Type is missing" });
}
if (contentType !== "application/json") {
return res
.status(403)
.send({ message: "Content-Type must be application/json" });
}
if (req.method == "POST") {
const { name, cpf, email, phone, password } = req.body;
let customer;
if (cpf) {
customer = await pgFindUser(cpf);
if (!customer) {
customer = await pgCreateUser({ name, cpf, email, phone });
}
}
let userRecord;
try {
userRecord = await admin.auth().getUserByEmail(email);
} catch (err) {
console.error(err); // o método retornar uma exception quando nao encontra o e-mail
}
try {
if (!userRecord) {
userRecord = await admin.auth().createUser({
email: email,
password: password,
phoneNumber: phone,
displayName: name,
});
}
let token;
if (userRecord ) {
if(cpf){
await admin.auth().setCustomUserClaims(userRecord.uid, { cpf });
// get user with CustomUserClaims
userRecord = await admin.auth().getUser(userRecord.uid);
}
}
const dataReturn = { userRecord };
return res.status(200).json(dataReturn);
} catch (err) {
return res.status(403).send({ message: err.message });
}
} else {
return res
.status(403)
.send({ message: `Method not ${req.method} allowed` });
}
};
pgCreateUser = async ({ name, cpf, email, phone }) => {
const response = await fetch(APP_ENDPOINT + "/customers", {
method: "post",
body: JSON.stringify({
email,
phone,
cpf,
name,
}),
headers: { "Content-Type": "application/json" },
});
if (response.ok) {
return response.body;
}
return null;
};
pgFindUser = async (cpf) => {
const response = await fetch(
APP_ENDPOINT + "/customers/search?cpf=" + cpf,
{
method: "get",
headers: { "Content-Type": "application/json" },
}
);
if (response.ok) {
return response.body;
}
return null;
};