-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathrouter.ts
240 lines (204 loc) · 9.25 KB
/
router.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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
import { authProvidersList } from "@app/utils/config/project";
import { getAuthProviderFromString, getUserRoleFromString } from "@app/utils/convertors";
import { LoginFormSchema } from "@app/utils/schemas/auth";
import { parseValueToSchema } from "@app/utils/schemas/utils";
import { AuthActionIntent, type AuthProvider, type LoggedInUserData } from "@app/utils/types";
import { type Context, Hono } from "hono";
import { AuthenticationMiddleware, LoginProtectedRoute } from "~/middleware/auth";
import { getReqRateLimiter, strictGetReqRateLimiter } from "~/middleware/rate-limit/get-req";
import { invalidAuthAttemptLimiter } from "~/middleware/rate-limit/invalid-auth-attempt";
import { critModifyReqRateLimiter } from "~/middleware/rate-limit/modify-req";
import { REQ_BODY_NAMESPACE } from "~/types/namespaces";
import { HTTP_STATUS, invalidReqestResponse, serverErrorResponse } from "~/utils/http";
import { userIconUrl } from "~/utils/urls";
import { getLinkedAuthProviders, linkAuthProviderHandler, unlinkAuthProvider } from "./controllers/link-provider";
import { deleteUserSession, getUserSessions, revokeSessionFromAccessCode } from "./controllers/session";
import { oAuthSignInHandler } from "./controllers/signin";
import credentialSignIn from "./controllers/signin/credential";
import { oAuthSignUpHandler } from "./controllers/signup";
import { getOAuthUrl } from "./helpers";
import { getUserFromCtx } from "./helpers/session";
const authRouter = new Hono();
// Middlewares
authRouter.use(invalidAuthAttemptLimiter);
authRouter.use(AuthenticationMiddleware);
// Route Definitions
authRouter.get("/me", getReqRateLimiter, currSession_get);
// Routes to get OAuth URL
authRouter.get("/signin/:authProvider", strictGetReqRateLimiter, async (ctx: Context) => oAuthUrl_get(ctx, AuthActionIntent.SIGN_IN));
authRouter.get("/signup/:authProvider", strictGetReqRateLimiter, async (ctx: Context) => oAuthUrl_get(ctx, AuthActionIntent.SIGN_UP));
authRouter.get("/link/:authProvider", strictGetReqRateLimiter, LoginProtectedRoute, async (ctx: Context) =>
oAuthUrl_get(ctx, AuthActionIntent.LINK),
);
authRouter.post("/signin/credential", critModifyReqRateLimiter, credentialSignin_post); // Sign in with credentials
authRouter.post("/signin/:authProvider", critModifyReqRateLimiter, oAuthSignIn_post);
authRouter.post("/signup/:authProvider", critModifyReqRateLimiter, oAuthSignUp_post);
authRouter.post("/link/:authProvider", critModifyReqRateLimiter, LoginProtectedRoute, oAuthLinkProvider_post);
authRouter.delete("/link/:authProvider", critModifyReqRateLimiter, LoginProtectedRoute, oAuthLinkProvider_delete);
authRouter.get("/sessions", strictGetReqRateLimiter, LoginProtectedRoute, sessions_get);
authRouter.get("/linked-providers", strictGetReqRateLimiter, LoginProtectedRoute, linkedProviders_get);
authRouter.delete("/sessions", critModifyReqRateLimiter, LoginProtectedRoute, session_delete);
authRouter.delete("/sessions/:revokeCode", critModifyReqRateLimiter, revokeSession_delete);
async function currSession_get(ctx: Context) {
try {
const userSession = getUserFromCtx(ctx);
if (!userSession) return ctx.json({ success: false, message: "You're not logged in!" }, HTTP_STATUS.OK);
const formattedObject: LoggedInUserData = {
id: userSession.id,
email: userSession.email,
userName: userSession.userName,
role: getUserRoleFromString(userSession.role),
hasAPassword: !!userSession.password,
avatar: userIconUrl(userSession.id, userSession.avatar),
sessionId: userSession.sessionId,
bio: userSession.bio,
};
return ctx.json(formattedObject, HTTP_STATUS.OK);
} catch (error) {
console.error(error);
return serverErrorResponse(ctx);
}
}
async function oAuthUrl_get(ctx: Context, intent: AuthActionIntent) {
try {
const userSession = getUserFromCtx(ctx);
if (userSession?.id && intent !== AuthActionIntent.LINK) return invalidReqestResponse(ctx, "You are already logged in!");
const authProvider = ctx.req.param("authProvider");
if (!authProvider) return ctx.json({ success: false, message: "Invalid auth provider" }, HTTP_STATUS.BAD_REQUEST);
const redirect = ctx.req.query("redirect") === "true";
const url = getOAuthUrl(ctx, authProvider, intent);
if (redirect) {
return ctx.redirect(url);
}
return ctx.json({ success: true, url }, HTTP_STATUS.OK);
} catch (error) {
return serverErrorResponse(ctx);
}
}
async function credentialSignin_post(ctx: Context) {
try {
const { data, error } = await parseValueToSchema(LoginFormSchema, ctx.get(REQ_BODY_NAMESPACE));
if (error || !data) {
return ctx.json({ success: false, message: error }, HTTP_STATUS.BAD_REQUEST);
}
const result = await credentialSignIn(ctx, data);
return ctx.json(result.data, result.status);
} catch (err) {
console.error(err);
return serverErrorResponse(ctx);
}
}
async function oAuthSignIn_post(ctx: Context) {
try {
if (getUserFromCtx(ctx)?.id) {
return invalidReqestResponse(ctx);
}
const authProvider = ctx.req.param("authProvider");
const code = ctx.get(REQ_BODY_NAMESPACE)?.code;
if (!authProvidersList.includes(authProvider.toLowerCase() as AuthProvider) || !code) {
return invalidReqestResponse(ctx);
}
const result = await oAuthSignInHandler(ctx, authProvider, code);
return ctx.json(result.data, result.status);
} catch (error) {
console.error(error);
return serverErrorResponse(ctx);
}
}
async function oAuthSignUp_post(ctx: Context) {
try {
if (getUserFromCtx(ctx)?.id) {
return invalidReqestResponse(ctx);
}
const authProvider = ctx.req.param("authProvider");
const code = ctx.get(REQ_BODY_NAMESPACE)?.code;
if (!authProvidersList.includes(authProvider.toLowerCase() as AuthProvider) || !code) {
return invalidReqestResponse(ctx);
}
const result = await oAuthSignUpHandler(ctx, authProvider, code);
return ctx.json(result.data, result.status);
} catch (error) {
console.error(error);
return serverErrorResponse(ctx);
}
}
async function oAuthLinkProvider_post(ctx: Context) {
try {
const userSession = getUserFromCtx(ctx);
if (!userSession?.id) {
return invalidReqestResponse(ctx);
}
const authProvider = ctx.req.param("authProvider");
const code = ctx.get(REQ_BODY_NAMESPACE)?.code;
if (!authProvidersList.includes(getAuthProviderFromString(authProvider)) || !code) {
return invalidReqestResponse(ctx);
}
const result = await linkAuthProviderHandler(ctx, userSession, authProvider, code);
return ctx.json(result.data, result.status);
} catch (error) {
console.error(error);
return serverErrorResponse(ctx);
}
}
async function oAuthLinkProvider_delete(ctx: Context) {
try {
const userSession = getUserFromCtx(ctx);
if (!userSession?.id) {
return invalidReqestResponse(ctx);
}
const authProvider = ctx.req.param("authProvider");
const result = await unlinkAuthProvider(ctx, userSession, authProvider);
return ctx.json(result.data, result.status);
} catch (error) {
console.error(error);
return serverErrorResponse(ctx);
}
}
async function sessions_get(ctx: Context) {
try {
const userSession = getUserFromCtx(ctx);
if (!userSession) return ctx.json([], HTTP_STATUS.OK);
const result = await getUserSessions(userSession);
return ctx.json(result.data, result.status);
} catch (error) {
console.error(error);
return serverErrorResponse(ctx);
}
}
async function linkedProviders_get(ctx: Context) {
try {
const userSession = getUserFromCtx(ctx);
if (!userSession?.id) return ctx.json([], HTTP_STATUS.BAD_REQUEST);
const result = await getLinkedAuthProviders(userSession);
return ctx.json(result.data, result.status);
} catch (err) {
console.error(err);
return serverErrorResponse(ctx);
}
}
async function session_delete(ctx: Context) {
try {
const userSession = getUserFromCtx(ctx);
const targetSessionId = ctx.get(REQ_BODY_NAMESPACE)?.sessionId || userSession?.sessionId;
if (!userSession?.id || !targetSessionId) {
return ctx.json({ success: false, message: "Session id is required" }, HTTP_STATUS.BAD_REQUEST);
}
const result = await deleteUserSession(ctx, userSession, targetSessionId);
return ctx.json(result.data, result.status);
} catch (error) {
console.error(error);
return serverErrorResponse(ctx);
}
}
async function revokeSession_delete(ctx: Context) {
try {
const code = ctx.req.param("revokeCode");
if (!code) return ctx.json({ success: false }, HTTP_STATUS.BAD_REQUEST);
const result = await revokeSessionFromAccessCode(ctx, code);
return ctx.json(result.data, result.status);
} catch (err) {
console.error(err);
return serverErrorResponse(ctx);
}
}
export default authRouter;