Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
26593ec
feat: add user tokens for submitting new backend curricula
moT01 Aug 17, 2021
a6471be
fix: clean up
moT01 Aug 27, 2021
5a0589a
fix: adjust to new approach
moT01 Aug 31, 2021
22c6914
rename: deleet to deleteRequest
moT01 Aug 31, 2021
74636fb
Update client/i18n/locales/english/translations.json
moT01 Aug 31, 2021
90915f1
fix: comment out component so we can merge this
moT01 Sep 1, 2021
d7eda99
feat: add route for submitting challenges
moT01 Oct 4, 2021
79d79e1
fix: remove file I didn't use
moT01 Oct 4, 2021
ae4570c
feat: add user token as envVariable to codeally URL
moT01 Oct 4, 2021
0e216f6
Update api-server/src/server/boot/challenge.js
moT01 Oct 14, 2021
54f5b3f
fix: unify translations with English versions
moT01 Oct 14, 2021
cba1132
fix: prettier error
moT01 Oct 15, 2021
dc59032
Update api-server/src/server/boot/challenge.js
moT01 Oct 21, 2021
57f6a87
Update api-server/src/server/middlewares/request-authorization.js
moT01 Oct 21, 2021
e995eb3
Update api-server/src/server/utils/certTypes.json
moT01 Oct 21, 2021
209ca47
fix: dynamically get tutorial info from md files
moT01 Oct 22, 2021
3d0473c
fix: prettier?
moT01 Oct 22, 2021
2f94006
fix: lint error
moT01 Nov 9, 2021
ff51919
Update api-server/src/server/boot/challenge.js
moT01 Nov 11, 2021
a4ea077
Update api-server/src/server/boot/challenge.js
moT01 Nov 11, 2021
cce79bf
Update api-server/src/server/boot/user.js
moT01 Nov 11, 2021
0c9adfe
Update api-server/src/server/boot/user.js
moT01 Nov 11, 2021
0545d0a
fix: review concerns in clienent/src/redux/index.js
moT01 Nov 11, 2021
3cc1001
fix: use upcoming changes flag instead of commentts to hide components
moT01 Nov 11, 2021
b62fc85
fix: remove unused comments
moT01 Nov 11, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions api-server/src/common/models/user.json
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,11 @@
"type": "hasMany",
"model": "article",
"foreignKey": "externalId"
},
"webhookTokens": {
"type": "hasMany",
"model": "WebhookToken",
"foreignKey": "userId"
}
},
"acls": [
Expand Down
7 changes: 6 additions & 1 deletion api-server/src/server/boot/certificate.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ const {
infosecV7Id,
sciCompPyV7Id,
dataAnalysisPyV7Id,
machineLearningPyV7Id
machineLearningPyV7Id,
relationalDatabasesV8Id
} = certIds;

const log = debug('fcc:certification');
Expand Down Expand Up @@ -112,6 +113,10 @@ function createCertTypeIds(allChallenges) {
[certTypes.machineLearningPyV7]: getCertById(
machineLearningPyV7Id,
allChallenges
),
[certTypes.relationalDatabasesV8]: getCertById(
relationalDatabasesV8Id,
allChallenges
)
};
}
Expand Down
90 changes: 88 additions & 2 deletions api-server/src/server/boot/challenge.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { Observable } from 'rx';
import isNumeric from 'validator/lib/isNumeric';
import isURL from 'validator/lib/isURL';

