Skip to content

Commit

Permalink
Migrate to Amplify v6
Browse files Browse the repository at this point in the history
  • Loading branch information
amits97 committed Oct 27, 2024
1 parent ef0607f commit ef03ff3
Show file tree
Hide file tree
Showing 22 changed files with 1,503 additions and 1,320 deletions.
2,018 changes: 1,021 additions & 997 deletions package-lock.json

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "naadan-chords",
"version": "0.84.2",
"version": "0.84.3",
"homepage": "https://www.naadanchords.com/",
"private": true,
"dependencies": {
Expand All @@ -13,7 +13,7 @@
"ajv-errors": "^2.0.1",
"ajv-formats": "^2.1.1",
"ajv-keywords": "^4.0.1",
"aws-amplify": "^6.6.4",
"aws-amplify": "^6.6.7",
"axios": "^1.7.5",
"chord-fingering": "github:amits97/chord-fingering",
"moment": "^2.29.4",
Expand Down
128 changes: 66 additions & 62 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import React, { Component } from "react";
import { withRouter } from "react-router-dom";
import { Auth, Hub } from "aws-amplify";
import {
fetchAuthSession,
fetchUserAttributes,
getCurrentUser,
signInWithRedirect,
signOut,
} from "aws-amplify/auth";
import { Hub } from "aws-amplify/utils";
import { Modal } from "react-bootstrap";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faSyncAlt } from "@fortawesome/free-solid-svg-icons";
Expand Down Expand Up @@ -40,8 +47,8 @@ class App extends Component {

getUserPrevileges = (session) => {
return new Promise((resolve) => {
if (session && session.getIdToken) {
let sessionPayload = session.getIdToken().decodePayload();
if (session && session.tokens && session.tokens.idToken) {
let sessionPayload = session.tokens.idToken.payload;
if (
sessionPayload["cognito:groups"] &&
sessionPayload["cognito:groups"].includes("admin")
Expand All @@ -65,61 +72,54 @@ class App extends Component {
});
};

getUserAttributes = (session) => {
return new Promise((resolve) => {
Auth.currentAuthenticatedUser({
bypassCache: true,
})
.then(async (user) => {
const currentUserInfo = await Auth.currentUserInfo();
this.setState(
{
userName: user.username,
name: user.attributes.name,
email: user.attributes.email,
identities: user.attributes.identities,
emailVerified: user.attributes.email_verified,
preferredUsername: user.attributes.preferred_username,
picture: user.attributes.picture,
userTheme: currentUserInfo.attributes["custom:theme"] ?? "auto",
},
() => {
this.setWebsiteTheme();
}
);
await this.getUserPrevileges(session);
resolve();
})
.catch((err) => {
console.log(err);
resolve();
});
});
getUserAttributes = async (session) => {
try {
const { username } = await getCurrentUser();
const userAttributes = await fetchUserAttributes();
this.setState(
{
userName: username,
name: userAttributes.name,
email: userAttributes.email,
identities: userAttributes.identities,
emailVerified: userAttributes.email_verified === "true",
preferredUsername: userAttributes.preferred_username,
picture: userAttributes.picture,
userTheme: userAttributes["custom:theme"] ?? "auto",
},
() => {
this.setWebsiteTheme();
}
);
await this.getUserPrevileges(session);
} catch (e) {
// Non logged in user. Do nothing
}
};

getUserDetails = async (session) => {
Auth.currentAuthenticatedUser({
bypassCache: true,
})
.then(async (user) => {
const currentUserInfo = await Auth.currentUserInfo();
this.setState(
{
userName: user.username,
preferredUsername: user.attributes.preferred_username,
picture: user.attributes.picture,
name: user.attributes.name,
email: user.attributes.email,
userTheme: currentUserInfo.attributes["custom:theme"] ?? "auto",
},
() => {
this.setWebsiteTheme();
}
);

await this.getUserPrevileges(session);
})
.catch((err) => console.log(err));
try {
const { username } = await getCurrentUser();
const userAttributes = await fetchUserAttributes();
this.setState(
{
userName: username,
preferredUsername: userAttributes.preferred_username,
picture: userAttributes.picture,
name: userAttributes.name,
email: userAttributes.email,
userTheme: userAttributes["custom:theme"] ?? "auto",
},
() => {
this.setWebsiteTheme();
}
);
await this.getUserPrevileges(session);
return true;
} catch (e) {
// Non logged in user
return false;
}
};

setWebsiteTheme = () => {
Expand All @@ -139,7 +139,7 @@ class App extends Component {

if (loginError.indexOf("Already found an entry for username") !== -1) {
// TODO: Known issue with Cognito merging accounts. Ugly! Clean up if possible.
Auth.federatedSignIn({ provider: "Facebook" });
signInWithRedirect({ provider: "Facebook" });
}

if (loginError.indexOf("attributes required: [email]") !== -1) {
Expand All @@ -151,9 +151,11 @@ class App extends Component {

try {
this.setWebsiteTheme();
let session = await Auth.currentSession();
let session = await fetchAuthSession();
if (session.tokens) {
this.userHasAuthenticated(true);
}
this.getUserDetails(session);
this.userHasAuthenticated(true);
} catch (e) {
this.setWebsiteTheme();
if (e !== "No current user") {
Expand Down Expand Up @@ -183,9 +185,11 @@ class App extends Component {
const listener = async (data) => {
switch (data.payload.event) {
case "signIn":
let session = await Auth.currentSession();
await this.getUserDetails(session);
this.userHasAuthenticated(true);
let session = await fetchAuthSession();
if (session.tokens) {
this.userHasAuthenticated(true);
}
this.getUserDetails(session);
break;
default:
break;
Expand All @@ -203,7 +207,7 @@ class App extends Component {
if (event) {
event.preventDefault();
}
await Auth.signOut();
await signOut();

this.userHasAuthenticated(false);
this.setState(
Expand Down
3 changes: 1 addition & 2 deletions src/Header.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import React from "react";
import { Link } from "react-router-dom";
import { LinkContainer } from "react-router-bootstrap";
import { API } from "aws-amplify";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { Navbar, Nav, Form, NavDropdown } from "react-bootstrap";
import {
Expand All @@ -14,7 +13,7 @@ import {
faPowerOff,
} from "@fortawesome/free-solid-svg-icons";
import { AsyncTypeahead } from "react-bootstrap-typeahead";
import { slugify } from "./libs/utils";
import { API, slugify } from "./libs/utils";
import * as urlLib from "./libs/url-lib";
import logo from "./logo.svg";

Expand Down
2 changes: 1 addition & 1 deletion src/components/GlobalStyles.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ export const GlobalStyles = createGlobalStyle`
color: ${({ theme }) => theme.textMuted} !important;
}
a.text-primary {
a.text-primary, button.text-primary {
color: ${({ theme }) => theme.linkPrimary} !important;
&:hover {
Expand Down
5 changes: 2 additions & 3 deletions src/containers/Content.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import ReactGA from "react-ga4";
import Moment from "react-moment";
import ReactMarkdown from "react-markdown";
import config from "../config";
import { API } from "aws-amplify";
import StarRatings from "react-star-ratings";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
Expand All @@ -24,7 +23,7 @@ import {
faUserCircle,
faCommentAlt,
} from "@fortawesome/free-solid-svg-icons";
import { slugify, capitalizeFirstLetter } from "../libs/utils";
import { slugify, capitalizeFirstLetter, API } from "../libs/utils";
import Sidebar from "./Sidebar";
import NotFound from "./NotFound";
import ContentParser from "./ContentParser";
Expand Down Expand Up @@ -72,7 +71,7 @@ export default class Content extends Component {
if (
!this.props.isLoading &&
!Array.isArray(this.props.posts) &&
this.props.posts.postId !== prevProps.posts.postId
this.props.posts?.postId !== prevProps.posts?.postId
) {
if (this.props.isAuthenticated) {
await this.getRating();
Expand Down
40 changes: 25 additions & 15 deletions src/containers/Login.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,12 @@ import {
Button,
} from "react-bootstrap";
import { Helmet } from "react-helmet";
import { Auth } from "aws-amplify";
import {
confirmSignIn,
fetchAuthSession,
signIn,
signInWithRedirect,
} from "aws-amplify/auth";
import { LinkContainer } from "react-router-bootstrap";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faFacebook } from "@fortawesome/free-brands-svg-icons";
Expand Down Expand Up @@ -71,9 +76,13 @@ export default class Login extends SearchComponent {
this.setState({ isLoading: true });

try {
await Auth.signIn(this.state.email, this.state.password);
let session = await Auth.currentSession();
await signIn({
username: this.state.email,
password: this.state.password,
});
let session = await fetchAuthSession();
await this.props.getUserPrevileges(session);
await this.props.getUserAttributes(session);
this.props.userHasAuthenticated(true);

if (this.props.isDialog) {
Expand All @@ -90,7 +99,7 @@ export default class Login extends SearchComponent {
};

handleSocialLogin = (provider) => {
Auth.federatedSignIn({ provider });
signInWithRedirect({ provider });
};

renderError = () => {
Expand Down Expand Up @@ -130,10 +139,10 @@ export default class Login extends SearchComponent {
this.setState({ isLoading: true });

if (OTPSent) {
await Auth.sendCustomChallengeAnswer(this.state.cognitoUser, code);
await confirmSignIn({ challengeResponse: code });
try {
// This will throw an error if the user is not yet authenticated:
let session = await Auth.currentSession();
let session = await fetchAuthSession();
await this.props.getUserPrevileges(session);
this.props.userHasAuthenticated(true);
if (this.props.isDialog) {
Expand All @@ -153,7 +162,12 @@ export default class Login extends SearchComponent {
} else {
try {
let cognitoUser;
cognitoUser = await Auth.signIn(this.state.email);
cognitoUser = await signIn({
username: this.state.email,
options: {
authFlowType: "CUSTOM_WITHOUT_SRP",
},
});
this.setState({ OTPSent: true, cognitoUser });
} catch (e) {
this.setState({
Expand Down Expand Up @@ -278,24 +292,20 @@ export default class Login extends SearchComponent {
type="button"
text="Login with OTP"
loadingText="Logging in…"
isLoading={this.state.isLoading}
isLoading={this.state.isOTPFlow && this.state.isLoading}
disabled={!this.validateOTPForm()}
onClick={this.handleLoginWithOTP}
/>
{isOTPFlow && (
<>
<div className="login-divider-container my-4">
<hr className="login-divider" />
<Styles.LoginDividerText className="text-muted">
OR
</Styles.LoginDividerText>
</div>
<Button
block
type="button"
variant="link"
className="text-primary"
onClick={() => this.setState({ isOTPFlow: false })}
>
Login with password
Cancel
</Button>
</>
)}
Expand Down
3 changes: 1 addition & 2 deletions src/containers/Posts.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import React, { Component } from "react";
import { API } from "aws-amplify";
import { Helmet } from "react-helmet";
import ReactGA from "react-ga4";
import * as urlLib from "../libs/url-lib";
import { slugify, capitalizeFirstLetter } from "../libs/utils";
import { slugify, capitalizeFirstLetter, API } from "../libs/utils";
import Content from "./Content";
import config from "../config";

Expand Down
5 changes: 3 additions & 2 deletions src/containers/Request.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ import {
Button,
} from "react-bootstrap";
import { Helmet } from "react-helmet";
import { API, Auth } from "aws-amplify";
import { fetchAuthSession } from "aws-amplify/auth";
import { API } from "../libs/utils";
import LoaderButton from "../components/LoaderButton";
import SearchComponent from "../components/SearchComponent";
import Sidebar from "./Sidebar";
Expand Down Expand Up @@ -75,7 +76,7 @@ export default class Request extends SearchComponent {

async componentDidMount() {
try {
let session = await Auth.currentSession();
let session = await fetchAuthSession();
this.props.userHasAuthenticated(true);
await this.props.getUserAttributes(session);
this.setState({
Expand Down
Loading

0 comments on commit ef03ff3

Please sign in to comment.