Skip to content

Commit bc66b3d

Browse files
neighbor-peaceatu81601001101CKgeistnine
committed
move authUrl fetch to backend
Co-authored-by: atu816 <[email protected]> Co-authored-by: Yufa <[email protected]> Co-authored-by: Steven Geiger <[email protected]>
1 parent e6eb823 commit bc66b3d

File tree

3 files changed

+87
-75
lines changed

3 files changed

+87
-75
lines changed

server/controllers/auth.controller.ts

Lines changed: 80 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1,68 +1,93 @@
1-
import jwt, { JwtPayload } from 'jsonwebtoken'
2-
import { RequestHandler } from "express"
3-
import log from "../logger/index"
4-
import { getGoogleAuthToken } from "../utils/getGoogleAuthToken"
5-
import { createUser, findUser } from "./user.controller"
6-
declare module "express-session" {
7-
interface SessionData {
8-
user: string;
9-
}
1+
import jwt, { JwtPayload } from 'jsonwebtoken';
2+
import { RequestHandler } from 'express';
3+
import log from '../logger/index';
4+
import { getGoogleAuthToken } from '../utils/getGoogleAuthToken';
5+
import { createUser, findUser } from './user.controller';
6+
declare module 'express-session' {
7+
interface SessionData {
8+
user: string;
9+
}
1010
}
1111

12-
const client_url = process.env.NODE_ENV === 'development' ? process.env.DEV_CLIENT_ENDPOINT : process.env.CLIENT_ENDPOINT
12+
const client_url =
13+
process.env.NODE_ENV === 'development'
14+
? process.env.DEV_CLIENT_ENDPOINT
15+
: process.env.CLIENT_ENDPOINT;
1316

1417
export const handleGoogleAuth: RequestHandler = async (req, res) => {
15-
// get code from qs
16-
const code = req.query.code as string
18+
// get code from qs
19+
const code = req.query.code as string;
1720

18-
try {
19-
// get the id and access token w/ the code
20-
const { id_token, access_token } = await getGoogleAuthToken({ code })
21+
try {
22+
// get the id and access token w/ the code
23+
const { id_token, access_token } = await getGoogleAuthToken({ code });
2124

22-
//get user with tokens
23-
const decodedUser = jwt.decode(id_token) as JwtPayload;
25+
//get user with tokens
26+
const decodedUser = jwt.decode(id_token) as JwtPayload;
2427

25-
if (!decodedUser.email_verified) {
26-
req.session.destroy((err) => {
27-
// res.redirect('localhost:8080/')
28-
return res.status(403).send("Unable to authorize, google account is not verified.")
29-
})
30-
}
28+
if (!decodedUser.email_verified) {
29+
req.session.destroy((err) => {
30+
// res.redirect('localhost:8080/')
31+
return res
32+
.status(403)
33+
.send('Unable to authorize, google account is not verified.');
34+
});
35+
}
3136

32-
//insert or retrieve the user
33-
const foundUser: any = await findUser(decodedUser.email)
34-
// // if we did not find the user, create one
35-
if (!foundUser) {
36-
createUser([
37-
decodedUser.sub,
38-
decodedUser.name,
39-
decodedUser.email,
40-
decodedUser.picture
41-
])
42-
}
43-
const newUser = await findUser(decodedUser.email)
37+
//insert or retrieve the user
38+
const foundUser: any = await findUser(decodedUser.email);
39+
// // if we did not find the user, create one
40+
if (!foundUser) {
41+
createUser([
42+
decodedUser.sub,
43+
decodedUser.name,
44+
decodedUser.email,
45+
decodedUser.picture,
46+
]);
47+
}
48+
const newUser = await findUser(decodedUser.email);
4449

45-
const user = await foundUser || newUser
50+
const user = (await foundUser) || newUser;
4651

47-
// create an access token to be provided on every call user makes to backend
48-
// expires in 1 day
49-
const obj = { user: user[0], session: 'session' }
52+
// create an access token to be provided on every call user makes to backend
53+
// expires in 1 day
54+
const obj = { user: user[0], session: 'session' };
5055

51-
// create a session
52-
// refresh token expires in 1 day
53-
const accessToken = jwt.sign(obj, process.env.TOKEN_KEY as string, { algorithm: 'HS256', expiresIn: '1d' })
56+
// create a session
57+
// refresh token expires in 1 day
58+
const accessToken = jwt.sign(obj, process.env.TOKEN_KEY as string, {
59+
algorithm: 'HS256',
60+
expiresIn: '1d',
61+
});
5462

55-
req.session.user = accessToken;
56-
57-
log.info('Login successful, redirecting...')
58-
59-
const queryStr = 'true'
60-
61-
console.log(client_url)
62-
res.redirect(301, `${client_url}/?success=` + queryStr)
63+
req.session.user = accessToken;
6364

64-
} catch (error) {
65-
log.error(error, "User authorization failed")
66-
return res.redirect(301, `${client_url}/login`)
67-
}
68-
}
65+
log.info('Login successful, redirecting...');
66+
67+
const queryStr = 'true';
68+
69+
console.log(client_url);
70+
res.redirect(301, `${client_url}/?success=` + queryStr);
71+
} catch (error) {
72+
log.error(error, 'User authorization failed');
73+
return res.redirect(301, `${client_url}/login`);
74+
}
75+
};
76+
77+
export const getGoogleAuthUrl: RequestHandler = (req, res) => {
78+
const base = 'https://accounts.google.com/o/oauth2/v2/auth';
79+
80+
const options = {
81+
redirect_uri: process.env.GOOGLE_AUTH_CALLBACK as string,
82+
client_id: '373965291205-utb8ih1hoeuf1g90okil5ju43tfdl3vs.apps.googleusercontent.com',
83+
access_type: 'offline',
84+
response_type: 'code',
85+
prompt: 'consent',
86+
scope: [
87+
'https://www.googleapis.com/auth/userinfo.profile',
88+
'https://www.googleapis.com/auth/userinfo.email',
89+
].join(' '),
90+
};
91+
const queryStr = new URLSearchParams(options);
92+
return res.status(200).json(JSON.stringify(`${base}?${queryStr.toString()}`));
93+
};

