Skip to content

Commit

Permalink
fix(Auth): Fix google auth created used issue
Browse files Browse the repository at this point in the history
Fix issue when user is gonna be created after successful google
authorization
  • Loading branch information
crazy-grizzly committed Feb 11, 2020
1 parent 4b128e2 commit 763d1bd
Show file tree
Hide file tree
Showing 10 changed files with 124 additions and 23 deletions.
26 changes: 19 additions & 7 deletions api/src/auth/passport.js
Original file line number Diff line number Diff line change
Expand Up @@ -212,13 +212,25 @@ if (
profile.emails,
email => email.verified === true
);
User.findOrCreate({ email: userEmail.value }, (err, user) => {
assert.ifError(err);
user.googleId = profile.id;
user.imageUrl = get(profile, 'photos.0.value');
user.name = profile.displayName;
user.save((err, savedUser) => done(err, savedUser));
});

User.findOne(
{
email: userEmail.value
},
(err, user) => {
assert.ifError(err);

if (!user) {
return done(null, false, { message: 'User does not exist' });
}

user.googleId = profile.id;
user.imageUrl = get(profile, 'photos.0.value');
user.name = profile.displayName;

user.save((err, savedUser) => done(err, savedUser));
},
);
}
)
);
Expand Down
11 changes: 8 additions & 3 deletions api/src/controllers/AuthController.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import passport from 'passport';
import jsonwebtoken from 'jsonwebtoken';
import { v4 as uuid } from 'uuid';
import ms from 'ms';
import status from 'http-status';
import logger from 'lib/logger';
import User from 'lib/models/user';
import OAuthToken from 'lib/models/oAuthToken';
Expand Down Expand Up @@ -262,11 +263,15 @@ const jwtOrganisation = (req, res) => {
};

const googleSuccess = (req, res) => {
// we have successfully signed into google
// create a JWT and set it in the query params (only way to return it with a redirect)
createUserJWT(req.user, 'google')
.then(token => res.redirect(`/api${AUTH_JWT_SUCCESS}?access_token=${token}`))
.catch(err => res.status(500).send(err));
.catch(
(err) => {
res
.status(status.INTERNAL_SERVER_ERROR)
.send(err);
}
);
};

