-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #3 from GenieWizards/feat/add-lucia-auth
feat: add auth and related utilities
- Loading branch information
Showing
38 changed files
with
2,067 additions
and
76 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -45,5 +45,6 @@ | |
"scss", | ||
"pcss", | ||
"postcss" | ||
] | ||
], | ||
"cSpell.words": ["openapi"] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,19 @@ | ||
// NOTE: If updating values update in both | ||
export const AuthRoles = ["user", "admin"] as const; | ||
// NOTE: Updating the array will auto update the AuthRoles object | ||
export const authRolesArr = ["user", "admin"] as const; | ||
|
||
export enum AuthRole { | ||
USER = "user", | ||
ADMIN = "admin", | ||
} | ||
type AuthRolesTuple = typeof authRolesArr; | ||
type AuthRolesValues = AuthRolesTuple[number]; | ||
type AuthRolesType = { | ||
[K in Uppercase<AuthRolesValues>]: Lowercase<K>; | ||
}; | ||
|
||
export const AuthRoles = authRolesArr.reduce( | ||
(acc, role) => ({ | ||
...acc, | ||
[role.toUpperCase()]: role, | ||
}), | ||
{} as AuthRolesType, | ||
); | ||
|
||
export type UpperCaseAuthRole = keyof typeof AuthRoles; | ||
export type AuthRole = (typeof AuthRoles)[UpperCaseAuthRole]; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
import type { ZodSchema } from "../lib/types"; | ||
|
||
import { jsonContent } from "./json-content.helper"; | ||
|
||
function jsonContentRequired<T extends ZodSchema>( | ||
schema: T, | ||
description: string, | ||
) { | ||
return { | ||
...jsonContent(schema, description), | ||
required: true, | ||
}; | ||
} | ||
|
||
export default jsonContentRequired; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
import * as HTTPStatusPhrases from "@/common/utils/http-status-phrases.util"; | ||
|
||
import { createMessageObjectSchema } from "../schema/create-message-object.schema"; | ||
|
||
export const notFoundSchema = createMessageObjectSchema( | ||
HTTPStatusPhrases.NOT_FOUND, | ||
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
import type { MiddlewareHandler } from "hono"; | ||
|
||
import { getCookie } from "hono/cookie"; | ||
|
||
import * as HTTPStatusCodes from "@/common/utils/http-status-codes.util"; | ||
|
||
import type { AuthRole } from "../enums"; | ||
|
||
import { validateSessionToken } from "../utils/sessions.util"; | ||
|
||
export function authMiddleware(): MiddlewareHandler { | ||
return async (c, next) => { | ||
const sessionId | ||
= c.req.header("session") || getCookie(c, "session") || null; | ||
|
||
if (!sessionId) { | ||
c.set("user", null); | ||
c.set("session", null); | ||
|
||
return next(); | ||
} | ||
|
||
const { session, user } = await validateSessionToken(sessionId); | ||
|
||
if (!session) { | ||
c.set("user", null); | ||
c.set("session", null); | ||
|
||
return next(); | ||
} | ||
|
||
c.set("user", user); | ||
c.set("session", session); | ||
|
||
return await next(); | ||
}; | ||
} | ||
|
||
export function requireAuth(): MiddlewareHandler { | ||
return async (c, next) => { | ||
if (!c.get("user")) { | ||
return c.json( | ||
{ | ||
success: false, | ||
message: "You are not authorized, please login", | ||
}, | ||
HTTPStatusCodes.UNAUTHORIZED, | ||
); | ||
} | ||
|
||
return await next(); | ||
}; | ||
} | ||
|
||
export function checkRoleGuard(...allowedRoles: AuthRole[]): MiddlewareHandler { | ||
return async (c, next) => { | ||
const user = c.get("user"); | ||
|
||
if (!user) { | ||
return c.json( | ||
{ | ||
success: false, | ||
message: "You are not authorized, please login", | ||
}, | ||
HTTPStatusCodes.UNAUTHORIZED, | ||
); | ||
} | ||
|
||
if (!user.role) { | ||
return c.json( | ||
{ | ||
success: false, | ||
message: "You are not allowed to perform this action", | ||
}, | ||
HTTPStatusCodes.FORBIDDEN, | ||
); | ||
} | ||
|
||
if (!allowedRoles.includes(user.role)) { | ||
return c.json( | ||
{ | ||
success: false, | ||
message: "You are not allowed to perform this action", | ||
}, | ||
HTTPStatusCodes.FORBIDDEN, | ||
); | ||
} | ||
|
||
await next(); | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
import { hash, verify } from "@node-rs/argon2"; | ||
import { sha1 } from "@oslojs/crypto/sha1"; | ||
import { encodeHexLowerCase } from "@oslojs/encoding"; | ||
|
||
export async function hashPassword(password: string): Promise<string> { | ||
return await hash(password, { | ||
memoryCost: 19456, | ||
timeCost: 2, | ||
outputLen: 32, | ||
parallelism: 1, | ||
}); | ||
} | ||
|
||
export async function verifyPasswordHash( | ||
hash: string, | ||
password: string, | ||
): Promise<boolean> { | ||
return await verify(hash, password); | ||
} | ||
|
||
export async function verifyPasswordStrength( | ||
password: string, | ||
): Promise<boolean> { | ||
if (password.length < 8 || password.length > 255) { | ||
return false; | ||
} | ||
const hash = encodeHexLowerCase(sha1(new TextEncoder().encode(password))); | ||
const hashPrefix = hash.slice(0, 5); | ||
const response = await fetch( | ||
`https://api.pwnedpasswords.com/range/${hashPrefix}`, | ||
); | ||
const data = await response.text(); | ||
const items = data.split("\n"); | ||
for (const item of items) { | ||
const hashSuffix = item.slice(0, 35).toLowerCase(); | ||
if (hash === hashPrefix + hashSuffix) { | ||
return false; | ||
} | ||
} | ||
return true; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
import { encodeBase32LowerCaseNoPadding } from "@oslojs/encoding"; | ||
import { eq } from "drizzle-orm"; | ||
|
||
import type { TSelectSessionSchema } from "@/db/schemas/session.model"; | ||
import type { TSelectUserSchema } from "@/db/schemas/user.model"; | ||
|
||
import { db } from "@/db/adapter"; | ||
import sessionModel from "@/db/schemas/session.model"; | ||
import userModel from "@/db/schemas/user.model"; | ||
|
||
export type SessionValidationResult = | ||
| { session: TSelectSessionSchema; user: TSelectUserSchema } | ||
| { session: null; user: null }; | ||
|
||
export function generateSessionToken(): string { | ||
const tokenBytes = new Uint8Array(20); | ||
crypto.getRandomValues(tokenBytes); | ||
const token = encodeBase32LowerCaseNoPadding(tokenBytes).toLowerCase(); | ||
return token; | ||
} | ||
|
||
export async function validateSessionToken( | ||
token: string, | ||
): Promise<SessionValidationResult> { | ||
const result = await db | ||
.select({ user: userModel, session: sessionModel }) | ||
.from(sessionModel) | ||
.innerJoin(userModel, eq(sessionModel.userId, userModel.id)) | ||
.where(eq(sessionModel.id, token)); | ||
|
||
if (result.length < 1) { | ||
return { session: null, user: null }; | ||
} | ||
|
||
const { user, session } = result[0]; | ||
|
||
if (!user) { | ||
await db.delete(sessionModel).where(eq(sessionModel.id, session.id)); | ||
return { session: null, user: null }; | ||
} | ||
|
||
if (Date.now() >= session.expiresAt.getTime()) { | ||
await db.delete(sessionModel).where(eq(sessionModel.id, session.id)); | ||
|
||
return { session: null, user: null }; | ||
} | ||
|
||
if (Date.now() >= session.expiresAt.getTime() - 1000 * 60 * 60 * 24 * 15) { | ||
session.expiresAt = new Date(Date.now() + 1000 * 60 * 60 * 24 * 30); | ||
|
||
await db | ||
.update(sessionModel) | ||
.set({ | ||
expiresAt: session.expiresAt, | ||
}) | ||
.where(eq(sessionModel.id, session.id)); | ||
} | ||
|
||
return { session, user }; | ||
} | ||
|
||
export async function invalidateSession(sessionId: string): Promise<void> { | ||
await db.delete(sessionModel).where(eq(sessionModel.id, sessionId)); | ||
} | ||
|
||
export async function invalidateUserSessions(userId: string): Promise<void> { | ||
await db.delete(sessionModel).where(eq(sessionModel.id, userId)); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.