Browse Source

get Auth0 Management API talking to backend and retrieve users from Query

Ramona Plogmann 4 years ago
parent
commit
0091a9c846

+ 1 - 0
.gitignore

@@ -1,3 +1,4 @@
 client/node_modules/
 server/node_modules/
 client/.eslintcache
+server/.env

+ 1 - 1
client/.env

@@ -1,7 +1,7 @@
 REACT_APP_SERVER_URL=http://localhost:5000
-TOP_HEIGHT=55
 REACT_APP_NAV_BOTTOM_HEIGHT=55
 REACT_APP_GRID_LIST_ROW_HEIGHT=140
 REACT_APP_LOGIN_REDIRECT=http://localhost:3000/plans
 REACT_APP_LOGOUT_REDIRECT=http://localhost:3000/
 REACT_APP_AUTH0_DOMAIN=emealay.eu.auth0.com
+REACT_APP_AUTH0_CLIENT_ID=OLWo3TleqtrIithLd6dU5GsyVL3lNoRI

+ 1 - 1
client/src/components/Images/ImageUpload.jsx

@@ -45,7 +45,7 @@ const useStyles = makeStyles((theme) => ({
     height: process.env.REACT_APP_GRID_LIST_ROW_HEIGHT + 4 + 'px',
   },
   snackbarOffset: {
-    bottom: '58px', // todo make adapt to bottomNavHeight
+    bottom: process.env.REACT_APP_NAV_BOTTOM_HEIGHT + 4 + 'px',
   },
   rejectSnackbar: {
     backgroundColor: theme.palette.error.light,

+ 1 - 1
client/src/components/Meals/EditMeal.jsx

@@ -37,7 +37,7 @@ const useStyles = makeStyles((theme) => ({
     margin: '1.5em 0 0',
   },
   snackbarOffset: {
-    bottom: '58px', // todo make adapt to bottomNavHeight
+    bottom: process.env.REACT_APP_NAV_BOTTOM_HEIGHT + 4 + 'px',
   },
   deleteSnackbar: {
     backgroundColor: theme.palette.error.light,

+ 2 - 2
client/src/components/Meals/MealDetailView.jsx

@@ -1,9 +1,9 @@
 import React, { useEffect, useState } from 'react';
-import { Divider, Typography, GridList, GridListTile, Card, CardContent, Dialog } from '@material-ui/core';
+import { Card, CardContent, Dialog, Typography } from '@material-ui/core';
 // import MuiAlert from '@material-ui/lab/Alert';
 import { makeStyles } from '@material-ui/styles';
 import axios from 'axios';
-import { func, bool, string, shape, arrayOf } from "prop-types";
+import { arrayOf, bool, func, shape, string } from "prop-types";
 import EditMeal from "./EditMeal";
 import Navbar from "../Navbar";
 import BackButton from "../Buttons/BackButton";

+ 1 - 1
client/src/components/Meals/Meals.jsx

@@ -28,7 +28,7 @@ const useStyles = makeStyles({
   }
 });
 
-// todo idea MUI Chips fpr filters
+// todo idea MUI Chips for filters
 
 const Meals = (props) => {
   const classes = useStyles();

+ 1 - 1
client/src/components/Plans/EditPlanItem.jsx

@@ -33,7 +33,7 @@ const useStyles = makeStyles((theme) => ({
     margin: '1.5em 0 0',
   },
   snackbarOffset: {
-    bottom: '58px', // todo make adapt to bottomNavHeight
+    bottom: process.env.REACT_APP_NAV_BOTTOM_HEIGHT + 4 + 'px',
   },
   deleteSnackbar: {
     backgroundColor: theme.palette.error.light,

+ 2 - 4
client/src/components/Settings/Profile.jsx

@@ -7,10 +7,9 @@ const domain = "emealay.eu.auth0.com";
 const Profile = () => {
   const { user, isAuthenticated, isLoading } = useAuth0();
 
-/*
   const [userMetadata, setUserMetadata] = useState(null);
 
-  useEffect(() => {
+/*  useEffect(() => {
     const getUserMetadata = async () => {
 
       try {
@@ -36,8 +35,7 @@ const Profile = () => {
     };
 
     getUserMetadata();
-  }, []);
-*/
+  }, []);*/
 
 if(isLoading) return <div>loading...</div>;
 

+ 58 - 3
client/src/components/Social/Social.jsx

@@ -1,5 +1,6 @@
-import React from 'react';
-import { Typography } from '@material-ui/core';
+import React, { useEffect, useState } from 'react';
+import { TextField, Typography } from '@material-ui/core';
+import axios from 'axios';
 import Navbar from "../Navbar";
 import SearchButton from "../Buttons/SearchButton";
 import { useAuth0, withAuthenticationRequired } from "@auth0/auth0-react";
@@ -12,9 +13,61 @@ const useStyles = makeStyles({
     margin: '6rem 2rem',
   }
 });
+
+const domain = process.env.REACT_APP_AUTH0_DOMAIN;
+const serverURL = process.env.REACT_APP_SERVER_URL;
+
 const Social = () => {
   const classes = useStyles();
-  const { user } = useAuth0();
+  const { user, getAccessTokenSilently } = useAuth0();
+
+  const [query, setQuery] = useState('');
+
+  const getUsers = () => {
+    axios.get(serverURL + '/users/all/')
+         .then(res => {
+           console.log('result', res);
+         })
+         .catch(err => {
+           console.log(err.message);
+         });
+  }
+
+  useEffect(() => {
+    getUsers();
+  }, [query]);
+  /*
+    useEffect(() => {
+      const getUsersFromQuery = async () => {
+
+        try {
+          const accessToken = await getAccessTokenSilently({
+            audience: `https://${domain}/api/v2/`,
+            scope: "read:users",
+          });
+
+          const options = {
+            method: 'GET',
+            url: `https://${domain}/api/v2/users`,
+            params: {q: `name:"*${query}*"`, search_engine: 'v3'},
+            headers: {authorization: `Bearer ${accessToken}`}
+          };
+
+          axios.request(options).then(function (response) {
+            console.log('response from API Call', response.data);
+          }).catch(function (error) {
+            console.error('error2', error);
+          });
+
+        } catch (e) {
+          console.log('error1', e.message);
+        }
+      };
+
+      getUsersFromQuery().then(() => {
+        console.log('request complete.');
+      });
+    }, [query]);*/
 
   return (
     <>
@@ -22,6 +75,8 @@ const Social = () => {
       <Typography variant="h1">
         Social
       </Typography>
+
+      <TextField value={query} name="query" onChange={e => setQuery(e.target.value)} label="Query" variant="outlined" autoFocus required />
     </>
   )
     ;

+ 8 - 2
client/src/index.jsx

@@ -7,14 +7,20 @@ import { BrowserRouter } from "react-router-dom";
 import { Auth0Provider } from "@auth0/auth0-react";
 
 const loginRedirect = process.env.REACT_APP_LOGIN_REDIRECT;
+const domain = process.env.REACT_APP_AUTH0_DOMAIN;
+const clientId = process.env.REACT_APP_AUTH0_CLIENT_ID;
 
 ReactDOM.render(
-  <Auth0Provider domain="emealay.eu.auth0.com" clientId="OLWo3TleqtrIithLd6dU5GsyVL3lNoRI" redirectUri={loginRedirect}>
+  <Auth0Provider domain={domain}
+                 clientId={clientId}
+                 redirectUri={loginRedirect}
+                 audience="https://emealay.eu.auth0.com/api/v2/"
+                 scope="read:current_user update:current_user_metadata update:users read:users">
     <BrowserRouter>
       <App />
     </BrowserRouter>
   </Auth0Provider>,
-document.getElementById('root')
+  document.getElementById('root')
 )
 ;
 

+ 1 - 0
server/controllers/settings.controller.js

@@ -11,6 +11,7 @@ export const getSingleSetting = async (req, res) => {
     res.status(404).json({ message: error.message });
   }
 }
+
 export const getSettingsOfUser = async (req, res) => {
   let id = req.params.id;
   try {

+ 50 - 0
server/controllers/users.controller.js

@@ -0,0 +1,50 @@
+import { ManagementClient } from 'auth0';
+import dotenv from 'dotenv';
+dotenv.config();
+
+const authConfig = {
+  domain: process.env.AUTH0_DOMAIN,
+  audience: process.env.AUTH0_AUDIENCE,
+  clientId: process.env.AUTH0_CLIENT_ID,
+  clientSecret: process.env.AUTH0_CLIENT_SECRET,
+};
+
+let managementAPI = new ManagementClient({
+  domain: authConfig.domain,
+  clientId: authConfig.clientId,
+  clientSecret: authConfig.clientSecret
+});
+
+export const getAllUsers = async (req, res) => {
+  managementAPI.getUsers()
+               .then(function (users) {
+                 console.log('found some users!', users);
+                 res.status(200).json(users);
+               })
+               .catch(function (err) {
+                 console.log('error when finding users', err);
+                 res.status(404).json({ message: error.message });
+               });
+}
+
+export const getUsersFromQuery = async (req, res) => {
+  let query = req.params.query;
+  console.log('in the right function', query, query.length);
+  console.log(query);
+  if(query.length>=3) query = '*' + query; // add wildcard to the front (needs at least 3 characters)
+  query += '*'; // add wildcard to back, for query options see https://auth0.com/docs/users/user-search/user-search-query-syntax
+  console.log(query);
+
+  const params = {
+    q: 'name:'+query,
+  };
+  managementAPI.getUsers(params)
+               .then(function (users) {
+                 console.log('found some users!', users);
+                 res.status(200).json(users);
+               })
+               .catch(function (err) {
+                 console.log('error when finding users', err);
+                 res.status(404).json({ message: err.message });
+               });
+}

+ 5 - 0
server/index.js

@@ -1,3 +1,6 @@
+import dotenv from 'dotenv';
+dotenv.config();
+
 import express  from 'express';
 import bodyParser  from 'body-parser';
 import mongoose  from 'mongoose';
@@ -6,6 +9,7 @@ import planRoutes from './routes/plans.routes.js';
 import imageRoutes from './routes/images.routes.js';
 import mealRoutes from './routes/meals.routes.js';
 import settingsRoutes from './routes/settings.routes.js';
+import usersRoutes from './routes/users.routes.js';
 
 const app = express();
 
@@ -17,6 +21,7 @@ app.use('/plans', planRoutes);
 app.use('/images', imageRoutes);
 app.use('/meals', mealRoutes);
 app.use('/settings', settingsRoutes);
+app.use('/users', usersRoutes);
 
 const ATLAS_URI = 'mongodb+srv://ramonap:emealadmin@emealaycluster.8oblc.mongodb.net/emealay?retryWrites=true&w=majority';
 const PORT = process.env.PORT || 5000;

+ 2 - 2
server/models/plan.model.js

@@ -1,6 +1,6 @@
 import mongoose from 'mongoose';
 import Meal from "./meal.model.js";
-import exports from 'mongoose-autopopulate';
+import autopopulate from 'mongoose-autopopulate';
 
 const planSchema = new mongoose.Schema({
   userId: String,
@@ -33,7 +33,7 @@ planSchema.virtual('connectedMeal', {
   autopopulate: true,
 });
 
-planSchema.plugin(exports);
+planSchema.plugin(autopopulate);
 const Plan = mongoose.model('Plan', planSchema);
 
 export default Plan;

File diff suppressed because it is too large
+ 792 - 0
server/package-lock.json


+ 2 - 0
server/package.json

@@ -12,8 +12,10 @@
   "author": "",
   "license": "ISC",
   "dependencies": {
+    "auth0": "^2.33.0",
     "body-parser": "^1.19.0",
     "cors": "^2.8.5",
+    "dotenv": "^8.2.0",
     "express": "^4.17.1",
     "mongoose": "^5.10.19",
     "mongoose-autopopulate": "^0.12.3",

+ 8 - 0
server/routes/users.routes.js

@@ -0,0 +1,8 @@
+import express from 'express';
+import { getAllUsers, getUsersFromQuery } from "../controllers/users.controller.js";
+
+const router = express.Router();
+
+router.get('/fromQuery/:query', getUsersFromQuery);
+router.get('/all', getAllUsers);
+export default router;

Some files were not shown because too many files changed in this diff