Skip to content

Commit

Permalink
Refactor import paths and cleanup deprecated content helper functions
Browse files Browse the repository at this point in the history
  • Loading branch information
Adammatthiesen committed Dec 12, 2024
1 parent 6710ef9 commit 9c4cb81
Show file tree
Hide file tree
Showing 12 changed files with 116 additions and 207 deletions.
8 changes: 4 additions & 4 deletions packages/studiocms_auth/src/components/StaticAuthCheck.astro
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ const { isLoggedIn } = await getUserData(Astro);
<div
id="login-check"
style="display: none;"
data-isloggedin={`${isLoggedIn}`}
data-redirectroute={StudioCMSRoutes.mainLinks.dashboardIndex}
data-isLoggedIn={`${isLoggedIn}`}
data-redirectRoute={StudioCMSRoutes.mainLinks.dashboardIndex}
></div>

<script is:inline>
const loginCheck = document.getElementById('login-check');

if (loginCheck.dataset.isloggedin === 'true') {
window.location.href = loginCheck.dataset.redirectroute;
if (loginCheck.dataset.isLoggedIn === 'true') {
window.location.href = loginCheck.dataset.redirectRoute;
}
</script>
56 changes: 18 additions & 38 deletions packages/studiocms_auth/src/routes/api/auth0/callback.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,12 @@
import { logger } from '@it-astro:logger:studiocms-auth';
import { and, db, eq } from 'astro:db';
import { createUserSession } from 'studiocms:auth/lib/session';
import { LinkNewOAuthCookieName, createOAuthUser, getUserData } from 'studiocms:auth/lib/user';
import { StudioCMSRoutes } from 'studiocms:lib';
import { tsOAuthAccounts, tsUsers } from '@studiocms/core/sdk-utils/tables';
import studioCMS_SDK from 'studiocms:sdk';
import { OAuth2RequestError, type OAuth2Tokens } from 'arctic';
import type { APIContext, APIRoute } from 'astro';
import { type Auth0User, ProviderCookieName, ProviderID, auth0, getClientDomain } from './shared';

const {
authLinks: { loginURL },
mainLinks: { dashboardIndex },
} = StudioCMSRoutes;

export const GET: APIRoute = async (context: APIContext): Promise<Response> => {
const { url, cookies, redirect } = context;

Expand All @@ -23,7 +17,7 @@ export const GET: APIRoute = async (context: APIContext): Promise<Response> => {
const CLIENT_DOMAIN = getClientDomain();

if (!code || !state || !storedState || state !== storedState) {
return redirect(loginURL);
return redirect(StudioCMSRoutes.authLinks.loginURL);
}

let tokens: OAuth2Tokens;
Expand All @@ -46,23 +40,13 @@ export const GET: APIRoute = async (context: APIContext): Promise<Response> => {
// // TODO: Add first-time setup logic here
// }

const existingoAuthAccount = await db
.select()
.from(tsOAuthAccounts)
.where(
and(
eq(tsOAuthAccounts.provider, ProviderID),
eq(tsOAuthAccounts.providerUserId, auth0UserId)
)
)
.get();

if (existingoAuthAccount) {
const user = await db
.select()
.from(tsUsers)
.where(eq(tsUsers.id, existingoAuthAccount.userId))
.get();
const existingOAuthAccount = await studioCMS_SDK.AUTH.oAuth.searchProvidersForId(
ProviderID,
auth0UserId
);

if (existingOAuthAccount) {
const user = await studioCMS_SDK.GET.databaseEntry.users.byId(existingOAuthAccount.userId);

if (!user) {
return new Response('User not found', {
Expand All @@ -72,29 +56,25 @@ export const GET: APIRoute = async (context: APIContext): Promise<Response> => {

await createUserSession(user.id, context);

return redirect(dashboardIndex);
return redirect(StudioCMSRoutes.mainLinks.dashboardIndex);
}

const loggedInUser = await getUserData(context);
const linkNewOAuth = !!cookies.get(LinkNewOAuthCookieName)?.value;

if (loggedInUser.user && linkNewOAuth) {
const exisitingUser = await db
.select()
.from(tsUsers)
.where(eq(tsUsers.id, loggedInUser.user.id))
.get();

if (exisitingUser) {
await db.insert(tsOAuthAccounts).values({
const existingUser = await studioCMS_SDK.GET.databaseEntry.users.byId(loggedInUser.user.id);

if (existingUser) {
await studioCMS_SDK.AUTH.oAuth.create({
userId: existingUser.id,
provider: ProviderID,
providerUserId: auth0UserId,
userId: exisitingUser.id,
});

await createUserSession(exisitingUser.id, context);
await createUserSession(existingUser.id, context);

return redirect(dashboardIndex);
return redirect(StudioCMSRoutes.mainLinks.dashboardIndex);
}
}

Expand All @@ -116,7 +96,7 @@ export const GET: APIRoute = async (context: APIContext): Promise<Response> => {

await createUserSession(newUser.id, context);

return redirect(dashboardIndex);
return redirect(StudioCMSRoutes.mainLinks.dashboardIndex);
} catch (e) {
// the specific error message depends on the provider
if (e instanceof OAuth2RequestError) {
Expand Down
23 changes: 7 additions & 16 deletions packages/studiocms_auth/src/routes/api/auth0/shared.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,23 @@
import { authEnvCheck } from 'studiocms:auth/utils/authEnvCheck';
import Config from 'studiocms:config';
import { AuthConfig } from 'studiocms:config';
import { Auth0 } from 'arctic';

export const {
AUTH0: { CLIENT_ID, CLIENT_SECRET, DOMAIN, REDIRECT_URI },
} = await authEnvCheck(Config.dashboardConfig.AuthConfig.providers);
AUTH0: { CLIENT_ID = '', CLIENT_SECRET = '', DOMAIN, REDIRECT_URI = '' },
} = await authEnvCheck(AuthConfig.providers);

export const getClientDomain = () => {
const cleanDomainslash = DOMAIN ? DOMAIN.replace(/^\//, '') : '';
const cleanDomainSlash = DOMAIN ? DOMAIN.replace(/^\//, '') : '';

const NoHTTPDOMAIN = cleanDomainslash.replace(/http:\/\//, '').replace(/https:\/\//, '');
const NoHttpDomain = cleanDomainSlash.replace(/http:\/\//, '').replace(/https:\/\//, '');

return `https://${NoHTTPDOMAIN}`;
};

const CLIENT = () => {
return {
DOMAIN: getClientDomain(),
ID: CLIENT_ID || '',
SECRET: CLIENT_SECRET || '',
URI: REDIRECT_URI || '',
};
return `https://${NoHttpDomain}`;
};

export const ProviderID = 'auth0';
export const ProviderCookieName = 'auth0_oauth_state';

export const auth0 = new Auth0(CLIENT().DOMAIN, CLIENT().ID, CLIENT().SECRET, CLIENT().URI);
export const auth0 = new Auth0(getClientDomain(), CLIENT_ID, CLIENT_SECRET, REDIRECT_URI);

export interface Auth0User {
sub: string;
Expand Down
50 changes: 15 additions & 35 deletions packages/studiocms_auth/src/routes/api/discord/callback.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,12 @@
import { logger } from '@it-astro:logger:studiocms-auth';
import { and, db, eq } from 'astro:db';
import { createUserSession } from 'studiocms:auth/lib/session';
import { LinkNewOAuthCookieName, createOAuthUser, getUserData } from 'studiocms:auth/lib/user';
import { StudioCMSRoutes } from 'studiocms:lib';
import { tsOAuthAccounts, tsUsers } from '@studiocms/core/sdk-utils/tables';
import studioCMS_SDK from 'studiocms:sdk';
import { OAuth2RequestError, type OAuth2Tokens } from 'arctic';
import type { APIContext, APIRoute } from 'astro';
import { type DiscordUser, ProviderCookieName, ProviderID, discord } from './shared';

const {
authLinks: { loginURL },
mainLinks: { dashboardIndex },
} = StudioCMSRoutes;

export const GET: APIRoute = async (context: APIContext): Promise<Response> => {
const { url, cookies, redirect } = context;

Expand All @@ -21,7 +15,7 @@ export const GET: APIRoute = async (context: APIContext): Promise<Response> => {
const storedState = cookies.get(ProviderCookieName)?.value ?? null;

if (!code || !state || !storedState || state !== storedState) {
return redirect(loginURL);
return redirect(StudioCMSRoutes.authLinks.loginURL);
}

let tokens: OAuth2Tokens;
Expand All @@ -44,23 +38,13 @@ export const GET: APIRoute = async (context: APIContext): Promise<Response> => {
// // TODO: Add first-time setup logic here
// }

const existingoAuthAccount = await db
.select()
.from(tsOAuthAccounts)
.where(
and(
eq(tsOAuthAccounts.provider, ProviderID),
eq(tsOAuthAccounts.providerUserId, discordUserId)
)
)
.get();

if (existingoAuthAccount) {
const user = await db
.select()
.from(tsUsers)
.where(eq(tsUsers.id, existingoAuthAccount.userId))
.get();
const existingOAuthAccount = await studioCMS_SDK.AUTH.oAuth.searchProvidersForId(
ProviderID,
discordUserId
);

if (existingOAuthAccount) {
const user = await studioCMS_SDK.GET.databaseEntry.users.byId(existingOAuthAccount.userId);

if (!user) {
return new Response('User not found', {
Expand All @@ -70,29 +54,25 @@ export const GET: APIRoute = async (context: APIContext): Promise<Response> => {

await createUserSession(user.id, context);

return redirect(dashboardIndex);
return redirect(StudioCMSRoutes.mainLinks.dashboardIndex);
}

const loggedInUser = await getUserData(context);
const linkNewOAuth = !!cookies.get(LinkNewOAuthCookieName)?.value;

if (loggedInUser.user && linkNewOAuth) {
const existingUser = await db
.select()
.from(tsUsers)
.where(eq(tsUsers.id, loggedInUser.user.id))
.get();
const existingUser = await studioCMS_SDK.GET.databaseEntry.users.byId(loggedInUser.user.id);

if (existingUser) {
await db.insert(tsOAuthAccounts).values({
await studioCMS_SDK.AUTH.oAuth.create({
userId: existingUser.id,
provider: ProviderID,
providerUserId: discordUserId,
userId: existingUser.id,
});

await createUserSession(existingUser.id, context);

return redirect(dashboardIndex);
return redirect(StudioCMSRoutes.mainLinks.dashboardIndex);
}
}

Expand All @@ -116,7 +96,7 @@ export const GET: APIRoute = async (context: APIContext): Promise<Response> => {

await createUserSession(newUser.id, context);

return redirect(dashboardIndex);
return redirect(StudioCMSRoutes.mainLinks.dashboardIndex);
} catch (e) {
// the specific error message depends on the provider
if (e instanceof OAuth2RequestError) {
Expand Down
16 changes: 4 additions & 12 deletions packages/studiocms_auth/src/routes/api/discord/shared.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,15 @@
import { authEnvCheck } from 'studiocms:auth/utils/authEnvCheck';
import Config from 'studiocms:config';
import { AuthConfig } from 'studiocms:config';
import { Discord } from 'arctic';

export const {
DISCORD: { CLIENT_ID, CLIENT_SECRET, REDIRECT_URI },
} = await authEnvCheck(Config.dashboardConfig.AuthConfig.providers);

const CLIENT = () => {
return {
ID: CLIENT_ID || '',
SECRET: CLIENT_SECRET || '',
URI: REDIRECT_URI || '',
};
};
DISCORD: { CLIENT_ID = '', CLIENT_SECRET = '', REDIRECT_URI = '' },
} = await authEnvCheck(AuthConfig.providers);

export const ProviderID = 'discord';
export const ProviderCookieName = 'discord_oauth_state';

export const discord = new Discord(CLIENT().ID, CLIENT().SECRET, CLIENT().URI);
export const discord = new Discord(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI);

export interface DiscordUser {
id: string;
Expand Down
Loading

0 comments on commit 9c4cb81

Please sign in to comment.