Skip to content

Commit

Permalink
more cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
Adammatthiesen committed Dec 12, 2024
1 parent dc0e101 commit c51c3d6
Show file tree
Hide file tree
Showing 12 changed files with 88 additions and 62 deletions.
2 changes: 1 addition & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"editor.gotoLocation.multipleDefinitions": "goto",
"cSpell.words": ["astrojs", "Libravatar", "robotstxt", "studiocms", "withstudiocms"]
"cSpell.words": ["astrojs", "Libravatar", "oslojs", "robotstxt", "studiocms", "withstudiocms"]
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
import { authEnvCheck } from 'studiocms:auth/utils/authEnvCheck';
import Config from 'studiocms:config';
import { AuthConfig } from 'studiocms:config';
import { StudioCMSRoutes } from 'studiocms:lib';

const {
dashboardConfig: {
AuthConfig: { providers },
},
} = Config;
const { providers } = AuthConfig;

const {
authLinks: { googleIndex, auth0Index, discordIndex, githubIndex },
Expand Down
6 changes: 2 additions & 4 deletions packages/studiocms_auth/src/layouts/AuthLayout.astro
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,15 @@ import '@studiocms/ui/css/global.css';
import './authlayout.css';
import { Image } from 'astro:assets';
import { validImages } from 'studiocms:auth/utils/validImages';
import Config from 'studiocms:config';
import { dashboardConfig } from 'studiocms:config';
import studioCMS_SDK from 'studiocms:sdk';
import version from 'studiocms:version';
import onestWoff2 from '@fontsource-variable/onest/files/onest-latin-wght-normal.woff2?url';
import { Toaster } from '@studiocms/ui/components';
import OAuthButtonStack from '../components/OAuthButtonStack.astro';
import StudioCMSLogoSVG from '../components/StudioCMSLogoSVG.astro';
const {
dashboardConfig: { faviconURL },
} = Config;
const { faviconURL } = dashboardConfig;
interface Props {
title: string;
Expand Down
4 changes: 2 additions & 2 deletions packages/studiocms_auth/src/lib/password.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ type RemoveLast<T extends unknown[]> = T extends [...infer Rest, infer _Last] ?
function scrypt(...opts: RemoveLast<Parameters<typeof nodeScrypt>>): Promise<Buffer> {
return new Promise((res, rej) => {
nodeScrypt(...opts, (err, derivedKey) => {
if (err) rej(err)
else res(derivedKey)
if (err) rej(err);
else res(derivedKey);
});
});
}
Expand Down
5 changes: 2 additions & 3 deletions packages/studiocms_auth/src/routes/api/login.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { db, eq } from 'astro:db';
import { verifyPasswordHash } from 'studiocms:auth/lib/password';
import { createUserSession } from 'studiocms:auth/lib/session';
import { tsUsers } from '@studiocms/core/sdk-utils/tables';
import studioCMS_SDK from 'studiocms:sdk';
import type { APIContext, APIRoute } from 'astro';
import { badFormDataEntry, parseFormDataEntryToString } from './shared';

Expand All @@ -18,7 +17,7 @@ export const POST: APIRoute = async (context: APIContext): Promise<Response> =>
if (!password) return badFormDataEntry('Missing field', 'Password is required');

// Get the user from the database
const existingUser = await db.select().from(tsUsers).where(eq(tsUsers.username, username)).get();
const existingUser = await studioCMS_SDK.GET.databaseEntry.users.byUsername(username);

// If the user does not exist, return an ambiguous error
if (!existingUser) return badFormDataEntry('Invalid credentials', 'Invalid username or password');
Expand Down
14 changes: 5 additions & 9 deletions packages/studiocms_auth/src/routes/api/register.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { db, eq } from 'astro:db';
import { verifyPasswordStrength } from 'studiocms:auth/lib/password';
import { createUserSession } from 'studiocms:auth/lib/session';
import { createLocalUser, verifyUsernameInput } from 'studiocms:auth/lib/user';
import { tsUsers } from '@studiocms/core/sdk-utils/tables';
import studioCMS_SDK from 'studiocms:sdk';
import type { APIContext, APIRoute } from 'astro';
import { z } from 'astro/zod';
import { badFormDataEntry, parseFormDataEntryToString } from './shared';
Expand Down Expand Up @@ -44,18 +43,15 @@ export const POST: APIRoute = async (context: APIContext): Promise<Response> =>
if (!name) return badFormDataEntry('Missing entry', 'Display name is required');

// If the email is invalid, return an error
const checkemail = z.coerce
const checkEmail = z.coerce
.string()
.email({ message: 'Email address is invalid' })
.safeParse(email);

if (!checkemail.success) return badFormDataEntry('Invalid email', checkemail.error.message);
if (!checkEmail.success) return badFormDataEntry('Invalid email', checkEmail.error.message);

// Check if the username or email is already used by another user
const [usernameSearch, emailSearch] = await db.batch([
db.select().from(tsUsers).where(eq(tsUsers.username, username)),
db.select().from(tsUsers).where(eq(tsUsers.email, checkemail.data)),
]);
const { usernameSearch, emailSearch } =
await studioCMS_SDK.AUTH.user.searchUsersForUsernameOrEmail(username, checkEmail.data);

if (usernameSearch.length > 0)
return badFormDataEntry('Invalid username', 'Username is already in use');
Expand Down
16 changes: 6 additions & 10 deletions packages/studiocms_auth/src/routes/login.astro
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
import { authEnvCheck } from 'studiocms:auth/utils/authEnvCheck';
import Config from 'studiocms:config';
import { AuthConfig } from 'studiocms:config';
import { getLangFromUrl, staticPaths, useTranslatedPath, useTranslations } from 'studiocms:i18n';
import { StudioCMSRoutes } from 'studiocms:lib';
import { Button, Input } from '@studiocms/ui/components';
Expand All @@ -18,16 +18,12 @@ export const getStaticPaths = (() => {
}) satisfies GetStaticPaths;
const {
dashboardConfig: {
AuthConfig: {
providers,
providers: {
usernameAndPassword,
usernameAndPasswordConfig: { allowUserRegistration },
},
},
providers,
providers: {
usernameAndPassword,
usernameAndPasswordConfig: { allowUserRegistration },
},
} = Config;
} = AuthConfig;
const {
authLinks: { loginAPI, signupURL },
Expand Down
16 changes: 6 additions & 10 deletions packages/studiocms_auth/src/routes/signup.astro
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
import { authEnvCheck } from 'studiocms:auth/utils/authEnvCheck';
import Config from 'studiocms:config';
import { AuthConfig } from 'studiocms:config';
import { getLangFromUrl, staticPaths, useTranslatedPath, useTranslations } from 'studiocms:i18n';
import { StudioCMSRoutes } from 'studiocms:lib';
import { Button, Input } from '@studiocms/ui/components';
Expand All @@ -18,16 +18,12 @@ export const getStaticPaths = (() => {
}) satisfies GetStaticPaths;
const {
dashboardConfig: {
AuthConfig: {
providers,
providers: {
usernameAndPassword,
usernameAndPasswordConfig: { allowUserRegistration },
},
},
providers,
providers: {
usernameAndPassword,
usernameAndPasswordConfig: { allowUserRegistration },
},
} = Config;
} = AuthConfig;
const {
authLinks: { registerAPI, loginURL },
Expand Down
31 changes: 14 additions & 17 deletions packages/studiocms_core/src/integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,21 +39,6 @@ export default defineIntegration({
addVirtualImports(params, {
name,
imports: {
'virtual:studiocms/config': `
export default ${JSON.stringify(options)};
`,
'virtual:studiocms/version': `
export default '${version}';
`,

// Core Virtual Modules
'studiocms:config': `
export default ${JSON.stringify(options)};
`,
'studiocms:version': `
export default '${version}';
`,

// Old Virtual helpers - TO BE REMOVED
'studiocms:helpers': `
export { default as pathGenerators } from '${resolve('./lib/pathGenerators.ts')}';
Expand All @@ -68,6 +53,19 @@ export default defineIntegration({
export * from '${resolve('./lib/routeMap.ts')}';
`,

// Core Virtual Modules
'studiocms:config': `
export default ${JSON.stringify(options)};
export const config = ${JSON.stringify(options)};
export const dashboardConfig = ${JSON.stringify(options.dashboardConfig)};
export const AuthConfig = ${JSON.stringify(options.dashboardConfig.AuthConfig)};
export const developerConfig = ${JSON.stringify(options.dashboardConfig.developerConfig)};
export const defaultFrontEndConfig = ${JSON.stringify(options.defaultFrontEndConfig)};
`,
'studiocms:version': `
export default '${version}';
`,

// Core Virtual Components
'studiocms:components': `
export { default as Avatar } from '${resolve('./components/Avatar.astro')}';
Expand Down Expand Up @@ -122,8 +120,7 @@ export default defineIntegration({
export default studioCMS_SDK_AUTH;
`,
'studiocms:sdk/types': `
import type { STUDIOCMS_SDK } from '${resolve('./sdk-utils/types.ts')}';
export type { STUDIOCMS_SDK };
export * from '${resolve('./sdk-utils/types.ts')}';
`,
},
});
Expand Down
21 changes: 21 additions & 0 deletions packages/studiocms_core/src/sdk-utils/auth/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,27 @@ export const authUser: STUDIOCMS_SDK['AUTH']['user'] = {
throw new StudioCMS_SDK_Error('Error updating user: An unknown error occurred.', `${error}`);
}
},
searchUsersForUsernameOrEmail: async (username, email) => {
try {
const [usernameSearch, emailSearch] = await db.batch([
db.select().from(tsUsers).where(eq(tsUsers.username, username)),
db.select().from(tsUsers).where(eq(tsUsers.email, email)),
]);

return { usernameSearch, emailSearch };
} catch (error) {
if (error instanceof Error) {
throw new StudioCMS_SDK_Error(
`Error searching for username or email: ${error.message}`,
error.stack
);
}
throw new StudioCMS_SDK_Error(
'Error searching for username or email: An unknown error occurred.',
`${error}`
);
}
},
// TODO: Implement delete function that wont error since
// there could be references to the user in other tables
// delete: async () => {},
Expand Down
5 changes: 5 additions & 0 deletions packages/studiocms_core/src/sdk-utils/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -657,6 +657,11 @@ export interface STUDIOCMS_SDK {
*/
update: (userId: string, userData: tsUsersUpdate) => Promise<tsUsersSelect>;

searchUsersForUsernameOrEmail: (
username: string,
email: string
) => Promise<{ usernameSearch: tsUsersSelect[]; emailSearch: tsUsersSelect[] }>;

// delete: async () => {},
};

Expand Down
22 changes: 22 additions & 0 deletions packages/studiocms_core/src/stubs/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,28 @@ dtsFile.addModule('studiocms:config', {
defaultExport: {
typeDef: `import('${resolve('../schemas/config/index.ts')}').StudioCMSConfig`,
},
namedExports: [
{
name: 'config',
typeDef: `import('${resolve('../schemas/config/index.ts')}').StudioCMSConfig`,
},
{
name: 'dashboardConfig',
typeDef: `import('${resolve('../schemas/config/index.ts')}').StudioCMSConfig['dashboardConfig']`,
},
{
name: 'AuthConfig',
typeDef: `import('${resolve('../schemas/config/index.ts')}').StudioCMSConfig['dashboardConfig']['AuthConfig']`,
},
{
name: 'developerConfig',
typeDef: `import('${resolve('../schemas/config/index.ts')}').StudioCMSConfig['dashboardConfig']['developerConfig']`,
},
{
name: 'defaultFrontEndConfig',
typeDef: `import('${resolve('../schemas/config/index.ts')}').StudioCMSConfig['defaultFrontEndConfig']`,
},
],
});

dtsFile.addModule('studiocms:version', {
Expand Down

0 comments on commit c51c3d6

Please sign in to comment.