Skip to content

Commit

Permalink
aa debug
Browse files Browse the repository at this point in the history
  • Loading branch information
Joabesv committed Sep 21, 2024
1 parent 67e0ffb commit feac2ca
Show file tree
Hide file tree
Showing 4 changed files with 145 additions and 81 deletions.
2 changes: 2 additions & 0 deletions apps/core/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { publicModule } from './modules/public/public.module.js';
import { userModule } from './modules/user/user.module.js';
import { syncModule } from './modules/sync/sync.module.js';
import { backOfficeModule } from './modules/backoffice/backoffice.module.js';
import Oauth2Debug from './plugins/oauth2/oauthFixed.js';
import { nextJobs } from './queue/NextJobs.js';
import { nextWorker } from './queue/NextWorker.js';
import { connect } from 'mongoose';
Expand All @@ -18,6 +19,7 @@ export async function buildApp(opts: FastifyServerOptions = {}) {
try {
httpErrorsValidator(app);
await loadPlugins(app);
await app.register(Oauth2Debug, Config);
await app.register(userModule, {
prefix: '/v2',
});
Expand Down
16 changes: 8 additions & 8 deletions apps/core/src/plugins.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Cors from './plugins/cors.js';
import JwtAuth from './plugins/jwt.js';
import Oauth2 from './plugins/oauth2/oauth2.js';
// import Oauth2 from './plugins/oauth2/oauth2.js';
import Swagger from './plugins/swagger.js';
import Sensible from './plugins/sensible.js';
import { Config } from './config/config.js';
Expand All @@ -9,17 +9,17 @@ import type { FastifyInstance } from 'fastify';
export async function loadPlugins(app: FastifyInstance) {
await Promise.all([
app.register(Cors, {
origins: Config.ALLOWED_ORIGINS
origins: Config.ALLOWED_ORIGINS,
}),
app.register(JwtAuth, {
secret: Config.JWT_SECRET,
}),
app.register(Oauth2, {
googleId: Config.OAUTH_GOOGLE_CLIENT_ID,
googleSecret: Config.OAUTH_GOOGLE_SECRET,
facebookId: '',
facebookSecret: '',
}),
// app.register(Oauth2, {
// googleId: Config.OAUTH_GOOGLE_CLIENT_ID,
// googleSecret: Config.OAUTH_GOOGLE_SECRET,
// facebookId: '',
// facebookSecret: '',
// }),
app.register(Swagger),
app.register(Sensible),
]);
Expand Down
148 changes: 75 additions & 73 deletions apps/core/src/plugins/oauth2/oauth2.ts
Original file line number Diff line number Diff line change
@@ -1,81 +1,83 @@
import { type OAuth2Namespace, fastifyOauth2 } from '@fastify/oauth2';
import { fastifyPlugin as fp } from 'fastify-plugin';
import { Config } from '@/config/config.js';
import { objectKeys } from './utils/objectKeys.js';
import { type Querystring, handleOauth } from './handler.js';
import { supportedProviders } from './supportedProviders.js';
import type { FastifyInstance, FastifyRequest } from 'fastify';
// import { type OAuth2Namespace, fastifyOauth2 } from '@fastify/oauth2';
// import { fastifyPlugin as fp } from 'fastify-plugin';
// import { Config } from '@/config/config.js';
// import { objectKeys } from './utils/objectKeys.js';
// import { type Querystring, handleOauth } from './handler.js';
// import { supportedProviders } from './supportedProviders.js';
// import type { FastifyInstance, FastifyRequest } from 'fastify';

export type NextOauthOptions = {
googleId: Config['OAUTH_GOOGLE_CLIENT_ID'];
googleSecret: Config['OAUTH_GOOGLE_SECRET'];
facebookId?: string;
facebookSecret?: string;
};
// export type NextOauthOptions = {
// googleId: Config['OAUTH_GOOGLE_CLIENT_ID'];
// googleSecret: Config['OAUTH_GOOGLE_SECRET'];
// facebookId?: string;
// facebookSecret?: string;
// };

async function oauth2(app: FastifyInstance, opts: NextOauthOptions) {
const providers = supportedProviders(opts, fastifyOauth2);
// async function oauth2(app: FastifyInstance, opts: NextOauthOptions) {
// const providers = supportedProviders(opts, fastifyOauth2);

for (const provider of objectKeys(providers)) {
const startRedirectPath = `/login/${provider}`;
await app.register(fastifyOauth2, {
name: provider,
credentials: {
client: {
id: providers[provider].credentials.client.id,
secret: providers[provider].credentials.client.secret,
},
auth: providers[provider].config,
},
scope: providers[provider].scope,
callbackUri: (req) => {
return `${Config.PROTOCOL}://${req.hostname}/login/${provider}/callback`;
},
});
// for (const provider of objectKeys(providers)) {
// const startRedirectPath = `/login/${provider}`;
// await app.register(fastifyOauth2, {
// name: provider,
// credentials: {
// client: {
// id: providers[provider].credentials.client.id,
// secret: providers[provider].credentials.client.secret,
// },
// auth: providers[provider].config,
// },
// scope: providers[provider].scope,
// callbackUri: (req) => {
// return `${Config.PROTOCOL}://${req.hostname}/login/${provider}/callback`;
// },
// });

app.get(`/login/google`, async function (request, reply) {
try {
const validatedURI = await this[provider].generateAuthorizationUri(
request,
reply,
);
request.log.warn(validatedURI, 'redirecting to');
return reply.redirect(validatedURI);
} catch (error) {
request.log.warn(error);
}
});
// app.log.warn(provider);

app.get(
`/login/google/callback`,
async function (
request: FastifyRequest<{ Querystring: Querystring }>,
reply,
) {
try {
await handleOauth.call(this, provider, request, reply, providers);
} catch (error: any) {
if (error?.data?.payload) {
reply.log.error({ error: error.data.payload }, 'Error in oauth2');
return error.data.payload;
}
// app.get(`/login/${provider}`, async function (request, reply) {
// try {
// const validatedURI = await this[provider].generateAuthorizationUri(
// request,
// reply,
// );
// request.log.warn(validatedURI, 'redirecting to');
// return reply.redirect(validatedURI);
// } catch (error) {
// request.log.warn(error);
// }
// });

// Unknwon (probably db) error
request.log.warn(error, 'deu merda severa');
return reply.internalServerError(
'Algo de errado aconteceu no seu login, tente novamente',
);
}
},
);
}
}
// app.get(
// `/login/${provider}/callback`,
// async function (
// request: FastifyRequest<{ Querystring: Querystring }>,
// reply,
// ) {
// try {
// await handleOauth.call(this, provider, request, reply, providers);
// } catch (error: any) {
// if (error?.data?.payload) {
// reply.log.error({ error: error.data.payload }, 'Error in oauth2');
// return error.data.payload;
// }

export default fp(oauth2, { name: 'NextOauth2' });
// // Unknwon (probably db) error
// request.log.warn(error, 'deu merda severa');
// return reply.internalServerError(
// 'Algo de errado aconteceu no seu login, tente novamente',
// );
// }
// },
// );
// }
// }

declare module 'fastify' {
export interface FastifyInstance {
google: OAuth2Namespace;
facebook: OAuth2Namespace;
}
}
// export default fp(oauth2, { name: 'NextOauth2' });

// declare module 'fastify' {
// export interface FastifyInstance {
// google: OAuth2Namespace;
// facebook: OAuth2Namespace;
// }
// }
60 changes: 60 additions & 0 deletions apps/core/src/plugins/oauth2/oauthFixed.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { fastifyPlugin as fp } from 'fastify-plugin';
import { fastifyOauth2, type OAuth2Namespace } from '@fastify/oauth2';
import type { FastifyInstance } from 'fastify';
import { Config } from '@/config/config.js';

async function oauth2Debug(app: FastifyInstance, opts: Record<string, string>) {
await app.register(fastifyOauth2, {
name: 'google',
credentials: {
client: {
id: opts.OAUTH_GOOGLE_CLIENT_ID,
secret: opts.OAUTH_GOOGLE_SECRET,
},
auth: fastifyOauth2.GOOGLE_CONFIGURATION,
},
scope: ['profile', 'email'],
callbackUri: (req) =>
`${Config.PROTOCOL}://${req.hostname}/login/google/callback`,
});

app.get('/login/google', async function (request, reply) {
try {
const oauthRedirectURI = await this.google.generateAuthorizationUri(
request,
reply,
);
request.log.warn(oauthRedirectURI, 'redirecting to');
return reply.redirect(oauthRedirectURI);
} catch (error) {
request.log.warn(error);
}
});

app.get('/login/google/callback', async function (request, reply) {
try {
const { token } =
await this.google.getAccessTokenFromAuthorizationCodeFlow(request);
return token.access_token;
} catch (error) {
if (error?.data?.payload) {
reply.log.error({ error: error.data.payload }, 'Error in oauth2');
return error.data.payload;
}

reply.log.warn(error, 'error');
return reply.status(500).send({
error,
msg: 'deu pau',
});
}
});
}

export default fp(oauth2Debug, { name: 'NextOauth2' });

declare module 'fastify' {
export interface FastifyInstance {
google: OAuth2Namespace;
}
}

0 comments on commit feac2ca

Please sign in to comment.