Skip to content

Commit

Permalink
Merge pull request #41 from agricreation/ui
Browse files Browse the repository at this point in the history
UI
  • Loading branch information
moovendhan-v authored Apr 23, 2024
2 parents 3582527 + 7944ab5 commit a65542d
Show file tree
Hide file tree
Showing 26 changed files with 844 additions and 193 deletions.
2 changes: 2 additions & 0 deletions backend/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const path = require('path'); //path
const session = require('express-session');
require('dotenv').config();


// json webtokens
const jwt = require('jsonwebtoken')

Expand All @@ -29,6 +30,7 @@ const app = express();
const port = 4000;
app.use(cors());
app.use(express.json());

// app.use(bodyParser.json());

//importing router files
Expand Down
85 changes: 84 additions & 1 deletion backend/controller/github-oauth.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
const axios = require('axios');
const GitHubUser = require('../models/user.model');
require('dotenv').config();
const jwt = require('jsonwebtoken');
const {jsonStatus, jsonStatusError, jsonStatusSuccess} = require('../operations/errorhandlingOperations');
const {getUserInformationsByName} = require('../controller/userProfile.controller');
const { response } = require('express');
Expand All @@ -12,6 +13,7 @@ const TOKEN_EXPIRE_TIMEOUT = process.env.TOKEN_EXPIRE_TIMEOUT;
async function exchangeGitHubCodeForToken(code) {
const client_id = process.env.GITHUB_CLIENT_ID;
const client_secret = process.env.GITHUB_CLIENT_SECRET;
console.log(client_secret);
const params = `?client_id=${client_id}&client_secret=${client_secret}&code=${code}`;
try {
const response = await axios.post(
Expand Down Expand Up @@ -74,5 +76,86 @@ const getUserInfoFromGit = async (req, res) => {
}
};

module.exports = { exchangeGitHubCodeForToken , getUserInformationsFromGitApi, getUserInfoFromGit};
const signup_or_login_with_git = async (req,res)=>{

// it will create a new account if account not already existis or creates a new account

const { code } = req.body;
try {
// #TODO Upadate a auth token where authanticated by user
const githubAccessToken = await exchangeGitHubCodeForToken(code);

const userInformations = await getUserInformationsFromGitApi(githubAccessToken);

//get user profile info with github oauth
const gitUserId = userInformations.id;
const existingUser = await GitHubUser.findOne({ id: gitUserId });

// #TODO test if not an existing user (Test the app behaviour) and update the code (high priyority)
if (!existingUser) {
const githubUser = new GitHubUser(userInformations);
await githubUser.save();
const response ={
"token": createTokens({userId: githubUser.id, userName: githubUser.name}),
"user": githubUser,
"components": []
}
return res.json(jsonStatusSuccess({ message: `New Account created ${githubUser.name}`, response: response }));
}

getUserInformationsByName(existingUser.name, async (error, userProfileWithComponents) => {
if (error) {
return res.status(500).send(`Internal Server Error ${error}`);
} else {
userProfileWithComponents['token'] = createTokens({userId: existingUser.id, userName: existingUser.name});
return res.json(jsonStatusSuccess({ message: `Welcome Back ${existingUser.name}`, response: await userProfileWithComponents }));

// res.json({ success: true, githubAccessToken: await req.session.githubAccessToken, token: githubAccessToken, response: await userProfileWithComponents});
}
});
// req.session.githubAccessToken = await githubAccessToken;

} catch (error) {
console.error('Error during GitHub OAuth:', error);
res.status(500).json({ success: false, error: error });
}
}

const createTokens = (tokenProperties)=>{
// Assume user is authenticated via GitHub and obtain user info
// const { userId, username } = req.body;

// Create JWT token
const token = jwt.sign({ tokenProperties }, JWT_SECRET, { expiresIn: '1h' });

// Set HTTPOnly cookie with JWT token
// res.cookie('jwt', token, { httpOnly: true, secure: true });

return token;
}

const validateToken = (req,res)=>{
// Retrieve JWT token from cookie
// const token = req.cookies.jwt;
const { token } = req.body;

if (!token) {
return res.status(401).json({ message: 'Unauthorized' });
}

try {
// Verify JWT token
const decoded = jwt.verify(token, JWT_SECRET);
console.log(decoded);

// Access protected resource
res.status(200).json({ message: 'Token validated', user: decoded });
} catch (err) {
// Token verification failed
res.status(401).json({ message: 'Unauthorized' });
}
}


module.exports = { exchangeGitHubCodeForToken , getUserInformationsFromGitApi, getUserInfoFromGit, createTokens, validateToken, signup_or_login_with_git};

90 changes: 50 additions & 40 deletions backend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 4 additions & 2 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,16 @@
"cors": "^2.8.5",
"discord.js": "^14.12.1",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"express": "^4.19.2",
"express-jwt": "^8.4.1",
"express-openid-connect": "^2.17.1",
"express-session": "^1.17.3",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.1.0",
"node-telegram-bot-api": "^0.63.0",
"passport": "^0.7.0",
"passport-github": "^1.1.0"
"passport-github": "^1.1.0",
"passport-github2": "^0.1.12"
},
"devDependencies": {
"nodemon": "^3.1.0"
Expand Down
38 changes: 4 additions & 34 deletions backend/routes/github-oauth.router.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
// authRouter.js
const express = require('express');
const axios = require('axios');
const { exchangeGitHubCodeForToken, getUserInfoFromGit, getUserInformationsFromGitApi } = require('../controller/github-oauth.controller');
const { exchangeGitHubCodeForToken, getUserInfoFromGit, getUserInformationsFromGitApi, createTokens, validateToken, signup_or_login_with_git } = require('../controller/github-oauth.controller');
const authRouter = express.Router();
require('dotenv').config();
const GitHubUser = require('../models/user.model');
const {getUserInformationsByName} = require('../controller/userProfile.controller');

authRouter.get('/', (req, res) => {
res.send('welcome to git')
Expand All @@ -14,39 +13,10 @@ authRouter.get('/', (req, res) => {
authRouter.post('/getUserInfoFromGit', getUserInfoFromGit);

// #TODO upgrade this with proper session
authRouter.post('/github-oauth', async (req, res) => {
const { code } = req.body;
try {
// #TODO Upadate a auth token where authanticated by user
// const githubAccessToken = await exchangeGitHubCodeForToken(code);
const githubAccessToken = "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";
console.log(`Git access token ${githubAccessToken}`);
authRouter.post('/github-oauth', signup_or_login_with_git);

const userInformations = await getUserInformationsFromGitApi(githubAccessToken);
authRouter.post('/github', createTokens )

//get user profile info with github oauth
const gitUserId = userInformations.id;
const existingUser = await GitHubUser.findOne({ id: gitUserId });

// #TODO test if not an existing user (Test the app behaviour) and update the code (high priyority)
if (!existingUser) {
const githubUser = new GitHubUser(userInformations);
await githubUser.save();
}

getUserInformationsByName(existingUser.name, async (error, userProfileWithComponents) => {
if (error) {
return res.status(500).send(`Internal Server Error ${error}`);
} else {
res.json({ success: true, githubAccessToken: await req.session.githubAccessToken, token: githubAccessToken, response: await userProfileWithComponents});
}
});
// req.session.githubAccessToken = await githubAccessToken;

} catch (error) {
console.error('Error during GitHub OAuth:', error);
res.status(500).json({ success: false, error: error });
}
});
authRouter.post('/github-validate', validateToken )

module.exports = { authRouter };
44 changes: 44 additions & 0 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,54 @@ services:
networks:
my_network:
ipv4_address: 172.28.0.3

adminer:
image: adminer
container_name: my_adminer
restart: always
ports:
- "8080:8080"

postgres:
image: postgres:latest
container_name: my_postgres_db
restart: always
environment:
POSTGRES_DB: my_database
POSTGRES_USER: my_user
POSTGRES_PASSWORD: my_password
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 10s
timeout: 5s
retries: 5

logto:
depends_on:
postgres:
condition: service_healthy
image: svhd/logto:${TAG-latest}
entrypoint: ["sh", "-c", "npm run cli db seed -- --swe && npm start"]
ports:
- "3001:3001" # Map container port 3001 to host port 3001
- "3002:3002" # Map container port 3002 to host port 3002
environment:
- TRUST_PROXY_HEADER=1
# Use localhost instead of the service name for local testing
- DB_URL=postgres://my_user:my_password@postgres:5432/logto
# Set other environment variables as needed
- ENDPOINT
- ADMIN_ENDPOINT


volumes:
mongodb_data:
redis_data:
postgres_data:

networks:
my_network:
Expand Down
Loading

0 comments on commit a65542d

Please sign in to comment.