Skip to content

Commit

Permalink
refactor(plugin): moved ipInfo plugin in a separate file
Browse files Browse the repository at this point in the history
  • Loading branch information
adrienZ committed Oct 3, 2024
1 parent a0801ca commit 1fea643
Show file tree
Hide file tree
Showing 9 changed files with 65 additions and 94 deletions.
3 changes: 2 additions & 1 deletion playground/app.vue
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<script setup></script>
<script setup lang="ts">
</script>

<template>
<UContainer class="main-container min-h-screen flex flex-col">
Expand Down
30 changes: 0 additions & 30 deletions src/runtime/core/README.md

This file was deleted.

7 changes: 4 additions & 3 deletions src/runtime/core/core.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createChecker, type supportedConnectors } from "drizzle-schema-checker";
import { getOAuthAccountsTableSchema, getSessionsTableSchema, getUsersTableSchema, getEmailVerificationCodesTableSchema, getPasswordResetTokensTableSchema } from "../database/lib/sqlite/schema.sqlite";
import { getOAuthAccountsTableSchema, getSessionsTableSchema, getUsersTableSchema, getEmailVerificationCodesTableSchema, getPasswordResetTokensTableSchema } from "../database/sqlite/schema.sqlite";
import { drizzle as drizzleIntegration } from "db0/integrations/drizzle/index";
import type { ICreateOrLoginParams, ICreateUserParams, ILoginUserParams, IPasswordHashingMethods, ISlipAuthCoreOptions, SchemasMockValue, SlipAuthUser, tableNames } from "./types";
import { createSlipHooks } from "./hooks";
Expand Down Expand Up @@ -226,10 +226,11 @@ export class SlipAuthCore {
public async askEmailVerificationCode(user: SlipAuthUser): Promise<void> {
await this.#repos.emailVerificationCodes.deleteAllByUserId(user.id);
await this.#repos.emailVerificationCodes.insert(user.id, user.email, this.#createRandomEmailVerificationCode());
// send mail to user
}

// TODO: use transactions
// should recreate session if true
// TODO: rate limit
public async verifyEmailVerificationCode(user: SlipAuthUser, code: string): Promise<boolean> {
const databaseCode = await this.#repos.emailVerificationCodes.findByUserId(user.id);
if (!databaseCode || databaseCode.code !== code) {
Expand All @@ -250,7 +251,7 @@ export class SlipAuthCore {
}

await this.#repos.users.updateEmailVerifiedByUserId(databaseCode.user_id, true);

// should recreate session if true
return true;
}

Expand Down
47 changes: 47 additions & 0 deletions src/runtime/core/plugins/ipInfoPlugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import type { IPinfo } from "node-ipinfo";
import { IPinfoWrapper, ApiLimitError } from "node-ipinfo";
import net from "node:net";
import fsDriver from "unstorage/drivers/fs";
import { createStorage } from "unstorage";
import type { SlipAuthCore } from "../core";

export const setupIpInfoAddOn = (auth: SlipAuthCore, ipInfoToken: string) => {
const ipinfoWrapper = new IPinfoWrapper(ipInfoToken);
const cache = createStorage<IPinfo>({
driver: fsDriver({
base: "./.data/cache/ipinfo",
}),
});

auth.hooks.hook("sessions:create", async (session) => {
session.ip = "92.168.1.58";
if (!session.ip) {
return;
}
const ipType = net.isIP(session.ip);

if (ipType === 0) {
// valid cases are 4 and 6 (ipv)
return;
}

const cachedValue = await cache.getItem(session.ip);
if (cachedValue !== null) {
return;
}

try {
const response = await ipinfoWrapper.lookupIp(session.ip);
cache.setItem(session.ip, response);
}
catch (error) {
console.log(error);
if (error instanceof ApiLimitError) {
// handle api limit exceed error
}
else {
// handle other errors
}
}
});
};
13 changes: 9 additions & 4 deletions src/runtime/core/types.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import type { SQLiteTable } from "drizzle-orm/sqlite-core";
import { getOAuthAccountsTableSchema, getSessionsTableSchema, getUsersTableSchema, getEmailVerificationCodesTableSchema, getPasswordResetTokensTableSchema } from "../database/lib/sqlite/schema.sqlite";
import type { tableNames } from "../database/lib/tables";

export type { tableNames };
import { getOAuthAccountsTableSchema, getSessionsTableSchema, getUsersTableSchema, getEmailVerificationCodesTableSchema, getPasswordResetTokensTableSchema } from "../database/sqlite/schema.sqlite";

interface ISessionCreateMetada {
ip?: string
Expand Down Expand Up @@ -78,3 +75,11 @@ const schemasMockValue = {
} satisfies Record<keyof tableNames, SQLiteTable>;
export type SchemasMockValue = typeof schemasMockValue;
// #endregion

export interface tableNames {
users: string
sessions: string
oauthAccounts: string
emailVerificationCodes: string
resetPasswordTokens: string
}
7 changes: 0 additions & 7 deletions src/runtime/database/lib/tables.ts

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { sqliteTable, text, integer, primaryKey } from "drizzle-orm/sqlite-core";
import type { tableNames } from "../tables";
import type { tableNames } from "../../core/types";
import { sql } from "drizzle-orm";

const datesColumns = {
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/nuxt/defaults.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { tableNames } from "../database/lib/tables";
import type { tableNames } from "../core/types";

export const defaultTableNames: tableNames = {
sessions: "slip_auth_sessions",
Expand Down
48 changes: 1 addition & 47 deletions src/runtime/server/utils/useSlipAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,7 @@ import {
// @ts-expect-error useDatabase is not enabled by default
useDatabase,
} from "#imports";
import type { IPinfo } from "node-ipinfo";
import { IPinfoWrapper, ApiLimitError } from "node-ipinfo";
import net from "node:net";
import fsDriver from "unstorage/drivers/fs";
import { createStorage } from "unstorage";
import { setupIpInfoAddOn } from "../../core/plugins/ipInfoPlugin";

let instance: SlipAuthCore;

Expand All @@ -28,45 +24,3 @@ export function useSlipAuth() {

return instance;
}

// TODO: build a plugin system
const setupIpInfoAddOn = (auth: SlipAuthCore, ipInfoToken: string) => {
const ipinfoWrapper = new IPinfoWrapper(ipInfoToken);
const cache = createStorage<IPinfo>({
driver: fsDriver({
base: "./.data/cache/ipinfo",
}),
});

auth.hooks.hook("sessions:create", async (session) => {
session.ip = "92.168.1.58";
if (!session.ip) {
return;
}
const ipType = net.isIP(session.ip);

if (ipType === 0) {
// valid cases are 4 and 6 (ipv)
return;
}

const cachedValue = await cache.getItem(session.ip);
if (cachedValue !== null) {
return;
}

try {
const response = await ipinfoWrapper.lookupIp(session.ip);
cache.setItem(session.ip, response);
}
catch (error) {
console.log(error);
if (error instanceof ApiLimitError) {
// handle api limit exceed error
}
else {
// handle other errors
}
}
});
};

0 comments on commit 1fea643

Please sign in to comment.