Skip to content

Commit

Permalink
Update auth.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
Denys Dinkevych authored Nov 18, 2024
1 parent 2cf6d2a commit 5e2762f
Showing 1 changed file with 26 additions and 6 deletions.
32 changes: 26 additions & 6 deletions netlify/functions/auth.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,26 @@
import { Handler } from '@netlify/functions';

const handler: Handler = async (event) => {
if (event.httpMethod !== 'POST') {
// Handle both POST and GET requests
if (event.httpMethod !== 'POST' && event.httpMethod !== 'GET') {
return { statusCode: 405, body: 'Method Not Allowed' };
}

try {
const { code } = JSON.parse(event.body || '{}');

// Extract the code based on the request method
const code =
event.httpMethod === 'POST'
? JSON.parse(event.body || '{}').code
: event.queryStringParameters?.code;

if (!code) {
return {
statusCode: 400,
body: 'Bad Request: Missing code parameter',
};
}

// Exchange the code for an access token
const response = await fetch('https://github.com/login/oauth/access_token', {
method: 'POST',
headers: {
Expand All @@ -23,17 +36,24 @@ const handler: Handler = async (event) => {

const data = await response.json();

if (data.error) {
return {
statusCode: 400,
body: JSON.stringify({ error: data.error_description || 'Failed to retrieve access token' }),
};
}

return {
statusCode: 200,
body: JSON.stringify(data),
body: JSON.stringify(data), // Return access token and additional info
};
} catch (error) {
console.error('Auth error:', error);
return {
statusCode: 500,
body: JSON.stringify({ error: 'Failed to exchange code for token' }),
body: JSON.stringify({ error: 'Internal Server Error' }),
};
}
};

export { handler };
export { handler };

0 comments on commit 5e2762f

Please sign in to comment.