feat(client/api): validate ms users (#51372)

Co-authored-by: Muhammed Mustafa <MuhammedElruby@gmail.com>
This commit is contained in:
Tom
2023-08-26 07:57:02 -05:00
committed by GitHub
parent 0f9ba6e9a5
commit 9a1895d2e3
45 changed files with 927 additions and 332 deletions

View File

@@ -1,27 +0,0 @@
// TODO: port to new API!
const MS_LEARN_DOMAIN = 'learn.microsoft.com';
const mSLearnRegex = /^\/[^/]+\/training\/achievements\/([^/]+)$/;
export const getApiUrlFromTrophy = trophyUrlString => {
if (!trophyUrlString) return null;
let mSLearnUrl;
try {
mSLearnUrl = new URL(trophyUrlString);
} catch {
return null;
}
if (mSLearnUrl.protocol !== 'https:') return null;
if (mSLearnUrl.hostname !== MS_LEARN_DOMAIN) return null;
const match = mSLearnUrl.pathname.match(mSLearnRegex);
if (!match) return null;
const apiUrl = new URL(
`https://${MS_LEARN_DOMAIN}/api/gamestatus/achievements/${match[1]}`
);
apiUrl.searchParams.set('username', mSLearnUrl.searchParams.get('username'));
return apiUrl.href;
};

View File

@@ -1,50 +0,0 @@
const { getApiUrlFromTrophy } = require('./ms-learn-utils');
const validApiUrl =
'https://learn.microsoft.com/api/gamestatus/achievements/learn.wwl.get-started-c-sharp-part-1.trophy?username=moT01';
const validTrophyUrl =
'https://learn.microsoft.com/en-us/training/achievements/learn.wwl.get-started-c-sharp-part-1.trophy?username=moT01&sharingId=E2EF453C1F9208B';
describe('ms-learn-utils', () => {
describe('getApiUrlFromTrophy', () => {
it('should return null if the trophy url is empty', () => {
expect(getApiUrlFromTrophy('')).toBeNull();
});
it('should return null if the protocol is wrong', () => {
expect(getApiUrlFromTrophy('http://learn.microsoft.com')).toBeNull();
});
it('should return null if the domain is wrong', () => {
expect(getApiUrlFromTrophy('https://learn.microsoft.co')).toBeNull();
});
it('should return null if the path is incomplete', () => {
expect(getApiUrlFromTrophy('https://learn.microsoft.com')).toBeNull();
expect(
getApiUrlFromTrophy(
'https://learn.microsoft.com/en-us/trainin/achievements/learn.wwl.get-started-c-sharp-part-1.trophy?username=moT01'
)
).toBeNull();
});
it('should add the username as a query param', () => {
const username = 'moT01';
const url = new URL(getApiUrlFromTrophy(validTrophyUrl));
expect(url.searchParams.get('username')).toBe(username);
});
it('should only add a single query param', () => {
const url = new URL(getApiUrlFromTrophy(validTrophyUrl));
// URLSearchParams.size is only supported in Node 19+
expect([...url.searchParams.keys()].length).toBe(1);
});
it('should append the trophy path to the api url', () => {
expect(getApiUrlFromTrophy(validTrophyUrl)).toBe(validApiUrl);
});
});
});