Skip to content

Commit

Permalink
Merge pull request #6 from Aut-Labs/socials-updates
Browse files Browse the repository at this point in the history
Socials updates
  • Loading branch information
AntGe authored Oct 29, 2024
2 parents 62a7fb2 + bf53c42 commit beb8e60
Show file tree
Hide file tree
Showing 11 changed files with 683 additions and 59 deletions.
222 changes: 219 additions & 3 deletions package-lock.json

Large diffs are not rendered by default.

6 changes: 5 additions & 1 deletion src/api/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,11 @@ export const swEnvVariables = {
// IPFS storage
ipfsApiKey: "VITE_IPFS_API_KEY",
ipfsApiSecret: "VITE_IPFS_API_SECRET",
ipfsGatewayUrl: "VITE_IPFS_GATEWAY_URL"
ipfsGatewayUrl: "VITE_IPFS_GATEWAY_URL",

discordClientId: "VITE_DISCORD_CLIENT_ID",
twitterClientId: "VITE_TWITTER_CLIENT_ID",
githubClientId: "VITE_GITHUB_CLIENT_ID"
};

export const environment: typeof swEnvVariables =
Expand Down
18 changes: 15 additions & 3 deletions src/components/AutEditProfileDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import { AutTextField } from "@theme/field-text-styles";
import { ipfsCIDToHttpUrl } from "@utils/ipfs";
import { base64toFile, toBase64 } from "@utils/to-base-64";
import AutOsFileUpload from "./Fields/AutOsFileUpload";
import { useOAuth } from "@components/OAuth";
import { useOAuth, useOAuthSocials } from "@components/OAuth";
import { SelectedAutID } from "@store/aut/aut.reducer";
import { useSelector } from "react-redux";
import { AutOSAutID } from "@api/models/aut.model";
Expand Down Expand Up @@ -143,7 +143,7 @@ export enum SocialLinkPrefixes {

function AutEditProfileDialog(props: EditDialogProps) {
const { getAuthGithub, getAuthX, getAuthDiscord, authenticating } =
useOAuth();
useOAuthSocials();
const theme = useTheme();
const desktop = useMediaQuery(theme.breakpoints.up("md"));
const dispatch = useAppDispatch();
Expand Down Expand Up @@ -207,6 +207,14 @@ function AutEditProfileDialog(props: EditDialogProps) {
};

const onEditProfile = async (data: any) => {
// const updatedSocials = data.socials.map((social) => {
// if (social.type === "discord") {
// return { link: "", type: "discord" };
// }
// return social;
// });
// // eslint-disable-next-line no-debugger
// debugger;
await dispatch(
updateProfile({
...autID,
Expand Down Expand Up @@ -432,13 +440,17 @@ function AutEditProfileDialog(props: EditDialogProps) {
);
const responseData =
await response.json();
const username = responseData.username;
const { username, id } = responseData;
onChange(username);
const fullLink = `${SocialLinkPrefixes.Discord}${username}`;
setValue(
`socials.${index}.link`,
fullLink
);
setValue(`socials.${index}.metadata`, {
userId: id,
username
});
},
() => {
// setLoading(false);
Expand Down
117 changes: 113 additions & 4 deletions src/components/OAuth/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

import { environment } from "@api/environment";
import axios from "axios";
import { useCallback, useState, useRef } from "react";
Expand Down Expand Up @@ -27,12 +26,89 @@ const cleanup = (intervalRef, popupRef, handleMessageListener) => {
window.removeEventListener("message", handleMessageListener);
};

const xCleanUp = (xIntervalRef) => {
if (xIntervalRef.current) {
clearInterval(xIntervalRef.current);
}
};

export const useOAuth = () => {
const [authenticating, setAuthenticating] = useState(false);
const [finsihedFlow, setFinishedFlow] = useState(false);
const popupRef = useRef<Window>();
const intervalRef = useRef<ReturnType<typeof setInterval>>();

const getAuth = useCallback(async (onSuccess, onFailure) => {
setAuthenticating(true);
if (popupRef.current && !popupRef.current.closed) {
popupRef.current.close();
}

const callbackUrl = encodeURI(`${window.location.origin}/callback`);
popupRef.current = openPopup(
`https://discord.com/oauth2/authorize?response_type=code&client_id=1080508975780474900&scope=guilds&state=15773059ghq9183habn&redirect_uri=${callbackUrl}&prompt=consent`
) as any;

async function handleMessageListener(message) {
try {
const type = message && message.data && message.data.type;
if (type === "OAUTH_RESPONSE") {
console.log("RECEIVE MESSAGE");
const error = message && message.data && message.data.error;
if (error) {
onFailure(error);
} else {
const response = await axios.post(
`${environment.apiUrl}/aut/config/oauth2AccessToken`,
{
code: message.data.payload.code,
callbackUrl
}
);
setAuthenticating(false);
clearInterval(intervalRef.current);
popupRef.current.close();
onSuccess(response.data);
cleanup(intervalRef, popupRef, handleMessageListener);
}
}
} catch (genericError) {
onFailure(genericError);
console.error(genericError);
}
}
window.addEventListener("message", handleMessageListener);

//Check for abrupt closing of popup
intervalRef.current = setInterval(() => {
const popupClosed =
!popupRef.current ||
!(popupRef.current as any).window ||
(popupRef.current as any).window.closed;
if (popupClosed) {
setAuthenticating(false);
clearInterval(intervalRef.current);
window.removeEventListener("message", handleMessageListener);
onFailure();
}
}, 550);

return () => {
setAuthenticating(false);
cleanup(intervalRef, popupRef, handleMessageListener);
};
}, []);

return { getAuth, authenticating };
};

export const useOAuthSocials = () => {
const [authenticating, setAuthenticating] = useState(false);
const [finsihedFlow, setFinishedFlow] = useState(false);
const popupRef = useRef<Window>();
const intervalRef = useRef<ReturnType<typeof setInterval>>();
const xIntervalRef = useRef<ReturnType<typeof setInterval>>();

const getAuthDiscord = useCallback(async (onSuccess, onFailure) => {
setAuthenticating(true);
if (popupRef.current && !popupRef.current.closed) {
Expand All @@ -41,7 +117,7 @@ export const useOAuth = () => {

const callbackUrl = encodeURI(`${window.location.origin}/callback`);
popupRef.current = openPopup(
`https://discord.com/oauth2/authorize?response_type=code&client_id=1080508975780474900&scope=identify%20guilds&state=15773059ghq9183habn&redirect_uri=${callbackUrl}&prompt=consent`
`https://discord.com/oauth2/authorize?client_id=${environment.discordClientId}&response_type=code&redirect_uri=${callbackUrl}&scope=identify+guilds`
) as any;

async function handleMessageListener(message) {
Expand Down Expand Up @@ -94,14 +170,15 @@ export const useOAuth = () => {
}, []);

const getAuthX = useCallback(async (onSuccess, onFailure) => {
localStorage.removeItem("OAUTH_RESPONSE");
setAuthenticating(true);
if (popupRef.current && !popupRef.current.closed) {
popupRef.current.close();
}

const callbackUrl = encodeURI(`${window.location.origin}/callback`);
popupRef.current = openPopup(
`https://twitter.com/i/oauth2/authorize?response_type=code&client_id=YWRmaEY4LU9aSkRXd2NoZlpiLVU6MTpjaQ&state=state&scope=tweet.read%20offline.access&redirect_uri=${callbackUrl}&code_challenge=challenge&code_challenge_method=plain`
`https://twitter.com/i/oauth2/authorize?response_type=code&client_id=${environment.twitterClientId}&state=state&scope=tweet.read%20offline.access&redirect_uri=${callbackUrl}&code_challenge=challenge&code_challenge_method=plain`
) as any;

async function handleMessageListener(message) {
Expand All @@ -112,13 +189,15 @@ export const useOAuth = () => {
if (error) {
onFailure(error);
} else {
xCleanUp(xIntervalRef);
const response = await axios.post(
`${environment.apiUrl}/aut/config/oauth2AccessTokenX`,
{
code: message.data.payload.code,
callbackUrl
}
);

setAuthenticating(false);
clearInterval(intervalRef.current);
popupRef.current.close();
Expand Down Expand Up @@ -147,9 +226,39 @@ export const useOAuth = () => {
}
}, 550);

xIntervalRef.current = setInterval(async () => {
const oauthResponse = JSON.parse(localStorage.getItem("OAUTH_RESPONSE"));
if (oauthResponse) {
cleanup(intervalRef, popupRef, handleMessageListener);
localStorage.removeItem("OAUTH_RESPONSE");
try {
if (oauthResponse.error) {
onFailure(oauthResponse.error);
} else {
const response = await axios.post(
`${environment.apiUrl}/aut/config/oauth2AccessTokenX`,
{
code: oauthResponse.payload.code,
callbackUrl
}
);

setAuthenticating(false);
popupRef.current.close();
onSuccess(response.data);
xCleanUp(xIntervalRef);
}
} catch (genericError) {
onFailure(genericError);
console.error(genericError);
}
}
}, 550);

return () => {
setAuthenticating(false);
cleanup(intervalRef, popupRef, handleMessageListener);
xCleanUp(xIntervalRef);
};
}, []);

Expand All @@ -161,7 +270,7 @@ export const useOAuth = () => {

const callbackUrl = encodeURI(`${window.location.origin}/callback`);
popupRef.current = openPopup(
`https://github.com/login/oauth/authorize?response_type=code&client_id=796be80cc5997ad5b9e6&state=state&scope=read:user&redirect_uri=${callbackUrl}`
`https://github.com/login/oauth/authorize?response_type=code&client_id=${environment.githubClientId}&state=state&scope=read:user&redirect_uri=${callbackUrl}`
) as any;

async function handleMessageListener(message) {
Expand Down
29 changes: 16 additions & 13 deletions src/pages/AutID/AutHub/AutHubContributionsTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -231,19 +231,22 @@ export const AutHubTasksTable = ({ header }) => {
take: 1000
}
});
useEffect(() => {
if (!contributions.length) {
const updatedContributions = data?.map((item) => ({
...item,
contributionType: "open",
status: TaskStatus.Created,
id: generateRandomId()
}));
dispatch(
updateContributionState({ contributions: updatedContributions })
);
}
}, [data]);
useEffect(() => {
if (!contributions.length) {
const updatedContributions = data?.map((item) => ({
...item,
contributionType: (item.properties as any)
.tweetUrl
? "retweet"
: "open",
status: TaskStatus.Created,
id: generateRandomId()
}));
dispatch(
updateContributionState({ contributions: updatedContributions })
);
}
}, [data]);

const theme = useTheme();
return (
Expand Down
14 changes: 9 additions & 5 deletions src/pages/Oauth2/Callback.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,27 +10,31 @@ const Callback = () => {
useEffect(() => {
const payload = queryToObject(window.location.search.split("?")[1]);
const error = payload && payload.error;

if (!window.opener) {
throw new Error("No window opener");
if (!window.opener && !error) {
localStorage.setItem("OAUTH_RESPONSE", JSON.stringify({ payload }));
window.close();
} else if (!window.opener && error) {
localStorage.setItem("OAUTH_RESPONSE", JSON.stringify({ error }));
window.close();
}
if (error) {
window.opener.postMessage({
type: "OAUTH_RESPONSE",
error: decodeURI(error) || "OAuth2 error: An error has occured."
});
} else {
console.log("POST MESSAGE");
// localStorage.setItem("OAUTH_RESPONSE", JSON.stringify({ payload }));
window.opener.postMessage({
type: "OAUTH_RESPONSE",
payload
});
}
// window.close();
}, []);

return (
<div>
<AutLoading />
<AutLoading width="130px" height="130px" />
</div>
);
};
Expand Down
4 changes: 4 additions & 0 deletions src/pages/Tasks/Contributions/Contributions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import DiscordTask from "../DiscordTask/DiscordTask";
import QuizTask from "../QuizTask/QuizTask";
import { useParams } from "react-router-dom";
import useQueryContributions from "@utils/hooks/GetContributions";
import TwitterTask from "../TwitterTask/TwitterTask";

const Contributions = () => {
let contribution = useSelector(SelectedContribution);
Expand All @@ -29,6 +30,9 @@ const Contributions = () => {
{contribution?.contributionType === "quiz" && (
<QuizTask contribution={contribution} />
)}
{contribution?.contributionType === "retweet" && (
<TwitterTask contribution={contribution} />
)}
</>
);
};
Expand Down
5 changes: 2 additions & 3 deletions src/pages/Tasks/DiscordTask/DiscordTask.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { StepperButton } from "@components/StepperButton";
import { useAccount } from "wagmi";
import { AutOsButton } from "@components/AutButton";
import { TaskStatus } from "@store/model";
import { useOAuth } from "@components/OAuth";
import { useOAuth, useOAuthSocials } from "@components/OAuth";
import { updateContributionById } from "@store/contributions/contributions.reducer";
import SubmitDialog from "@components/Dialog/SubmitDialog";

Expand All @@ -29,13 +29,12 @@ const JoinDiscordTask = ({ contribution }: any) => {
const { address: userAddress } = useAccount();
// const isAdmin = useSelector(IsAdmin);
const isAdmin = false;
const { getAuthDiscord, authenticating } = useOAuth();
const { getAuthDiscord, authenticating } = useOAuthSocials();
const [joinClicked, setJoinClicked] = useState(false);
const [openSubmitSuccess, setOpenSubmitSuccess] = useState(false);
const navigate = useNavigate();
const { autAddress, hubAddress } = useParams();


// const { task, isLoading: isLoadingTasks } = useGetAllTasksPerQuestQuery(
// {
// userAddress,
Expand Down
Loading

0 comments on commit beb8e60

Please sign in to comment.