server/routes/index.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { Express, Request, Response, NextFunction } from 'express';
2-
import { handleGoogleAuth } from '../controllers/auth.controller';
2+
import { handleGoogleAuth, getGoogleAuthUrl } from '../controllers/auth.controller';
33
import {
44
retrieveSchema,
55
saveSchema,
@@ -53,6 +53,8 @@ const routes = async (app: Express) => {
5353

5454
app.get('/api/oauth/google', handleGoogleAuth);
5555

56+
app.get('/api/googleAuthUrl', getGoogleAuthUrl);
57+
5658
app.use('/api/sql/postgres', postgresRouter);
5759

5860
app.use('/api/sql/mysql', mysqlRouter);

src/utils/getGoogleUrl.ts

Lines changed: 4 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,8 @@
1-
const getGoogleAuthUrl = () => {
2-
const base = 'https://accounts.google.com/o/oauth2/v2/auth';
1+
import axios from 'axios';
32

4-
const options = {
5-
redirect_uri: 'http://dbspy-env-1.eba-jf24jfwb.us-west-2.elasticbeanstalk.com/',
6-
client_id: '373965291205-utb8ih1hoeuf1g90okil5ju43tfdl3vs.apps.googleusercontent.com',
7-
access_type: 'offline',
8-
response_type: 'code',
9-
prompt: 'consent',
10-
scope: [
11-
'https://www.googleapis.com/auth/userinfo.profile',
12-
'https://www.googleapis.com/auth/userinfo.email',
13-
].join(' '),
14-
};
15-
const queryStr = new URLSearchParams(options);
16-
return `${base}?${queryStr.toString()}`;
17-
};
18-
19-
export const handleOAuthLogin = () => {
20-
const url = getGoogleAuthUrl();
3+
export const handleOAuthLogin = async () => {
4+
const res = await axios.get('/api/googleAuthUrl');
5+
const url = JSON.parse(res.data);
216
const strWindowFeatures =
227
'toolbar=no, menubar=no, width=600, height=700, top=100, left=100';
238
window.open(url, '_self', strWindowFeatures);

0 commit comments

Comments
 (0)