import { environment, deploymentEnv } from '../../../../config/env.json';
import { fixCompletedChallengeItem } from '../../common/utils';
import { getChallenges } from '../utils/get-curriculum';
import { ifNoUserSend } from '../utils/middleware';
Expand Down Expand Up @@ -59,6 +60,10 @@ export default async function bootChallenge(app, done) {

router.get('/challenges/current-challenge', redirectToCurrentChallenge);

const coderoadChallengeCompleted = createCoderoadChallengeCompleted(app);

api.post('/coderoad-challenge-completed', coderoadChallengeCompleted);

app.use(api);
app.use(router);
done();
Expand All @@ -78,7 +83,7 @@ export function buildUserUpdate(
_completedChallenge,
timezone
) {
const { files } = _completedChallenge;
const { files, completedDate = Date.now() } = _completedChallenge;
let completedChallenge = {};
if (jsProjects.includes(challengeId)) {
completedChallenge = {
Expand Down Expand Up @@ -108,7 +113,7 @@ export function buildUserUpdate(
} else {
updateData.$push = {
...updateData.$push,
progressTimestamps: Date.now()
progressTimestamps: completedDate
};
finalChallenge = {
...completedChallenge
Expand Down Expand Up @@ -328,6 +333,87 @@ function backendChallengeCompleted(req, res, next) {
.subscribe(() => {}, next);
}

function createCoderoadChallengeCompleted(app) {
/* Example request coming from CodeRoad:
* req.body: { tutorialId: 'freeCodeCamp/learn-bash-by-building-a-boilerplate:v1.0.0' }
* req.headers: { coderoad-user-token: '8kFIlZiwMioY6hqqt...' }
*/

const { WebhookToken, User } = app.models;

return async function coderoadChallengeCompleted(req, res) {
const { 'coderoad-user-token': userWebhookToken } = req.headers;
const { tutorialId } = req.body;

if (!tutorialId) return res.send(`'tutorialId' not found in request body`);

if (!userWebhookToken)
return res.send(`'coderoad-user-token' not found in request headers`);

const tutorialRepoPath = tutorialId?.split(':')[0];
const tutorialSplit = tutorialRepoPath?.split('/');
const tutorialOrg = tutorialSplit?.[0];
const tutorialRepoName = tutorialSplit?.[1];

// this allows any GH account to host the repo in development or staging
// .org submissions should always be from repos hosted on the fCC GH org
if (deploymentEnv !== 'staging' && environment !== 'development') {
if (tutorialOrg !== 'freeCodeCamp')
return res.send('Tutorial not hosted on freeCodeCamp GitHub account');
}

const codeRoadChallenges = getChallenges().filter(
challenge => challenge.challengeType === 12
);

// validate tutorial name is in codeRoadChallenges object
const tutorialInfo = codeRoadChallenges.find(tutorial =>
tutorial.url?.includes(tutorialRepoName)
);

if (!tutorialInfo) return res.send('Tutorial name is not valid');

const tutorialMongoId = tutorialInfo?.id;

try {
// check if webhook token is in database
const tokenInfo = await WebhookToken.findOne({
where: { id: userWebhookToken }
});

if (!tokenInfo) return res.send('User webhook token not found');

const { userId } = tokenInfo;

// check if user exists for webhook token
const user = await User.findOne({
where: { id: userId }
});

if (!user) return res.send('User for webhook token not found');

// submit challenge
const completedDate = Date.now();

const userUpdateInfo = buildUserUpdate(user, tutorialMongoId, {
id: tutorialMongoId,
completedDate
});

const updatedUser = await user.updateAttributes(
userUpdateInfo?.updateData
);

if (!updatedUser)
return res.send('An error occurred trying to submit the challenge');
} catch (e) {
return res.send('An error occurred trying to submit the challenge');
}

return res.send('Successfully submitted challenge');
Comment thread
moT01 marked this conversation as resolved.
Resolved
};
}

// TODO: extend tests to cover www.freecodecamp.org/language and
// chinese.freecodecamp.org
export function createRedirectToCurrentChallenge(
Expand Down
70 changes: 66 additions & 4 deletions api-server/src/server/boot/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,28 +24,77 @@ function bootUser(app) {
const getSessionUser = createReadSessionUser(app);
const postReportUserProfile = createPostReportUserProfile(app);
const postDeleteAccount = createPostDeleteAccount(app);
const postWebhookToken = createPostWebhookToken(app);
const deleteWebhookToken = createDeleteWebhookToken(app);

api.get('/account', sendNonUserToHome, getAccount);
api.get('/account/unlink/:social', sendNonUserToHome, getUnlinkSocial);
api.get('/user/get-session-user', getSessionUser);

api.post('/account/delete', ifNoUser401, postDeleteAccount);
api.post('/account/reset-progress', ifNoUser401, postResetProgress);
api.post('/user/webhook-token', postWebhookToken);
api.post(
'/user/report-user/',
ifNoUser401,
body('reportDescription').customSanitizer(trimTags),
postReportUserProfile
);

api.delete('/user/webhook-token', deleteWebhookToken);

app.use(api);
}

function createPostWebhookToken(app) {
const { WebhookToken } = app.models;

return async function postWebhookToken(req, res) {
const ttl = 900 * 24 * 60 * 60 * 1000;
let newToken;

try {
await WebhookToken.destroyAll({ userId: req.user.id });
newToken = await WebhookToken.create({ ttl, userId: req.user.id });
} catch (e) {
return res.status(500).json({
type: 'danger',
message: 'flash.create-token-err'
});
}

return res.json(newToken?.id);
};
}

function createDeleteWebhookToken(app) {
const { WebhookToken } = app.models;

return async function deleteWebhookToken(req, res) {
try {
await WebhookToken.destroyAll({ userId: req.user.id });
} catch (e) {
return res.status(500).json({
type: 'danger',
message: 'flash.delete-token-err'
});
}

return res.json(null);
};
}

function createReadSessionUser(app) {
const { Donation } = app.models;

return function getSessionUser(req, res, next) {
return async function getSessionUser(req, res, next) {
const queryUser = req.user;

const webhookTokenArr = await queryUser.webhookTokens({
userId: queryUser.id
});
const webhookToken = webhookTokenArr[0]?.id;

const source =
queryUser &&
Observable.forkJoin(
Expand Down Expand Up @@ -83,7 +132,8 @@ function createReadSessionUser(app) {
isTwitter: !!user.twitter,
isWebsite: !!user.website,
...normaliseUserFields(user),
joinDate: user.id.getTimestamp()
joinDate: user.id.getTimestamp(),
webhookToken
}
},
sessionMeta,
Expand Down Expand Up @@ -192,8 +242,20 @@ function postResetProgress(req, res, next) {
}

function createPostDeleteAccount(app) {
const { User } = app.models;
return function postDeleteAccount(req, res, next) {
const { User, WebhookToken } = app.models;
return async function postDeleteAccount(req, res, next) {
const {
user: { id: userId }
} = req;

try {
await WebhookToken.destroyAll({ userId });
} catch (err) {
log(
`An error occurred deleting webhook tokens for user with id ${userId} when they tried to delete their account`
);
}

return User.destroyById(req.user.id, function (err) {
if (err) {
return next(err);
Expand Down
4 changes: 3 additions & 1 deletion api-server/src/server/middlewares/csurf.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ export default function getCsurf() {
const { path } = req;
if (
// eslint-disable-next-line max-len
/^\/hooks\/update-paypal$|^\/donate\/charge-stripe$/.test(path)
/^\/hooks\/update-paypal$|^\/donate\/charge-stripe$|^\/coderoad-challenge-completed$/.test(
path
)
) {
next();
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ const unsubscribeRE = /^\/u\/|^\/unsubscribe\/|^\/ue\//;
const updateHooksRE = /^\/hooks\/update-paypal$/;
// note: this would be replaced by webhooks later
const donateRE = /^\/donate\/charge-stripe$/;
const submitCoderoadChallengeRE = /^\/coderoad-challenge-completed$/;

const _pathsAllowedREs = [
authRE,
Expand All @@ -40,7 +41,8 @@ const _pathsAllowedREs = [
unsubscribedRE,
unsubscribeRE,
updateHooksRE,
donateRE
donateRE,
submitCoderoadChallengeRE
];

export function isAllowedPath(path, pathsAllowedREs = _pathsAllowedREs) {
Expand Down
4 changes: 4 additions & 0 deletions api-server/src/server/model-config.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,5 +58,9 @@
"User": {
"dataSource": "db",
"public": false
},
"WebhookToken": {
"dataSource": "db",
"public": false
}
}
20 changes: 20 additions & 0 deletions api-server/src/server/models/webhook-token.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "WebhookToken",
"description": "Tokens for submitting curricula through CodeRoad",
"base": "AccessToken",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {},
"validations": [],
"relations": {
"user": {
"type": "belongsTo",
"model": "user",
"foreignKey": "userId"
}
},
"acls": [],
"methods": {}
}
3 changes: 2 additions & 1 deletion api-server/src/server/utils/certTypes.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,6 @@
"sciCompPyV7": "isSciCompPyCertV7",
"dataAnalysisPyV7": "isDataAnalysisPyCertV7",
"machineLearningPyV7": "isMachineLearningPyCertV7",
"fullStack": "isFullStackCert"
"fullStack": "isFullStackCert",
"relationalDatabasesV8": "isRelationalDatabasesV8"
}
19 changes: 18 additions & 1 deletion client/i18n/locales/chinese-traditional/translations.json
Original file line number Diff line number Diff line change
Expand Up @@ -466,7 +466,11 @@
"unlink-success": "你已成功取消 {{website}} 鏈接",
"provide-username": "檢查你是否提供用戶名和報告",
"report-sent": "已通過 {{email}} 向團隊發送副本報告",
"certificate-missing": "你嘗試查看的認證不存在"
"certificate-missing": "你嘗試查看的認證不存在",
"create-token-err": "An error occurred trying to create a token",
"delete-token-err": "An error occurred trying to delete your token",
"token-created": "You have successfully created a new token.",
"token-deleted": "Your token has been deleted."
},
"validation": {
"max-characters": "字符數最多爲 288 個,你還可以輸入 {{charsLeft}} 個字符",
Expand Down Expand Up @@ -594,5 +598,18 @@
"add-code-one": "用你的複製代碼替換這兩句。",
"add-code-two": "請保留上方的 ``` 行和下方的 ``` 行",
"add-code-three": "因爲它們允許你的代碼在帖子中被正確格式化。"
},
"webhook-token": {
"title": "Webhook Token",
"create": "Create a new token",
"create-p1": "It looks like you don't have a webhook token. Create one to save your progress on this section",
"create-p2": "Create a webhook token to save your progress on the curriculum sections that use a virtual machine.",
"delete": "Delete my token",
"delete-title": "Delete My Webhook Token",
"delete-p1": "Your webhook token below is used to save your progress on the curriculum sections that use a virtual machine.",
"delete-p2": "If you suspect your token has been compromised, you can delete it to make it unusable. Progress on previously submitted lessons will not be lost.",
"delete-p3": "You will need to create a new token to save future progress on the curriculum sections that use a virtual machine.",
"no-thanks": "No thanks, I would like to keep my token",
"yes-please": "Yes please, I would like to delete my token"
}
}
Loading