studiocms
Version:
Astro Native CMS for AstroDB. Built from the ground up by the Astro community.
83 lines (82 loc) • 2.76 kB
JavaScript
import { eq } from "astro:db";
import { GhostUserDefaults } from "../../../consts.js";
import { Effect } from "../../../effect.js";
import { SDKCoreError, StudioCMS_SDK_Error } from "../errors.js";
import {
tsDiffTracking,
tsOAuthAccounts,
tsPageData,
tsPermissions,
tsSessionTable,
tsUserResetTokens
} from "../tables.js";
import { AstroDB } from "./db.js";
class SDKCore_Users extends Effect.Service()("studiocms/sdk/SDKCore_Users", {
effect: Effect.gen(function* () {
const dbService = yield* AstroDB;
const verifyRank = (users, permissions, rank) => Effect.try({
try: () => {
const filteredUsers = permissions.filter((user) => user.rank === rank);
const permitted = [];
for (const user of filteredUsers) {
const foundUser = users.find((u) => u.id === user.user);
if (foundUser) {
permitted.push({ id: foundUser.id, name: foundUser.name });
}
}
return permitted;
},
catch: (error) => new SDKCoreError({
type: "UNKNOWN",
cause: new StudioCMS_SDK_Error(`verifyRank Error: ${error}`)
})
});
const combineRanks = (rank, users) => Effect.try({
try: () => users.map((user) => ({ rank, ...user })),
catch: (error) => new SDKCoreError({
type: "UNKNOWN",
cause: new StudioCMS_SDK_Error(`combineRanks Error: ${error}`)
})
});
const clearUserReferences = (userId) => Effect.gen(function* () {
yield* dbService.execute(
(db) => db.delete(tsUserResetTokens).where(eq(tsUserResetTokens.userId, userId))
);
yield* dbService.execute(
(db) => db.delete(tsPermissions).where(eq(tsPermissions.user, userId))
);
yield* dbService.execute(
(db) => db.delete(tsOAuthAccounts).where(eq(tsOAuthAccounts.userId, userId))
);
yield* dbService.execute(
(db) => db.delete(tsSessionTable).where(eq(tsSessionTable.userId, userId))
);
yield* dbService.execute(
(db) => db.update(tsDiffTracking).set({ userId: GhostUserDefaults.id }).where(eq(tsDiffTracking.userId, userId))
);
yield* dbService.execute(
(db) => db.update(tsPageData).set({ authorId: GhostUserDefaults.id }).where(eq(tsPageData.authorId, userId))
);
return true;
}).pipe(
Effect.catchTags({
LibSQLClientError: (cause) => Effect.fail(
new SDKCoreError({
type: "LibSQLDatabaseError",
cause: new StudioCMS_SDK_Error(`Error collecting page data: ${cause}`)
})
)
})
);
return {
verifyRank,
combineRanks,
clearUserReferences
};
}),
dependencies: [AstroDB.Default]
}) {
}
export {
SDKCore_Users
};