Last active
October 15, 2024 03:34
-
-
Save z4vmk/2c6e6586e60d985310ebc81a25a0f262 to your computer and use it in GitHub Desktop.
HD Example One
This file contains hidden or 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
// Dependencies | |
import { hash } from "jsr:@ts-rex/bcrypt"; | |
import { Hono } from "jsr:@hono/hono"; | |
import { encode } from "jsr:@gz/jwt"; | |
// Environment Variables | |
const DATABASE_URL = Deno.env.get("DATABASE_URL"); // Gets the DatabaseURL from the env. | |
const JWT_SECRET = Deno.env.get("JWT_SECRET"); // Gets the JWT Secret from the env. | |
// Create App | |
const app = new Hono(); // Creates a new Hono app. | |
const kv = await Deno.openKv(DATABASE_URL); // Create a Database Instance. | |
// Route (/) | |
app.get("/", (c) => { | |
const query = c.req.query("q"); // Gets the 'q' query in the URL. | |
if (!query) { | |
return c.text("400 Bad Request", 400); // Returns 400 if query not found. | |
} | |
const hashed_query = hash(query); // Hashes the query. | |
return c.text(hashed_query); // Returns the hashed query as text. | |
}); | |
// Route (/create-user) | |
app.post("/create-user", async (c) => { | |
// Body | |
const req_body = await c.req.parseBody(); // Parses the request body. | |
const un = req_body["username"]; // Variable from Username in body. | |
const up = req_body["password"]; // Variable from Password in body. | |
// Exist Check | |
if (!un || !up) { | |
return c.text("400 Bad Request", 400); // Returns 400 if Username or Password missing from body. | |
} | |
// Type Check | |
if (typeof un !== "string" || typeof up !== "string") { | |
return c.text("400 Bad Request", 400); // Returns 400 if the Username or Password is not a string. | |
} | |
// Check Already Exists | |
const existing_user = await kv.get(["users", un]); // Get's a user from the database 'Users', via the username. | |
if (existing_user.value) { | |
return c.text("401 Unauthorized", 401); // Returns 401 if the user with the username already exists. | |
} | |
// Create User | |
await kv.set(["users", un], { // Creates the user in the database. | |
username: un, | |
password: hash(up), | |
}); | |
// Create JWT | |
const json_token = await encode( // Creates a JSON Web Token for the frontend. | |
{ | |
username: un, | |
}, | |
JWT_SECRET || "TestingSecret", | |
{ | |
algorithm: "HS256", | |
} | |
); | |
return c.json({ // Returns success true and the JSON Web Token. | |
success: true, | |
token: json_token, | |
}); | |
}); | |
// Serve App | |
Deno.serve(app.fetch); // Serves the Hono app via Deno.Serve |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment