Skip to content

Commit

Permalink
chore:
Browse files Browse the repository at this point in the history
  • Loading branch information
CynicDog committed Dec 26, 2024
1 parent ac21424 commit 0fc8e58
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 16 deletions.
2 changes: 2 additions & 0 deletions 7_auth/7_1_express_js/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,15 @@
"cors": "^2.8.5",
"express": "^4.21.2",
"ioredis": "^5.4.2",
"jsonwebtoken": "^9.0.2",
"ts-node": "^10.9.2",
"typescript": "^5.7.2"
},
"devDependencies": {
"@types/cookie-parser": "^1.4.8",
"@types/cors": "^2.8.17",
"@types/ioredis": "^5.0.0",
"@types/jsonwebtoken": "^9.0.7",
"nodemon": "^3.1.9"
}
}
15 changes: 8 additions & 7 deletions 7_auth/7_1_express_js/src/controllers/GitHubController.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { Request, Response } from "express";
import axios from "axios";
import jwt from 'jsonwebtoken';

import { useMiddleware } from "../decorators/LogDecorator";
import Redis from "ioredis";

Expand All @@ -14,6 +16,7 @@ const OAUTH_ACCESS_TOKEN_URL = "https://github.com/login/oauth/access_token";
const REDIS_HOST = process.env.REDIS_HOST!;
const FRONTEND_HOST = process.env.FRONTEND_HOST!;
const FRONTEND_PORT = process.env.FRONTEND_PORT!;
const JWT_SECRET = process.env.JWT_SECRET || 'your_jwt_secret';

// docker run -d -p 6379:6379 --name redis redis
// Create a new Redis client
Expand Down Expand Up @@ -67,24 +70,22 @@ export class GithubController {

const { access_token } = tokenResponse.data;


// Get user info from GitHub using the access token
const userResponse = await axios.get(`${GITHUB_API_URL}/user`, {
headers: { Authorization: `Bearer ${access_token}` },
});

const userInfo = userResponse.data;

await redis.set(`user:${userInfo.login}:access_token`, access_token);

res.cookie('is_authenticated', 'true', {
httpOnly: true,
secure: true,
sameSite: "none",
maxAge: 3_600_000 // 1 hour
});
const userPayload = { username: userInfo.login };
const token = jwt.sign(userPayload, JWT_SECRET, { expiresIn: '6h' });

// Run the below command as Administrator on Window:
// Add-Content C:\Windows\System32\drivers\etc\hosts "127.0.0.1 vite-react-client"
res.redirect(`http://${FRONTEND_HOST}:${FRONTEND_PORT}`);
res.redirect(`http://${FRONTEND_HOST}:${FRONTEND_PORT}?user_token=${token}`);
} catch (err: unknown) {
if (err instanceof Error) {
res.status(500).send({ error: "GitHub OAuth2 callback failed", details: err.message });
Expand Down
24 changes: 15 additions & 9 deletions 7_auth/client/Context.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,28 @@ const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [userInfo, setUserInfo] = useState(null);

useEffect(() => {
// Read the 'is_authenticated' cookie
const isAuthenticatedCookie = document.cookie
.split('; ')
.find(cookie => cookie.startsWith('is_authenticated='))
?.split('=')[1];

if (isAuthenticatedCookie === 'true' && !isAuthenticated) {
const params = new URLSearchParams(window.location.search);
const token = params.get("user_token");
if (token) {
// Save token in local storage or cookie
localStorage.setItem("user_token", token);

// Clear token from URL to keep it clean
window.history.replaceState({}, document.title, "/");
setIsAuthenticated(true);

// Decode token to extract user info if needed
const user = JSON.parse(atob(token.split('.')[1])); // Decodes JWT payload
setUserInfo(user);
}
}, []);


const value = {
isAuthenticated
isAuthenticated,
userInfo
};

return (
Expand Down

0 comments on commit 0fc8e58

Please sign in to comment.