Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 17 additions & 21 deletions config/passport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,27 +10,9 @@ import { authUrl, hostUrl } from '../src/urls';
*/
const GitHubStrategy = passportGitHub.Strategy;

/**
* Serializes user profile returned after authentication.
*
* @param {object} user User profile
* @param {function} done Method called internally by passport.js to resume
* process
*/
passport.serializeUser((user, done) => {
done(null, user);
});

/**
* Deserializes cookie sent to know which user is logged in.
*
* @param {object} user The GitHub profile of the user
* @param {function} done Method called internally by passport.js to resume
* process
*/
passport.deserializeUser((user, done) => {
done(null, user);
});
console.log('Configuring GitHub strategy with callback URL:', `${hostUrl}${authUrl.callback}`);
console.log('GitHub client ID is set:', !!githubOauth.GITHUB_CLIENT_ID);
console.log('GitHub client secret is set:', !!githubOauth.GITHUB_CLIENT_SECRET);

/**
* GitHub OAuth strategy configuration.
Expand All @@ -42,7 +24,21 @@ passport.use(new GitHubStrategy({
clientID: githubOauth.GITHUB_CLIENT_ID,
clientSecret: githubOauth.GITHUB_CLIENT_SECRET,
callbackURL: `${hostUrl}${authUrl.callback}`,
scope: ['gist'],
}, (accessToken, refreshToken, profile, done) => {
console.log('GitHub OAuth callback received');

if (!profile) {
console.error('No profile received from GitHub');
return done(new Error('Failed to retrieve GitHub profile'));
}

if (!accessToken) {
console.error('No access token received from GitHub');
return done(new Error('No access token provided'));
}

console.log('GitHub OAuth successful for user:', profile.username ?? profile.displayName ?? 'Unknown');
done(null, { ...profile, accessToken });
}));

Expand Down
73 changes: 24 additions & 49 deletions src/app.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,12 @@
import bodyParser from 'body-parser';
import connectRedis, { RedisStore } from 'connect-redis';
import cors from 'cors';
import express from 'express';
import session from 'express-session';
import passport from 'passport';
import redis from 'redis';

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove the dependency then

import {
cookieExpiry,
redisConfiguration,
sessionSecret,
allowedOrigins,
} from '../config/index';
import AuthController from './controllers/auth';
import Controller from './controllers/base';
import GistController from './controllers/gist';
import HomeController from './controllers/home';

/**
Expand All @@ -24,67 +17,28 @@ class App {
* Stores the constructor of Express application.
*/
public app: express.Application;
public redisClient: redis.RedisClient;
public redisStore: RedisStore;

/**
* Constructor to initialize application.
*/
constructor() {
this.app = express();
this.redisClient = redis.createClient(
redisConfiguration.REDIS_PORT,
redisConfiguration.REDIS_HOST
);
if (redisConfiguration.REDIS_PASSWORD) {
this.redisClient.auth(redisConfiguration.REDIS_PASSWORD, error => {
console.error(error);
});
}
this.redisStore = connectRedis(session);
this.initializeMiddleWares();
this.initializeControllers([
new AuthController(),
new HomeController(),
new GistController(),
new HomeController()
]);
}

/**
* Initializes middleware for accessing request and response objects.
*/
private initializeMiddleWares() {
// Configuration for creating session cookies.
const redisStore = this.redisStore;
this.app.use(
session({
name: 'vega_session',
secret: sessionSecret,
resave: false,
saveUninitialized: false,
store: new redisStore({
host: redisConfiguration.REDIS_HOST,
port: redisConfiguration.REDIS_PORT,
client: this.redisClient,
ttl: cookieExpiry,
}),
/**
* `cookieExpiry` is converted to milliseconds. Reference:
* https://www.npmjs.com/package/express-session#cookiemaxage
*/
cookie: {
maxAge: cookieExpiry * 1000,
secure: process.env.NODE_ENV === 'production',
sameSite: 'none',
},
rolling: true,
})
);
this.app.use(bodyParser.json());

const corsOptions = {
origin: (origin, callback) => {
if (!origin || allowedOrigins.includes(origin)) {
if (!origin || origin === 'null' || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
Expand All @@ -94,7 +48,28 @@ class App {
};
this.app.use(cors(corsOptions));
this.app.use(passport.initialize());
this.app.use(passport.session());

// Handle preflight OPTIONS requests explicitly (required for CORS)
this.app.options('*', (req, res) => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need to handle preflight? Is that needed for something in auth?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah I was getting a bunch of CORS issues without them

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see let's say in the comment that it's needed for cors

const origin = req.headers.origin || '*';

if (origin === 'null') {
res.header('Access-Control-Allow-Origin', 'null');
} else {
res.header('Access-Control-Allow-Origin', origin);
}

// Needed to handle CORS preflight requests.
// i.e. tell browsers which origins, methods, are allowed.


res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we really need these?

res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Auth-Token, Cache-Control, Pragma, Expires');
// Without this, browsers may block cross-origin requests, especially when credentials are involved.
res.header('Access-Control-Allow-Credentials', 'true');
res.header('Access-Control-Expose-Headers', 'Content-Type, Authorization, X-Auth-Token');
res.status(200).end();
});

// Put IP of https://vega.github.io/editor instead of 1
this.app.set('trust proxy', 1);
Expand Down
Loading