Working Auth0 on site

This commit is contained in:
2021-09-28 21:29:15 -05:00
parent d4d904d165
commit 8855709a34
11 changed files with 138 additions and 9 deletions

View File

@@ -22,7 +22,6 @@ app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "*"); res.header("Access-Control-Allow-Methods", "*");
res.header("Access-Control-Allow-Headers", "*"); res.header("Access-Control-Allow-Headers", "*");
res.header("x-powered-by", "serverless-express");
next(); next();
}); });
@@ -78,9 +77,7 @@ app.get(`/*`, (req, res) => {
*/ */
app.use(function (err, req, res, next) { app.use(function (err, req, res, next) {
console.error(err); console.error(err);
res res.status(500).json({ error: `Internal Server Error - "${err.message}"` });
.status(500)
.json({ error: `Internal Serverless Error - "${err.message}"` });
}); });
module.exports = app; module.exports = app;

View File

@@ -4,8 +4,8 @@
const StrategyJWT = require("passport-jwt").Strategy; const StrategyJWT = require("passport-jwt").Strategy;
const ExtractJWT = require("passport-jwt").ExtractJwt; const ExtractJWT = require("passport-jwt").ExtractJwt;
const { users } = require("../models"); const { users } = require("../models");
const { comparePassword } = require("../utils");
module.exports = (passport) => { module.exports = (passport) => {
const options = {}; const options = {};

View File

@@ -55,7 +55,6 @@ const register = async (user = {}) => {
* Get user by email address * Get user by email address
* @param {string} email * @param {string} email
*/ */
const getByEmail = async (email) => { const getByEmail = async (email) => {
// Validate // Validate
if (!email) { if (!email) {
@@ -86,7 +85,6 @@ const getByEmail = async (email) => {
* Get user by id * Get user by id
* @param {string} id * @param {string} id
*/ */
const getById = async (id) => { const getById = async (id) => {
// Validate // Validate
if (!id) { if (!id) {

View File

@@ -4,7 +4,8 @@
"description": "[![Serverless Fullstack Application Express React DynamoDB AWS Lambda AWS HTTP API](https://s3.amazonaws.com/assets.github.serverless/components/readme-serverless-framework-fullstack-application.png\r )](https://www.serverless-fullstack-app.com)", "description": "[![Serverless Fullstack Application Express React DynamoDB AWS Lambda AWS HTTP API](https://s3.amazonaws.com/assets.github.serverless/components/readme-serverless-framework-fullstack-application.png\r )](https://www.serverless-fullstack-app.com)",
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
"test": "echo \"Error: no test specified\" && exit 1" "test": "echo \"Error: no test specified\" && exit 1",
"format": "prettier --write ."
}, },
"repository": { "repository": {
"type": "git", "type": "git",
@@ -14,5 +15,6 @@
"license": "ISC", "license": "ISC",
"devDependencies": { "devDependencies": {
"prettier": "2.4.1" "prettier": "2.4.1"
} },
"dependencies": {}
} }

View File

@@ -11,5 +11,8 @@
"devDependencies": { "devDependencies": {
"astro": "^0.20.7", "astro": "^0.20.7",
"@astrojs/renderer-react": "^0.2.1" "@astrojs/renderer-react": "^0.2.1"
},
"dependencies": {
"@auth0/auth0-react": "^1.8.0"
} }
} }

View File

@@ -0,0 +1,25 @@
import React from "react";
import { Auth0Provider } from "@auth0/auth0-react";
import LoginButton from "./LoginButton";
import LogoutButton from "./LogoutButton";
import Profile from "./Profile";
import ProfileFromApi from "./ProfileFromApi";
const AuthTest = () => {
return (
<Auth0Provider
domain="dev-b-bgocbi.us.auth0.com"
clientId="c5A08v815qx3ySjffHbaUc5b5MPWhRad"
redirectUri={window.location.origin}
audience="https://dev-b-bgocbi.us.auth0.com/api/v2/"
scope="read:current_user update:current_user_metadata"
>
<LoginButton />
<LogoutButton />
<Profile />
<ProfileFromApi />
</Auth0Provider>
);
};
export default AuthTest;

View File

@@ -0,0 +1,10 @@
import React from "react";
import { useAuth0 } from "@auth0/auth0-react";
const LoginButton = () => {
const { loginWithRedirect } = useAuth0();
return <button onClick={() => loginWithRedirect()}>Log In</button>;
};
export default LoginButton;

View File

@@ -0,0 +1,14 @@
import React from "react";
import { useAuth0 } from "@auth0/auth0-react";
const LogoutButton = () => {
const { logout } = useAuth0();
return (
<button onClick={() => logout({ returnTo: window.location.origin })}>
Log Out
</button>
);
};
export default LogoutButton;

View File

@@ -0,0 +1,22 @@
import React from "react";
import { useAuth0 } from "@auth0/auth0-react";
const Profile = () => {
const { user, isAuthenticated, isLoading } = useAuth0();
if (isLoading) {
return <div>Loading ...</div>;
}
return (
isAuthenticated && (
<div>
<img src={user.picture} alt={user.name} />
<h2>{user.name}</h2>
<p>{user.email}</p>
</div>
)
);
};
export default Profile;

View File

@@ -0,0 +1,54 @@
import React, { useEffect, useState } from "react";
import { useAuth0 } from "@auth0/auth0-react";
const ProfileFromApi = () => {
const { user, isAuthenticated, getAccessTokenSilently } = useAuth0();
const [userMetadata, setUserMetadata] = useState(null);
useEffect(() => {
const getUserMetadata = async () => {
const domain = "dev-b-bgocbi.us.auth0.com";
try {
const accessToken = await getAccessTokenSilently({
audience: `https://${domain}/api/v2/`,
scope: "read:current_user",
});
const userDetailsByIdUrl = `https://${domain}/api/v2/users/${user.sub}`;
const metadataResponse = await fetch(userDetailsByIdUrl, {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
const { user_metadata } = await metadataResponse.json();
setUserMetadata(user_metadata);
} catch (e) {
console.log(e.message);
}
};
getUserMetadata();
}, [getAccessTokenSilently, user?.sub]);
return (
isAuthenticated && (
<div>
<img src={user.picture} alt={user.name} />
<h2>{user.name}</h2>
<p>{user.email}</p>
<h3>User Metadata</h3>
{userMetadata ? (
<pre>{JSON.stringify(userMetadata, null, 2)}</pre>
) : (
"No user metadata defined"
)}
</div>
)
);
};
export default ProfileFromApi;

View File

@@ -4,6 +4,8 @@ import Tour from '../components/Tour.astro';
// You can import components from any supported Framework here! // You can import components from any supported Framework here!
import ReactCounter from '../components/ReactCounter.jsx'; import ReactCounter from '../components/ReactCounter.jsx';
import AuthTest from '../components/AuthTest.jsx';
// Component Script: // Component Script:
// You can write any JavaScript/TypeScript that you'd like here. // You can write any JavaScript/TypeScript that you'd like here.
// It will run during the build, but never in the browser. // It will run during the build, but never in the browser.
@@ -42,6 +44,8 @@ let title = 'My Astro Site';
</div> </div>
</header> </header>
<AuthTest client:only />
<Tour /> <Tour />
<!-- <!--