-
-
Notifications
You must be signed in to change notification settings - Fork 250
/
[refreshToken].ts
210 lines (185 loc) · 5.5 KB
/
[refreshToken].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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
import { db } from "@/server/db";
import { applications } from "@/server/db/schema";
import type { DeploymentJob } from "@/server/queues/deployments-queue";
import { myQueue } from "@/server/queues/queueSetup";
import { eq } from "drizzle-orm";
import type { NextApiRequest, NextApiResponse } from "next";
export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
) {
const { refreshToken } = req.query;
try {
if (req.headers["x-github-event"] === "ping") {
res.status(200).json({ message: "Ping received, webhook is active" });
return;
}
const application = await db.query.applications.findFirst({
where: eq(applications.refreshToken, refreshToken as string),
with: {
project: true,
},
});
if (!application) {
res.status(404).json({ message: "Application Not Found" });
return;
}
if (!application?.autoDeploy) {
res.status(400).json({ message: "Application Not Deployable" });
return;
}
const deploymentTitle = extractCommitMessage(req.headers, req.body);
const deploymentHash = extractHash(req.headers, req.body);
const sourceType = application.sourceType;
if (sourceType === "docker") {
const applicationDockerTag = extractImageTag(application.dockerImage);
const webhookDockerTag = extractImageTagFromRequest(
req.headers,
req.body,
);
if (
applicationDockerTag &&
webhookDockerTag &&
webhookDockerTag !== applicationDockerTag
) {
res.status(301).json({
message: `Application Image Tag (${applicationDockerTag}) doesn't match request event payload Image Tag (${webhookDockerTag}).`,
});
return;
}
} else if (sourceType === "github") {
const branchName = extractBranchName(req.headers, req.body);
if (!branchName || branchName !== application.branch) {
res.status(301).json({ message: "Branch Not Match" });
return;
}
} else if (sourceType === "git") {
const branchName = extractBranchName(req.headers, req.body);
if (!branchName || branchName !== application.customGitBranch) {
res.status(301).json({ message: "Branch Not Match" });
return;
}
}
try {
const jobData: DeploymentJob = {
applicationId: application.applicationId as string,
titleLog: deploymentTitle,
descriptionLog: `Hash: ${deploymentHash}`,
type: "deploy",
applicationType: "application",
};
await myQueue.add(
"deployments",
{ ...jobData },
{
removeOnComplete: true,
removeOnFail: true,
},
);
} catch (error) {
res.status(400).json({ message: "Error To Deploy Application", error });
return;
}
res.status(200).json({ message: "App Deployed Succesfully" });
} catch (error) {
console.log(error);
res.status(400).json({ message: "Error To Deploy Application", error });
}
}
/**
* Return the last part of the image name, which is the tag
* Example: "my-image" => null
* Example: "my-image:latest" => "latest"
* Example: "my-image:1.0.0" => "1.0.0"
* Example: "myregistryhost:5000/fedora/httpd:version1.0" => "version1.0"
* @link https://docs.docker.com/reference/cli/docker/image/tag/
*/
function extractImageTag(dockerImage: string | null) {
if (!dockerImage || typeof dockerImage !== "string") {
return null;
}
const tag = dockerImage.split(":").pop();
return tag === dockerImage ? "latest" : tag;
}
/**
* @link https://docs.docker.com/docker-hub/webhooks/#example-webhook-payload
*/
export const extractImageTagFromRequest = (
headers: any,
body: any,
): string | null => {
if (headers["user-agent"]?.includes("Go-http-client")) {
if (body.push_data && body.repository) {
return body.push_data.tag;
}
}
return null;
};
export const extractCommitMessage = (headers: any, body: any) => {
// GitHub
if (headers["x-github-event"]) {
return body.head_commit ? body.head_commit.message : "NEW COMMIT";
}
// GitLab
if (headers["x-gitlab-event"]) {
return body.commits && body.commits.length > 0
? body.commits[0].message
: "NEW COMMIT";
}
// Bitbucket
if (headers["x-event-key"]?.includes("repo:push")) {
return body.push.changes && body.push.changes.length > 0
? body.push.changes[0].new.target.message
: "NEW COMMIT";
}
// Gitea
if (headers["x-gitea-event"]) {
return body.commits && body.commits.length > 0
? body.commits[0].message
: "NEW COMMIT";
}
if (headers["user-agent"]?.includes("Go-http-client")) {
if (body.push_data && body.repository) {
return `Docker image pushed: ${body.repository.repo_name}:${body.push_data.tag} by ${body.push_data.pusher}`;
}
}
return "NEW CHANGES";
};
export const extractHash = (headers: any, body: any) => {
// GitHub
if (headers["x-github-event"]) {
return body.head_commit ? body.head_commit.id : "";
}
// GitLab
if (headers["x-gitlab-event"]) {
return (
body.checkout_sha ||
(body.commits && body.commits.length > 0
? body.commits[0].id
: "NEW COMMIT")
);
}
// Bitbucket
if (headers["x-event-key"]?.includes("repo:push")) {
return body.push.changes && body.push.changes.length > 0
? body.push.changes[0].new.target.hash
: "NEW COMMIT";
}
// Gitea
if (headers["x-gitea-event"]) {
return body.after || "NEW COMMIT";
}
return "";
};
export const extractBranchName = (headers: any, body: any) => {
if (headers["x-github-event"] || headers["x-gitea-event"]) {
return body?.ref?.replace("refs/heads/", "");
}
if (headers["x-gitlab-event"]) {
return body?.ref ? body?.ref.replace("refs/heads/", "") : null;
}
if (headers["x-event-key"]?.includes("repo:push")) {
return body?.push?.changes[0]?.new?.name;
}
return null;
};