const clientInfo = (req, res) => {
Expand Down
25 changes: 23 additions & 2 deletions api/src/routes/HttpRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,13 @@ router.get(
AuthController.clientInfo
);

router.get(
routes.OAUTH2_FAILED,
(request, response) => {
response.send('Authorization failed');
},
);

router.post(
routes.OAUTH2_TOKEN,
AuthController.issueOAuth2AccessToken
Expand All @@ -138,10 +145,24 @@ if (process.env.GOOGLE_ENABLED) {
routes.AUTH_JWT_GOOGLE,
passport.authenticate('google', GOOGLE_AUTH_OPTIONS)
);

router.get(
routes.AUTH_JWT_GOOGLE_CALLBACK,
passport.authenticate('google', DEFAULT_PASSPORT_OPTIONS),
AuthController.googleSuccess
(request, response, next) => {
passport.authenticate(
'google',
DEFAULT_PASSPORT_OPTIONS,
(error, user, info) => {
if (!user) {
response.redirect(`/api${routes.OAUTH2_FAILED}?error=${info.message}`);

return;
}

AuthController.googleSuccess(request, response);
},
)(request, response, next);
},
);
}

Expand Down
1 change: 1 addition & 0 deletions lib/constants/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export const AUTH_JWT_SUCCESS = '/auth/jwt/success';
export const AUTH_CLIENT_INFO = '/auth/client/info';

export const OAUTH2_TOKEN = '/oauth2/token';
export const OAUTH2_FAILED = '/oauth2/failed';

export const SENDSMS = '/sendsms';

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@
"highland": "^2.8.1",
"html-to-text": "^2.1.0",
"http-proxy": "^1.12.0",
"http-status": "^1.4.2",
"immutable": "^3.8.1",
"ioredis": "^3.2.2",
"js-cookie": "^2.1.3",
Expand Down
2 changes: 2 additions & 0 deletions ui/src/containers/App/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { routeNodeSelector } from 'redux-router5';
import { startsWithSegment } from 'router5.helpers';
import get from 'lodash/get';
import createAsyncComponent from 'ui/utils/createAsyncComponent';
import SaveBarErrors from 'ui/containers/SaveBarErrors';

const renderPage = (routeName) => {
const testRoute = startsWithSegment(routeName);
Expand Down Expand Up @@ -62,6 +63,7 @@ const component = ({ route }) => {
<Helmet {...config.app.head} />
{renderPage(name)}
<Toasts />
<SaveBarErrors />
</div>
);
};
Expand Down
7 changes: 5 additions & 2 deletions ui/src/pages/LoginPage/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,11 @@ const render = ({
if (email && password) loginStart({ username: email, password }).catch(() => { });
};

const onClickOAuthLogin = (e) => {
if (e) e.preventDefault();
const onClickOAuthLogin = (event) => {
if (event) {
event.preventDefault();
}

oAuthLoginStart('google').catch(() => { });
};

Expand Down
2 changes: 1 addition & 1 deletion ui/src/utils/createAsyncDuck.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export default function createAsyncDuck({
yield put(actions.complete(args));
}
} catch (err) {
yield put(actions.failure({ ...args, message: err.message }));
yield put(actions.failure({ ...args, message: err.message || '' }));
yield put(alert({
...args,
message: err.message,
Expand Down
67 changes: 59 additions & 8 deletions ui/src/utils/oauth.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,29 +78,80 @@ function getEndpoint(provider) {
}

export function openPopup(provider) {
console.log('openPopup', provider);
return window.open(getEndpoint(provider), provider, `${settings},${getPopupDimensions(provider)}`);
}

/**
* @typedef {object} OauthError
* @property {string} message
*/

/**
* @callback checkForToken~tokenResolve
* @param {string} token
*/

/**
* @callback checkForToken~tokenReject
* @param {OauthError} error
*/

/**
* @param {Window} popup
* @param {checkForToken~tokenResolve} resolve
* @param {checkForToken~tokenReject} reject
*/
function checkForToken(popup, resolve, reject) {
if (popup.closed) reject({ errors: 'Authentication was cancelled.' });
else {
console.log('checkForToken');
if (popup.closed) {
reject({ message: 'Authentication was cancelled' });
} else {
let parsed;

try {
parsed = url.parse(popup.location.href, true);
} catch (e) {
// cross origin errors will be thrown trying to
// access the popup when it is on the third party site
}

if (_.has(parsed, 'query.access_token')) {
const accessToken = _.get(parsed, 'query.access_token');
const error = _.get(parsed, 'query.error');

if (accessToken || error) {
popup.close();
resolve(_.get(parsed, 'query.access_token'));
} else setTimeout(checkForToken.bind(null, popup, resolve, reject), 0);

if (error) {
reject({ message: error });

return;
}

resolve(accessToken);
} else {
setTimeout(
checkForToken.bind(null, popup, resolve, reject),
0,
);
}
}
}

/**
* @param {Window} popup
* @returns {Promise<string>}
*/
export function listenForToken(popup) {
return new Promise((resolve, reject) => {
checkForToken(popup, resolve, reject);
});
console.log('listenForToken', popup);

return new Promise(
/**
* @param {checkForToken~tokenResolve} resolve
* @param {checkForToken~tokenReject} reject
*/
(resolve, reject) => {
checkForToken(popup, resolve, reject);
}
);
}
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6751,6 +6751,11 @@ http-status-codes@^1.3.0:
version "1.4.0"
resolved "https://registry.yarnpkg.com/http-status-codes/-/http-status-codes-1.4.0.tgz#6e4c15d16ff3a9e2df03b89f3a55e1aae05fb477"

http-status@^1.4.2:
version "1.4.2"
resolved "https://registry.yarnpkg.com/http-status/-/http-status-1.4.2.tgz#75406e829dca9bfdf92972c579b47cd6a58ab6c8"
integrity sha512-mBnIohUwRw9NyXMEMMv8/GANnzEYUj0Y8d3uL01zDWFkxUjYyZ6rgCaAI2zZ1Wb34Oqtbx/nFZolPRDc8Xlm5A==

httpntlm@1.6.1:
version "1.6.1"
resolved "https://registry.yarnpkg.com/httpntlm/-/httpntlm-1.6.1.tgz#ad01527143a2e8773cfae6a96f58656bb52a34b2"
Expand Down

0 comments on commit 763d1bd

Please sign in to comment.