Skip to content

Commit

Permalink
added supabase auth
Browse files Browse the repository at this point in the history
  • Loading branch information
alisryan committed Sep 5, 2024
1 parent 84a5988 commit e5532c5
Show file tree
Hide file tree
Showing 23 changed files with 616 additions and 135 deletions.
8 changes: 8 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
NODE_ENV=development
PORT=3000
MONGO_PATH="mongodb+srv://user:dbUserPassword@snappercluster.i3fur.mongodb.net/?retryWrites=true&w=majority&appName=SnapperCluster"
MONGO_USERNAME="user"
MONGO_PASSWORD="dbUserPassword"
SUPABASE_PASSWORD="9waZ2NQKum6FmP$"
SUPABASE_URL="https://xcgzrcnpyoxwxbjwnfnn.supabase.co"
SUPABASE_KEY="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhjZ3pyY25weW94d3hianduZm5uIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MjU1NTMxOTUsImV4cCI6MjA0MTEyOTE5NX0.NgMdOTtSCbMdxkrzCgNYCyKBSLpzPuyARB8qnn3NKNo"
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,7 @@ coverage/
coverage-final.json

#Build output
build/
build/

# MongoDB data directory
/data/
4 changes: 4 additions & 0 deletions backend/.env
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
NODE_ENV=development
PORT=3000
MONGO_PATH=
MONGO_URL=mongodb+srv://user:dbUserPassword@snappercluster.i3fur.mongodb.net/?retryWrites=true&w=majority&appName=SnapperCluster;
MONGO_USERNAME="user"
MONGO_PASSWORD="dbUserPassword"
SUPABASE_PASSWORD="9waZ2NQKum6FmP$"
SUPABASE_URL="https://xcgzrcnpyoxwxbjwnfnn.supabase.co"
SUPABASE_KEY="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhjZ3pyY25weW94d3hianduZm5uIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MjU1NTMxOTUsImV4cCI6MjA0MTEyOTE5NX0.NgMdOTtSCbMdxkrzCgNYCyKBSLpzPuyARB8qnn3NKNo"
293 changes: 279 additions & 14 deletions backend/package-lock.json

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,17 @@
"ts-jest": "^29.2.5",
"ts-node": "^10.9.2",
"tsc-watch": "^6.2.0",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.5.4"
},
"dependencies": {
"@supabase/supabase-js": "^2.45.3",
"@types/express-session": "^1.18.0",
"@types/supertest": "^6.0.2",
"connect-mongo": "^5.1.0",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"express-session": "^1.18.0",
"jest": "^29.7.0",
"mongodb": "^6.8.0",
"mongodb-memory-server": "^10.0.0",
Expand Down
26 changes: 26 additions & 0 deletions backend/src/__tests__/ping.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import request from 'supertest';
import express from 'express';
import pingRoute from '../routes/healthcheck'; // Adjust to the correct file path

jest.mock('../middlewares/authMiddleware', () => ({
isAuthenticated: (
req: express.Request,
res: express.Response,
next: express.NextFunction,
) => {
return next();
},
}));

const app = express();
const router = express.Router();
pingRoute(router);
app.use(router);

describe('GET /ping', () => {
it('should return 200 with "hello: world"', async () => {
const res = await request(app).get('/ping');
expect(res.status).toBe(200);
expect(res.body).toEqual({ hello: 'world' });
});
});
62 changes: 0 additions & 62 deletions backend/src/__tests__/register.test.ts

This file was deleted.

9 changes: 8 additions & 1 deletion backend/src/config/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@ dotenv.config();

const MONGO_USERNAME = process.env.MONGO_USERNAME || '';
const MONGO_PASSWORD = process.env.MONGO_PASSWORD || '';
const MONGO_URL = `mongodb+srv://user:dbUserPassword@snappercluster.i3fur.mongodb.net/?retryWrites=true&w=majority&appName=SnapperCluster`;
const MONGO_URL = process.env.MONGO_URL || '';

const SERVER_PORT = process.env.SERVER_PORT
? Number(process.env.SERVER_PORT)
: 1337;

const SUPABASE_URL = process.env.SUPABASE_URL || '';
const SUPABASE_KEY = process.env.SUPABASE_KEY || '';

export const config = {
mongo: {
username: MONGO_USERNAME,
Expand All @@ -19,4 +22,8 @@ export const config = {
server: {
port: SERVER_PORT,
},
supabase: {
url: SUPABASE_URL,
key: SUPABASE_KEY,
},
};
16 changes: 16 additions & 0 deletions backend/src/config/sessionConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import session from 'express-session';
import MongoStore from 'connect-mongo';
import dotenv from 'dotenv';

dotenv.config();

export const sessionMiddleware = session({
secret: process.env.SESSION_SECRET || 'your-secret-key',
resave: false,
saveUninitialized: false,
store: MongoStore.create({
mongoUrl: process.env.MONGO_URL,
collectionName: 'sessions',
}),
cookie: { maxAge: 30 * 24 * 60 * 60 * 1000 },
});
4 changes: 4 additions & 0 deletions backend/src/config/supabaseClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { createClient } from '@supabase/supabase-js';
import { config } from './config';

export const supabase = createClient(config.supabase.url, config.supabase.key);
76 changes: 76 additions & 0 deletions backend/src/controllers/authController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// import express from 'express';
// import { supabase } from '../config/supabaseClient';
// import { createUser } from '../services/userService';
// import session from 'express-session';

// export const register = async (req: express.Request, res: express.Response) => {
// try {
// const { email, password, username } = req.body;

// if (!email || !password || !username) {
// return res.status(400).json({ error: 'Missing required fields' });
// }

// const { data, error } = await supabase.auth.signUp({ email, password });

// if (error) {
// console.error('Supabase signUp error:', error.message);
// return res.status(400).json({ error: error.message });
// }

// const user = data.user;
// if (!user) {
// console.error('User creation failed: no user returned from Supabase');
// return res.status(400).json({ error: 'User creation failed' });
// }

// await createUser({ email, username, supabaseId: user.id });

// req.session.userId = req.session ? user.id : undefined;

// return res.status(200).json({ message: 'User registered successfully', user });
// } catch (err) {
// console.error('Registration error:', err);
// return res.status(500).json({ error: 'Internal server error' });
// }
// };

// export const login = async (req: express.Request, res: express.Response) => {
// const { email, password } = req.body;

// if (!email || !password) {
// return res.status(400).json({ error: 'Missing required fields' });
// }

// const { data, error } = await supabase.auth.signInWithPassword({ email, password });

// if (error) {
// return res.status(400).json({ error: error.message });
// }

// const user = data.user;

// if (!user) {
// return res.status(400).json({ error: 'Login failed' });
// }

// req.session.userId = req.session ? user.id : undefined;

// return res.status(200).json({ message: 'Login successful', user });
// };

// export const logout = async (req: express.Request, res: express.Response) => {
// const { error } = await supabase.auth.signOut();

// if (error) {
// return res.status(400).json({ error: 'Failed to log out' });
// }

// req.session.destroy((err) => {
// if (err) {
// return res.status(500).json({ error: 'Failed to destroy session' });
// }

// return res.status(200).json({ message: 'Logout successful' });
// });
// };
25 changes: 0 additions & 25 deletions backend/src/controllers/authentification.ts

This file was deleted.

42 changes: 42 additions & 0 deletions backend/src/controllers/authentification/login.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import express from 'express';
import { supabase } from '../../config/supabaseClient';

export const login = async (req: express.Request, res: express.Response) => {
try {
const { email, password } = req.body;

if (!email || !password) {
return res
.status(400)
.json({ error: 'Email and password are required.' });
}

const { data, error } = await supabase.auth.signInWithPassword({
email,
password,
});

if (error) {
return res
.status(400)
.json({ error: 'Invalid email or password. Please try again.' });
}

const user = data.user;

if (!user) {
return res
.status(500)
.json({ error: 'Login failed. Please try again later.' });
}

req.session.userId = req.session ? user.id : undefined;

return res.status(200).json({ message: 'Login successful.', user });
} catch (err) {
console.error('Login error:', err);
return res
.status(500)
.json({ error: 'Internal server error during login.' });
}
};
29 changes: 29 additions & 0 deletions backend/src/controllers/authentification/logout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import express from 'express';
import { supabase } from '../../config/supabaseClient';

export const logout = async (req: express.Request, res: express.Response) => {
try {
const { error } = await supabase.auth.signOut();

if (error) {
return res
.status(400)
.json({ error: 'Failed to log out. Please try again later.' });
}

req.session.destroy((err) => {
if (err) {
return res
.status(500)
.json({ error: 'Failed to end session. Please try again later.' });
}

return res.status(200).json({ message: 'Logout successful.' });
});
} catch (err) {
console.error('Logout error:', err);
return res
.status(500)
.json({ error: 'Internal server error during logout.' });
}
};
Loading

0 comments on commit e5532c5

Please sign in to comment.