Login Multi Role dengan Node JS, Express, MySQL, dan React JS (LENGKAP)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
In this video you will learn how to create a multi-role login using node.js, express, MySQL and react js on the frontend not only that You will also learn how to set up access control based on the logged in user here's the demo first i will login as admin login then I will be directed to the dashboard and here we display the username then here there are products now i can see all data products because I'm logged in as admin then this is the data input by John while this is the data input by the admin and this is also the data entered by the user then here it is found in users here there are three users, namely John, M Fikri and Laura where acting as admin is M Fikri John and Laura act as users This users menu can only be accessed by admin and only admins can add users, edit users, and delete users then i will login as user I will log out then i will login as user we have John's data here login then here will appear the username John Doe then here there is no users menu because we are logged in as user then if i go to products then I can only see the product input by John himself I can't see the products that are input by the admin or those that are input by other users What is the manufacturing process like? Let's get started Here I have created an empty folder called authentication then I will create another subfolder here I named the backend then I will enter this folder in Terminal by cd backend then I will create a package.json file with the command npm init -y then in the backend folder there is a file that is package.json then I will install some dependencies that we need I will clear first npm install first I will install express then I will also install the mysql client, namely mysql2 then i will also install sequelize then i will also install argon argon2 for password hashing you can also use bcrypt but here I use argon argon this is a highly recommended password hashing who won the password hashing competition in 2015 then i will also install cors so that later our API can be accessed from outside the domain then i will also install dotenv so that later we can use environment variables enter if the installation is complete here there are dependencies namely argon2, cors, dotenv, then express, mysql2 and sequelize then apart from that I will also install express session because we will use the session later npm install express-session now in dependencies there is express-session then here I will add type then type the module so that later we can use ES6 syntax to import and export modules save then here there is an entry point, namely index.js I'll make the file here, make sure it's in the backend folder index.js the first one I will import express import express from express then i will also import cors import cors from cors then I will also import the session import session from express-session then const app = express() then app.listen then here the port I will take from the environment variable I'll save this first then here I will create a file again named .env like this then here I will create APP_PORT variable like this then the value I will give here is 5000 save then return to index.js then here I will take the port from .env process.env.APP_PORT like this then here there is a callback then here I will log in the console console.log Server up and running save then to run our project here I use nodemon if you haven't installed nodemon please install it here i have installed nodemon globally and to make sure I just type here nodemon -v like this here I am using nodemon version 2.0.15 it means i have installed nodemon globally then I will run our project with the command nodemon index like this index this is the name of the file that is index.js then enter then here there is a message server up and running that means our application is running well then here I will add some middleware app.use the first is cors then here on cors i will add credentials and I will set it to true this function so that later the frontend can send requests along with cookies by including their credentials then the second I will also add here origin this is the domain we allow to be able to access our API it can be an array like this if you have multiple domains who are allowed to be able to access our API but here I only allow one domain to access our API Therefore, I will use a string like this here and the domain we allow is our frontend yaitu http://localhost then here is the port port-word 3000 because we will use react on the frontend and the default port for react is port 3000 like this if you run react with a different port please adjust it yourself here then I will also use another middleware i.e. app.use then express.json so that later we can receive data in json format then I forgot to import dotenv here I will import import dotenv from dotenv then we call the function dotenv.config() like this then I will define the session directly I will define here app.use then session here are options then here is a secret then I will take the secret from .env i will go to .env and I will create another variable here i.e. SESSION_SECRET then the value is a random string the more complicated the better save then return to index.js then here process.env then SESSION_SECRET like this then the other option is resave I will set it to false then next saveUninitialized and I will set it to true then here there are cookies then the cookie here is secure and secure there are booleans that are true and false if we use http we can set it to false like this secure is false and if we use https we will set secure to true but here I will let the secure be detected automatically if i use http it will set automatically to false and if i use https it will automatically be true That's why I can use here 'auto' here save then next i will create some folders in the backend folder the first new folder is config then I will also create a controllers folder then i will also create a models . folder then i will also create a routes . folder then I will also create another folder that is middleware this will contain the custom middleware that we will create later then here in the config folder I create a new file I named it Database.js then i will import its sequelize import sequelize from sequelize kemudian const db = new sequelize then here is the database name the database name I will give 'auth_db' like this Then here's the user I will use the root user then here my password will not use a password then here there is the first option which is the host The host is localhost then here there is dialect then the dialect is mysql like this then I just export this export default db like this save then i will create this 'auth_db' database here I use xampp make sure Apache and MySQL are running well then go to browser and visit localhost/phpmyadmin like this then go to database Then I created the database here i.e. auth_db like this create now we have database auth_db back to vs code then i created some models . files new file first i will create models UserModel.js then I will import the sequelize here import sequelize from sequelize then I will also import the connection because we need a connection to the database import db from config/Database.js then const I will destructure its DataTypes DataTypes equals sequelize const Users kemudian db.define then here is the table name I will make the table name 'users' like this then in the second parameter there is the field then in the third parameter there is an option and i will give option which is freezeTableName and I will set it to true then I will export this export default Users like this then on the field I will make the first field 'uuid' like this I will use uuid then type DataTypes.STRING then the default value I will set the default value here the default value we will use uuid DataTypes.UUIDV4 like this it will be generated automatically by sequelize then I will add another option which is allowNull and I will set it to false like this meaning this field cannot be empty then i will also provide validation here i will add validate then here I will also add notEmpty and I will set it to true This means that this field cannot be null and cannot be an empty string then I will copy this separate by comma paste here the second field is 'name' then we don't need defaultValue then validate it I'll add it here len This len is the number of characters and the number of characters I will limit here is a minimum of three characters then a maximum of 100 characters like this then I copy it again and then paste it here then the next field is 'email' The DataTypes are also strings then on validate i will not use len here but i will use isEmail and I will set it to true like this then I will paste it here again the next field is 'password' then i don't need len here then the next field is 'role' and i also don't need len here save then I will also create another model file new file i.e. ProductModel.js I will copy the code from UserModel I will copy everything Ctrl + A then go to ProductModel.js paste here then here I will change it to Products like this then on export default I will also change to Products like this then here I will change the table name to product like this then we also need uuid then we also need a name that is the product name then here we don't need an email and password I will remove this but here we need price we have the product name and also the price and the DataTypes I will change to an integer like this then the next field I will copy this and here I will create a userId field like this because I want the product table to have a relationship with the users table we can use association and here the type is integer not string because we have an id that is automatically generated from the users table with an integer type that will be the Primary Key while in product it will be the foreign key then we need to import the UserModel into this ProductModel import Users from UserModel.js like this I will go here then I will the relation here This is a one-to-many relationship so one user can input many products like that then the first one is Users.hasMany then here Products then Products.belongsTo then here Users then we will foreign key here Foreign Key and the Foreign Key is userId like this which we set here save Next I will create some controller files the first i create a controller file that is Users.js then I will also create Products.js file file then here on the Products controller I will import the model yaitu Product from ../models then the file is ProductModel.js like this then i made some function I will export directly export const the first one is getProducts here brings two parameters, namely request and response then i make another function i.e. getProductById then here createProduct then here updateProduct and then here deleteProduct like this save temporarily I leave the function blank like this then i will copy everything go to Users controller then paste here and here I change to Users then the model is UserModel.js like this then here getUsers then here getProductById then createUser then updateUser and deleteUser like this save I will also leave it blank for a while then I will create some routes files here new file the first one is UserRoute.js then I will also create a ProductRoute.js file like this go to UserRoute.js then I will import here express from express kemudian const router = express.Router() then I will export directly export default router then I will import the controller here import I will call directly like this from then ../controllers then the file name is Users.js like this then here I will call the method the first one is getUsers Then getUserById then createUser then updateUser then deleteUser like this then i will create some routes here router.get I will use the method get then here is the endpoint I give here /users like this then here I will use getUsers like this and I will duplicate this then the second getUserById then here we need the id . parameter like this and then here getUserById like this and I will duplicate again here the method is post then the endpoint is /users then here createUser like this and i duplicate again then here for the update I will use the patch method then we need the id . parameter and here updateUser like this and I will duplicate again lastly to delete I will use the delete method then we also need the id . parameter then here deleteUser like this save then I will copy this Ctrl + A copy go to ProductRoute.js paste then here on the controller I will change it to import from the ../controllers then Products.js like this then here is getProducts then getProductById then createProduct then updateProduct then deleteProduct and i will change this one by one disini getProducts then here getProductById then here createProduct then here updateProduct then here deleteProduct like this and then I will change the endpoint to /products like this and I will copy this I will change this to products like this save then go to our entry point which is index.js then i will import here the first import is UserRoute from ./routes then UserRoute.js like this kemudian import ProductRoute from ./routes then ProductRoute.js like this then I will use it as middleware here app.use then here UserRoute like this then here app.use ProductRoute like this then I will also import the connection here so we can sync the model to generate the table automatically import db from ./config/Database.js like this then I just sync here I will do it here i will make here a function i will call directly like this then here it's async because it's asyncronous then here await db.sync() like this I will enlarge the terminal again before I save it then save so here we will execute the query to create the users table and also the product table where the users table and the product table are related to the id contained in users with the Foreign key i.e. userId then back to browser here on database auth_db then here there are two tables namely product and users then if i go to I will reset the zoom again here then here there is more and if I go to more then I go to Designer then here there is a table users and table products I will move it here here there is a users table and a product table where the user table and product table are related with the Foreign Key userId and the Primary Key is the id found in the users table come back here back to vs code then I'll turn off the sync again because we have finished creating a table in the database and I will also disable this like this save it back then in Terminal we don't execute the query anymore Next we will focus on file controllers go to Users controller then here I will also import argon because we need to hash the password import argon2 from argon2 like this then here in the getUsers function I will use asyncronus then I will also use a try-catch block kemudian const response = await User.findAll() then res.status I will enter the status here which is 200 then .json Then I will parse the response here then if there is an error I will give a response with a status of 500 then .json then i will give you a msg message then the message I will take from error.message like this then I copy this then paste here I will also add here asyncronous then i will change this to findOne() like this then here are the options the option is where then here uuid we take the uuid from req.params.id like this Then to createUser I will also add here asyncronous then here I will destructure the request.body const the first is name then email then password then confPassword then his role = req.body then i will make a little validation if if the password is not the same as confPassword then I will return res.status and I will give the status which is 400 then .json I will give a message here msg then the message is the password and confirm the password doesn't match like this then if the password and confirm the password match then I will hash the password const hashPassword = await I use argon2.hash and here I will parse the password then I will use a try-catch block then I will insert the data into the database await User.create then here the field is name the name we take from the name then email we took the email from email then password we take the password hashPassword then roll we take the role from a role like this then I give a response res.status I will give the status 201 which is created then .json and I will give you a msg message then the message is that the register was successful like this then if there is an error I will give a response again I will copy this then paste here and I will change the status to 400 like this save then we can do the test here I use the rest client extension this if you haven't installed this extension, please install it or you can also use Postman to do the test but I use this rest client extension I will close again back to our project then I will create a new file here for testing I named it request.rest like this then the first I will do a test against createUser I will use the post method here then the endpoint is http://localhost:5000 then /users like this then here I will add content-type content-type nya yaitu application/json then here is the data the data is in json format the first one is name Then I will set the name to M Fikri for example then email The email is admin@gmail.com then there is a password The password is I will set it to be like this then confPassword and I will set it like this then roll I will set the role to be admin like this then I will give a label here the label is create a user like this then click send request then here we get response 201 created and we get the message register successful Next we need to test get users and get by id I will make a new request here i will separate it with ### like this then I give the label get All Users then here the method is get then the endpoint I will copy this then paste it here send request so now we get the user i.e. id, uuid, name, email, and password and also the role here and the password has been hashed like this now i don't want to show the id and also the password I just want to display the fields i.e. uuid, name, and email, role and createdAt and updatedAt I will lose the id and password back to Users controller go to getUsers then i added here the option the option is attribute then here is the attribute we want to display that is the first uuid then name then email and then roll we only display this attribute then I will copy this then I will also paste it here, don't forget to add a comma here save back then go to request.rest then I will send another request here now we get the user and the fields that are displayed are only uuid, name, email, and role then I will make a request to get single data i will separate it with ### like this then I will label get single user paste here then here we need to include its uuid I will copy this then paste it here I will close this first then send request now we get the single data here then I will also insert one more data for example here john doe then the email is john@gmail.com the password is the same then I will enter the role here user send request then the registration is successful then if i click get all users so now we have two admin and user data then here for single data then return Users controller and now we just have to do the update and delete methods then in the update function I will copy the code from getUserById I will copy this then paste here and I don't need the attribute then I will change the variable to user like this then i will check if if there is no user then I will return res.status I will enter the status 404 which is not found then .json I will give you a msg message then the message user not found like this then if the user is found I will copy this the req.body is from createUser then i will paste it here If the user is found, I will destructure the req.body again then I will do the validation again if the user sends the password then we need to update the password and if the user doesn't send the password then we don't need to update the password I will create a variable here let I named hashPassword then i will validate if if the password sent by the user is equal to empty, empty string or password is equal to null then we will take the password hashPassword from the database i.e. user.password this password is the name of the field contained in the database while this user is the variable that we define here then else if the user sends the password then we also need to update the password and we need to hash the password again hashPassword = await don't forget to add here asyncronous async then argon2 then .hash then password then i will validate again if I will copy from here from createUser I will copy this copy then paste here If the password sent by the user with the confirmed password is not the same, then I will return it the message is that the password and confirm the password don't match then if all the validations have been successful I can update you in the database I will copy from here I will copy from this try-catch block copy then paste it here then here we will change it to update then we update it based on id I will add a comma here then where id = user.id like this this user is the variable we define here then this id is the field where there is a database then on the response I will give the status 200 then the message I will change to user updated like this save then I will copy this all code from function update copy then here in the delete function I will add asyncronous then paste it here here we do not need to include the data I will delete this we will check the id sent by the user if there is no user then we send the message the user is not found and if the user is found we will delete the user User.destroy like this to delete the user we don't need the data I will delete this we only need id and the message I will change to user deleted like this save then we will do the test go to request.rest and I will copy this the first one I will try to update the user i will separate it with ### like this and I put a label here update user paste here then I will change the method to a patch and we need id I will take this id which is the id with user John I will paste it here then I will change to John Updated then we don't update the password I will delete the password send request so now we have successfully updated the user and if i click get single data to data John then now John has changed to John Updated like this now to delete I will close again and I will copy this then separate with ### then I will label here delete user paste here then I will change the method to delete like this then send request then now we have successfully deleted the data and if you go to all users here and now we have one data here which is John Doe that means we delete user M Fikri not John Doe turns out this is id M Fikri and I will insert again I will come back to M Fikri then here admin and the role is admin send request register successful and go to all users and now we have two data john doe and M Fikri like this now have two data namely user and admin Next I will create another file in the controllers folder I named Auth.js here I will create several functions, namely login and logout Then here I will import the model import User from ../models/UserModel.js then i will also import argon2 import argon2 from argon2 then I will make the login function const I will export directly export const Login i will also use asyncronous function then here request, response then i will copy some code from controller Users I will copy from this delete function I will copy this back to Auth.js paste here then here I will look for the data by email then here req.body.email like this because we login by email then if no user is found based on this email then I will give a 404 response and the message is that the user was not found and if the user is found I will verify the password I will create a variable here const match then wait and we will verify the password using argon2.verify then here is the password in the database we will take it from user.password then here is the password sent by the user i.e. req.body.password like this if the password sent by the user with the password in the database does not match if exclamation mark like this then match if it doesn't match then I will return the res.status I will give the status which is 400 then .json and I will give the message msg wrong password like this If the password matches then I will set the session req.session then here the name of the session I will give the name of the session, namely userId like this then I will take the value from user.uuid like this then I will give a response res.status I gave only 200 then .json and the response I will create some variables here the first const is uuid we need the uuid response user.uuid then const name we also need the response name user.name then const email user.email then const role then user.role like this Then I will parse the response here ie uuid then name, email, then role we don't include the password in the response because it is sensitive information then here I will also create a function to logout export const LogOut then here req, res then i will delete the session req.session.destroy then here brings the error parameter if there is an error I will return res.status and I will give the status which is 400 then .json I will give a message can't log out like this if there is no error I will give res.status I will give the status which is 200 .json and I give a message you have logged out like this save then I will also create a function to get user login this will be useful later on the frontend export const I named the function Me like this then here async request, response then i will check if if there is no session userId req.session.userId then I will return res.status I will give the status which is 401 then .json and I will give you a message please login to your account like this then if there is a session I will take the user in the database I will copy this then paste here then here I will look for user data based on uuid because the session we set here is uuid req I will copy this and then paste it here if it is not found in the user with this uuid then I will return the message here then if there is a user then I will give a response res.status I will give the status which is 200 then .json and I will parse the user here of this user variable then I also don't want to display the password in this response I want to display the response like this, namely uuid, name, email, and role I can add attributes here attribute then here uuid then name then email then a role like this Don't forget to add a comma here save the reason here is why we don't add the attribute then parse the user here because we need a password here That's why we can't add attributes here then i will create a file inside this routes folder new file I named AuthRoute.js I will copy some code from ProductRoute.js I will copy everything then paste here then i will delete this then i will need some route then here I will import the controller from ../controllers then Auth.js then here the function is Login then Logout then Me like this then here on the get method I will change to Me then in the post method I will change it to Login and in the delete method I change it to LogOut like this and I will change the endpoint to me then here I will change to login then here I change it to logout I will remove the id parameter like this save then go to our entry point which is index.js and I will import the routes here import AuthRoute from ./routes then AuthRoute.js then I will use it as middleware here I will duplicate this then i will change this to AuthRoute like this save now go to request.rest then I will try to login I will copy this separate with ### like this then I will give the user login label then here the endpoint is /login then to login we only need an email and password then send request so now we have successfully logged in we get a response here uuid, name, email, and role means that we are logged in with the admin role while if we login using another user for example John here send request then now I login with role user then I will try to access another endpoint, namely Me I will copy this separate with ### like this then the endpoint is /me like this and I will change the method to get send request then now we also get the same data I will close again send request then now we get the same data like this if i login with admin i will login with admin like this I will close again then if I get a request to get user login then now I login with the name M Fikri like this then I will check the endpoint again to logout separate with ### like this then the method is delete paste here then logout send request then now we get a message you have successfully logged out then I will show you something for example here I will login I successfully logged in I got the user data then if I restart the server for example I will deactivate again then i will run it again now the server is running then I access this endpoint me it means I want to get the data of the user who is currently logged in send request then now I have logged out automatically every time the server restarts then we will be asked to log back in this is not good practice because every server will restart every day Therefore, we need to save the session into the database so that when the server restarts we are still logged in until we logout I will close this again then I will stop the server again then I will install the dependencies we need to save the session into the database npm install then the name of the dependency is connect-session-sequelize like this these are the dependencies we need enter then if I go to the package.json file we can add one dependency which is connect-session-sequelize then go to our entry point which is index.js and I will import here import I named SequelizeStore from connect-session-sequelize like this then I will activate this again import connection to database then here I will create a variable again const sessionStore = SequelizeStore(session.Store) like this then const store = new sessionStore then here is the database db we take the database from this connection db like this then in the session we just make here the option is store then we take the store from a store like this then we need to create a session table in the database it's quite easy, we just stay in sync here i will go here store.sync() like this save then I will run the server again nodemon index so now we create a table, namely the Sessions table with the fields sid, expires, the data then createdAt and updatedAt go to browser I will click this auth_db database so now we have three tables namely product, users and sessions like this sid, expires, data, createdAt, and updatedAt like this back to vs code and now I disable this store.sync() again I will disable it like this because we have finished creating the session table in the database save so now we don't execute the create table command anymore now back to request.rest now i will try to login again now i have successfully logged in if i stop the server then i run it again it means the server is restarting then I will try to access this /me that is to get the user who is currently logged in send request then I get the user it means I'm still logged in then if i log out I managed to logout then send the request again here then now i have logged out like that Next I will create a file here in the middleware folder new file I named AuthUser.js like this here is the middleware that we will use to protect the endpoint First I will import the user model import User from ../models then UserModel.js then I will make the function middleware here I will export directly const I named verifyUser then i will use asyncronous function here then here brings three parameters req, res, and next because this is middleware then I will copy some code from our Auth.js controller I will copy from here I will copy everything from this Me function go to AuthUser then paste it here if there is no session userId then we will give a message here and we will return the status 401 then if there is a session we will find the user data based on the session here we don't need attributes then if the user is not found we will send a message user not found and if the user is found then I will create a variable here req.userId because we need the userId and the userId we will take from user.id then req.role because we also need the role so that later we can use this variable in each of our controllers then we take the role from user.role like this this user is the variable we set here then I will call function next like this save then we just call this verifyUser function at every endpoint that requires a user login I will go to UserRoute here I want when we access users, user by id, post user and update user and delete user we require the user to login Therefore we will import here import verifyUser from middleware and AuthUser.js like this then we just parse verifyUser as middleware here add comma here then paste it here be alright then paste comma again paste here then here and also here save it means we can't access the user if we're not logged in then go to request.rest I will check whether we are logged in or not I will go to get user login here send request this means we are not logged in we are not logged in I will close again now I will try to access this post user create user send request a message will appear, please login to your account then i will check get user then the same message will appear here then if i login I will login here as admin send request it means I'm logged in then I will access this get all users send request then now I managed to retrieve all users' data then I will click logout and I will try again get all users then please login to your account that means we have successfully protected these endpoint users baik post user, get single-user, maupun get all users dan update user, serta delete user then I want to get these users and post these users and update and delete users can only be done by admin and if we login as user we can't access this endpoint we can do like this back to AuthUser.js in the middleware then i will add one more method here i will copy this paste here here I give the name adminOnly like this we no longer need to check if there is a session because we have definitely logged in and then here I will add another validation here if user.role is not the same as admin like this then I returned I will copy this paste here then I return the status which is 403 which is Forbidden and I will give a message here forbidden access like this then we don't need req.userId and this role I will delete this and we will call the next function here save then return to UserRoute.js and I will import here adminOnly like this and I will copy this then I will add another middleware here adminOnly then here and also here then here save back to request.rest now i will try to login I will make two logins here I will copy this then here separate it with ### paste here here we login as admin while here we login as user I will login as John here save if i click send request and now I'm logged in as user then i try to access this get users send request then I get a forbidden access message like this because this can only be accessed by admin then i will log out again I will log out and I will login as admin I managed to login and as admin then i try to access this then now i get the data it means i can access this endpoint then we just focus on controller Products This product can be accessed by admin and user but admin can see all products but the user can only see the products he inputs himself actually there is an easy way that is by separating the admin controller and the user controller and then we just call it like this if he can only be accessed by admin, we can only admin only like this but in this tutorial I want to show how admin and user can access one controller then here I will add asyncronous i will start with getProducts and then here i will use try-catch block then here we can do validation because I want the query to be executed if the user is logged in as admin and the query executed with the user logged in as that user is different I will provide validation here if req.role = admin req. this role it comes from middleware after we login we have this variable which we set in middleware I will check again here here we have req.userId and this req.role comes from middleware if the user is logged in as admin then I will execute I will create a variable here let then I give the name response like this kemudian response = await Product.findAll() then I will give an option here which is include that is, we include the user here we also need to import the user here import User from the model from ../models then UserModel.js like this then we can use here the model then the model is User it means that we include the user in this product table because there is a relationship between the product and the user then if the user is logged in other than admin then I will execute another query I will add here the else condition I will copy this then paste it here then i will add the option which is where Don't forget to add a comma here then where is userId we have a userId field in the product table this is the foreign key so we are looking for data product data based on userId and the userId we will take from req.userId like this this is from the same middleware as this role req.role this means that if the user is logged in as admin then we can see all product data and if the user is logged in other than the admin, that is, the user can only see the data entered by the user himself like that then I will give a response res.status and I give the status which is 200 .json Then I will parse the response here response like this if there is an error I will give a response res.status and I will give the status which is 500 then .json and I'll give you a message and the message I will take from error.message like this save then go to ProductRoute.js here then I will import verifyUser here import verifyUser because I want this product to only be accessed by logged in users copy then paste it here then here and here then here and here save then go to request.rest then I will make a request to get product data I will copy this then i will separate it with ### like this then I will label here Get All Products like this paste here then here I will change to products like this send request then I get here empty array that means I'm still logged in I will logout first now i have logged out then I access again then now i get a message please login to your account now I will show you something for example here I will login as admin send request and now I'm logged in as admin here if i send a request here then I get an empty array because we don't have data yet then here there is a select which is joined with the users table and here there is no where it means that all the data contained in the product table will be displayed if i log out I successfully logged out and I logged in as a user here John and now I'm logged in as user and if I go to /products again here then here there is an addition here where product.userId = 2 here there is an additional where here means this user can only access the product based on userId 2 like this and coincidentally now we don't have the data then we will do the createProduct go to Products.js then here in the createProduct function i will add here asyncronous then I will also use a try-catch block then I will destructure the req.body const name, price because we have two fields namely name and price req.body like this then wait here Product.create then here is the data the first is name the name we take from the name then price the price we take from price then the userId userId We take the userId from this req.userId from the middleware then if it has been saved successfully I will give a response res.status I will give the status 201 which is created then .json and I'll give you a message the message is product created successfully like this then if there is an error I will copy this then paste here save then go back to request.rest I will make a new request here to post data I will copy this then separate it with ### like this and I will label here POST Data Product like this then here /products like this then the data is name then price the product name, for example, here I give here Product 1, for example then the price i will use 997 like this now i will check if i am logged in i will go here get me now I'm logged in as a user then here send request maka sekarang Product created successfully and now I will enter Product 2 post again then Product 3 post again now if i access get product here So now I have 3 products here 1, 2, 3 here then i will log out again and I will login as admin now I'm logged in as admin then I will post the data now I use Product 4 send request then Product 5 send request then Product 6 send request if I go to /products here so now i have 6 products here with the 6th id like this This is input by admin while this is input by the user like this and if i log out and I'm logged in as a user here John I am logged in as a user now and if i get the products here then I can only access up to the 3rd product here I can't access what the admin input while if I login as admin I can see all products now there is a user here where the user has an id, uuid, name, email and password then there is also a role here I just want to display the user, only the name and email without the password and other attributes and on the product here I also just want to display the uuid, the name, and also the price and i don't want to show this user id I will close this again then go back to Products.js then in the getProducts function I need to add here the attributes add a comma here then attribute the field I want to display is uuid then name this is the product name then the price is like this then on the user I also need to add here the attribute I will add a comma here attribute the attributes are name and email like this I will copy this then paste it here then copy this again comma then paste here save back to request.rest now if i get product now I'm logged in as a user then there is here uuid this is the uuid for the product then the product name then the price then the user only has name and email there is no password anymore and we can only access the data input by John like this if i log out and I'm logged in as admin send request and now i go to get product and I can access the data entered by John and also inputted by admin like this I can access all data products then go back to Products.js then I will copy this copy then paste here di getProductById I will add here asyncronous then I will check the id sent by the user const product i will create product variable here = await Product this is from the model .findOne() like this then i added an option here where uuid then we take the uuid from the parameter req.params.id like this if there is no data with the user-sent id then I will give a response if if there is no product with that id then I will return it res.status I will give the status which is 404 which is not found .json then i will give you a message the message is data not found like this if the data is found we will check again whether he is logged in as admin or user if he is logged in as admin I will change this to findOne because it is single data then the query that I executed i add here where i will copy this paste here comma here then I will select based on id not uuid anymore because we have got the id from this product then we take the id from product.id this product is the variable we set here then here I will also change to one here if logged in as a user then I will add another operator I will select the data based on the id and also the logged in user I will add here the operator I will import here import {Op} from sequelize like this then back to getProductById and I will add operator here Op.and I will use the 'and' operator then here the field is id then we take the id from product.id then the second one is we take the userId from req.userId I will cut this then paste it here like this then we parse the response here save back to request.rest then I will make a new request here copy then paste it here I will label it as get single product I will get all products first now I'm logged in as admin and I will select data with this id copy then / paste here the id then send request then now i get single data here i.e. data inputted by John Doe because I am logged in as admin if i login as user I will send another request here I will take one of the ids entered by the admin I will copy this then i will replace this paste send request then now I get the data inputted by the admin now if i log out and login as user send request then here we have successfully logged in then I will send a request here then I get a response here null means that we cannot access the data inputted by the admin while if I select the data here which is inputted by John Doe paste here send request then now I get the data input by John Doe so the user can only access the data he inputs himself while the admin can access all the data then we just need to create a function to update and delete the product go to Products controller and I will copy everything this getProductById function I will copy then paste in updateProduct and I will add here asyncronous like this then we will check the product data based on the id sent by the user and if there is no data then we will send a message data not found and if the data is found I will take the req.body I will copy this from createProduct copy then paste it here we don't need the response variable anymore I will delete this then i will also delete this if we login as admin then i will execute query like this await Product.update() then here is the data we want to update the first is the name then the price is like this then we update based on id I will add the option here where id We take the id from product.id like this this product is the variable we set here while this product is the model then if the user is logged in as user then I will execute another query I will copy this I will paste it here i will add the 'and' operator I will copy from here I will copy this where is this copy then I will paste it here like this then i will check again here if req.userId !== product.userId if not the same then I will return the response res.status and status I will give here 403 which is Forbidden .json here I will give a message the message is that access is forbidden like this if the same then we will execute this update then it also works I will give the response here I will give a message here product updated successfully like this and if there is an error I will execute this save then go to request.rest then I will make a new request here I will copy this then paste here then I will change the method to a patch then i will take this id like this and I will change this to product updated then I will change the price to be like this now i will check if i am logged in now I'm logged in as a user then I will update this now i get the message product updated successfully then go to get all products then here there is an updated product like this now if i login as admin i will log out first here then i will login as admin then I will go to get all products and I will copy the id of the data entered by the admin copy then paste it here then i will log out again logout and I will login again as user now I'm logged in as a user and I will try this update this is the id input by admin then send request so now I get a forbidden access message, meaning that the user cannot change the data entered by the admin The user can only change the data he inputs himself then go back to Products.js then we just make the delete function i will add here async then I will copy all the code from this updateProduct copy then paste it here now I will change this Product to destroy like this and we don't need data here I will delete this then here I will also change to destroy I will delete the data like this then here I will change the message to deleted successfully save go to request.rest now i will make a new request here i will copy this then separate it with ### like this paste here then I will change the method to delete like this this is the id input by admin and if I try to delete it here then I get access here access is forbidden because I am logged in as a user and I will log out then I will login again as admin now I'm logged in as admin and if i click delete maka product deleted successfully and now i will copy this I will check again this is the data inputted by John Doe meaning this is the data inputted by the user and I will copy this id and I will paste it here of course I can delete this data because I am logged in as admin and now I will logout first and I will login as user now I'm logged in as a user and I will try to delete this then now I get the message product deleted successfully that means the user can delete the data that he input himself while admin can delete all data as well as data entered by themselves or data entered by the user until here the backend creation has been completed Next we will focus on the frontend I will close everything close all I will collapse this then I will open a new terminal here now I am in the authentication folder not in the backend folder here I open two terminals the first terminal here is the backend running here while here for the frontend then here I will create a react project npx create-react-app then I name it frontend and I will integrate directly with the redux toolkit because I will use redux here redux template like this enter if the installation is complete I will cd into the frontend folder now i'm inside the frontend folder I will clear first then I will install some dependencies that we need npm install the first one I installed react-router-dom react-router-dom then I will also install axios because we will interact with the API then i will also install bulma css for the user interface style then i will also install react-icons because later we will use the icon enter Then to make sure our project is going well run our frontend project with the command npm start then go to browser and visit localhost port 3000 like this if it goes well it will look like this back to vs code then i will do a little clean up go to frontend then src then here there is an additional folder, namely the features folder and in the features folder there is a counter folder where the contents are Counter.js and counterApi, counterSlice, and counterSlice.spec.js then i will delete this counter folder delete then I will also delete App.css kemudian App.test.js, index.css, logo.svg, reportWebVitals.js, setupTests.js I will delete everything then go to index.js then here there is a provider and also a store this is from app folder store.js because our project is integrated with redux toolkit then here there is a provider then here the store takes it from the store here then i will delete this index.css then also reportWebVitals then here I also delete the reportWebVitals function save then go to App.js I will delete everything here then i will also delete this header then i will also delete the class for a while will give here loram5 like this save then go to app then store.js then I will delete this because we have deleted the file then also this counterReducer save then back to browser if it goes well it will look like this then go to index.js then I will import the bulma here import bulma/css/bulma.css like this save then i will create a folder here i name it components then I will create a component file here I named it Navbar.jsx You can also use .js but here I use .jsx so that later the snippet will work well You can also use .js for example here App.js and for the snippet to work properly go here to the bottom right corner select language then i will change to react like this and I will choose javascript react so here the logo has changed to the react logo like this and the same as this it's actually the same then if i save it will be formatted automatically like this then go to navbar here I am using the ES7 React/Redux/React-Native snippets extension extension if you haven't installed this extension, please install it then I also installed bulma snippets to make it easier for us to play with bulma CSS back to our project then here rafce it will be generated automatically like this then i will delete this and here I will create a navbar I will choose this it will be generated automatically like this this is from bulma snippets then here there is an image tag then here I will add the lid here like this here I will delete the menu that we don't need I will delete this then i also delete this sign up then here I will use NavLink from react-router-dom import from react-router-dom like this then here I will import NavLink then I will change this to NavLink here and also this then i will remove the href then this NavLink has an attribute which is 'to' and I will point to /dashboard like this then here I will add href I will give the href here # like this then here I will delete this start navbar because we don't need it then at login I will use the here button and here is the button I will change to logout like this save it will be formatted automatically then here the Image tag we also need alt then here I give a logo like this then here I already have the logo I will replace this logo I already have the logo and I'm going to drag it over here into the src folder now the song has appeared here then I will import the logo here import logo from ../logo.png like this then I will parse the logo here logos like this save then here on the class navbar I will add another class which is is-fixed-top like this so that later when we scroll down the navbar stays at the top then I will also give another class, namely has-shadow like this so that later there will be a shadow on the navbar save then I will also make other components new file I named Sidebar.jsx like this as usual rafce then here I will copy the code from the documentation bulma go to browser and visit bulma.io go to the documentation then here on components I will find here Menu and I will copy this copy then go to vs code and i will paste it here like this save then I will change this class to className I will Ctrl + D here then i will change to className like this save then I will also give a shadow here has-shadow like this then I will also use NavLink here import from react-router-dom then here is NavLink and I will use here NavLink on the dashboard then attribute and here I will point to the dashboard like this then I copy this and paste it here then here I will give the menu here products like this then i will redirect this to /products like this and I will change this to Admin and I will copy this then paste it here then here I will give Users like this then here /users like this and I will delete the menus that we don't need I will delete this then also this then here I will give here Settings then I only need one menu here I will delete this and I will later this becomes a button then here is the button then here is the button to logout like this and I will give a class here className the class is button this is class bulma then is-white like this save then I will create another folder here new folder I name the pages then in this folder I created a file I named Layout.jsx like this then here rafce then here I will make the Layout This layout takes the parameter i.e. children then here we will use react fragment React.Fragment like this then I will import the navbar and sidebar here import Navbar then import Sidebar like this then here I will parse here the Navbar then here I will create a div with class columns like this then here I will also give another class, namely margin-top I enter here 6 then inside this div I will also create a div with column class like this without s and I will also give a class here is-2 like this then in this div I will parse here the Sidebar like this then I will create another div with another column class like this then I will also make another one, namely has-background-light like this then in it here I will make a main tag then I will render the children here like this save then here I will create a file again new file I named it Dashboard.jsx like this then here rafce and then here I will import the Layout import Layout and I will change this to Layout like this then for a while I will give here lorem2 save then I will create a component again here new file I named Welcome.jsx like this as usual rafce then here I will give the h1 tag here and I will label it here Dashboard like this and I will give a class here className then the class is title then here I will give the h2 tag here and I will give a subtitle class like this then here I will give the label Welcome Back later here is the user who is currently logged in like this for the time being i will leave it like this save then go to App.js then here I will use react-router-dom import from react-router-dom then here I import BrowserRouter then Routes then Route like this then here BrowserRouter then here it closes I'll save it to tidy it up it will be formatted automatically like this then here Routes then here the route is like this then the attribute is path then here /dashboard then here element and here are the components that we will render I will import the components here import I won't take it from components but from page from here from pages Dashboards like this from pages dan dashboard then I will parse the dashboard here I will close immediately like this I will delete this save then go to browser then I will access localhost port 3000/dashboard like this enter then it will look like this here is the navbar then here is the sidebar then I will tidy it up again back to vs code then go to Layout and here I will add a custom style then here I will use inline CSS I added here the style then the style is I will give here minHeight like this then the value I will give here is 100vh like this save back to browser so now here it's pretty neat here Then I'll tidy this up again back to vs code then go to Sidebar and here I will give here the padding left and I will give here the padding left 2 like this save back to browser then here there is space here then here I will add the icon back to vs code then here on the sidebar I will import the react icon import from react-icons like this and here I will use ionic icons / like this and I will use here io5 like this then first I will import ioPerson like this then also ioPricetag like this then ioHome then ioLogOut then I use his ioHome here ioHome like this then here ioPricetag then here ioPerson then here ioLogOut like this save back to browser so now we have the icons here then I will import these Welcome components in the Dashboard I will import here import Welcome then I will render these Welcome components here like this save back to browser now here there is a dashboard and welcome back back to vs code then I will create a component again here I named it Login.jsx rafce then i will delete this here I made a hero and I will use full hero and i will delete this then here i will also add is-fullwidth like this and I will change this to has-background-gray-light like this then here I will create a div with class columns and I will give an is-centered class like this so that later the login form will be in the middle then i will create another div with class column and I will give class is-4 like this then here I make a form I will remove the action then here I will give a class the class is a box like this then here I will give a div with a class field like this then in here I will create a label with the label class I will remove the htmlFor then here the label I will give Email then here there is another div with class control then here there is a text input with an input class like this then i will give placeholder then here email like this and I will copy this then paste it here then here is the password and here is the password then here I will give stars like this then paste again here and here we need a button I don't need a label here then here I will replace it with button button dengan class button here I label Login then here I will also add the is-success class then is-fullwidth like this save then go to App.js then I will import the login here import Login we take it from components because I don't want this login form to be inside Layout I will copy this then here / like this and I will change this to login like this save back to browser if i access localhost port 3000 then here there is a login form then i need to add a label here and also a little margin back to vs code go Login.jsx and here I add margin-top 5 like this then here above the form I will give a label here h1 then here sign in like this then i will give class title like this then is-2 save back to browser I want to sign in it's in here back to vs code I will cut this then paste it in the form like this save back to browser then now there is Sign In here back to vs code then I will create a component file again I named it UserList.jsx rafce then here I will copy some code from the Welcome component I will copy this back to UserList then i will paste it here and I will change this to users then here the list of users like this then here I will create a table and inside the table there is a heading for the table I will group like this then in the head there is a row and in the row there is a column and I will make the column 5 like this then I will make the body I will group again then in the body there is a row then in the row there is a column and I will also make the column 5 like this enter it will be generated automatically like this then I will also add a class here and I will give the class that is table then is-striped then is-fullwidth like this then here number and here's the name then here email then here is the role then here actions for the time being I will leave the body blank like this save then I will create a page here new file then I named Users.jsx rafce then here I will import the layout import Layout then I will also import the UserList component import UserList like this then here I will change it to Layout then in my layout I will render the UserList like this save then go to App.js and here I will create a new Route I will duplicate this then I will import the users from pages/users like this then I will render these users here then here I will change to users like this save back to browser then i will go to /users like this then there are users here then here is the List of Users then here is the table back to vs code then I will create a component again here new file then I name it ProductList.jsx then here rafce and then I will copy the code from UserList I will copy this copy then go to ProductList.jsx and I will paste it here then here I will change to Products then here is the list of products like this and here is the product name then here is the price and then here Created By like this then here actions save then I will create a new page here again new file I named Products.jsx like this rafce then here I will import the Layout then I will also import the ProductList component import ProductList like this then here Layout then I will render here the ProductList like this save go to App.js and I will import it here import Products from page/Products seperti ini then i will duplicate this then here I change to products then here are also products like this save go to browser now if i go to products then here there are products list of products dan disini tablenya nomor, product name, price, created by, dan actions back to vs code then I will create a component file again new file I named it FormAddUser.jsx rafce then I will copy some code from Welcome I will copy this then i will paste it here like this and here I will change to Users then here I will change to Add New User then here I create a div with class card then I will also add another class, namely is-shadowless like this so that later the card doesn't have a shadow then in this div I will create another div with the card-content class like this then inside this div I will also create another div I forgot to add here the dot then inside this div I will also create another div with class content like this enter it will be generated automatically like this then in here I will make a form and I will copy from Login I will copy the form here then return to FormAddUser then paste it here and I will remove the className box and I will also remove this sign in then here there is an email then i also need name I will copy this then paste on it and here's the name then here's the name like this then here is the password and I will copy this then paste here then this is to confirm the password then I will paste again here here for the role role in the role I will use select here I will delete this then for select I will also add here a div with class select then I will also add another class, namely is-fullwidth like this then here I will make a select I will remove the name and id like this then here there is an option and the option has value and the value here I will set admin like this then here the label I will give admin and I will duplicate this then here user then here the label I will set to user like this then here on the button I will remove the margin-top then I will add here the class control div and I will insert the button in the div I will drag here then I will change the button to Save like this then I don't need is-fullwidth here i delete save then I will copy all the code from this FormAddUser copy then I will create a component again I named it FormEditUser.jsx then paste here then here I will change it to FormEditUser then I will change the button to Update like this then here in the function I will also change it to FormEditUser same as the file name then here are the subtitles and I will change to update user save then I will make some pages here new file the first is AddUser.jsx then here rafce and I will import the Layout import Layout then I will also import FormAddUser then I will change this to Layout then here FormAddUser like this I will copy this copy then I will create a new page again new file EditUser.jsx then paste here and I will change this to import FormEditUser and I will parse the FormEditUser here like this save and I will change this to EditUser according to the filename then here is also EditUser like this save then go to App.js then I will import AddUser and also EditUser import AddUser then import EditUser like this then i will duplicate this like this then here /add then here /edit/:id like this because we need id parameter for edit and then here I will change to AddUser and then here I will change to EditUser like this save back to browser then go to users here now i'm on users then if i go to /add like this then here there is an add new user form there is a name, email, password, confirm password and also the role like this then if I go to users/edit/1 for example enter so now there is a user update here ada name, email, password, confirm password, role then here there is an update button back to vs code I will create a component file again new file I named it FormAddProduct.jsx rafce like this then I copy the code from FormAddUser I will copy from here come here copy go to FormAddProduct then paste it here here we don't need a role then we also don't need a password and confirm the password we only need here the name i.e. the product name then here we also need price like this then here is the price and here I will change it to a product name like this and I will change these users to Products and here Add New Product like this save then I will copy this copy then i create component file again new file FormEditProduct.jsx then i will paste it here and I will change this to FormEditProduct like this and I will change the button to update then here I change it to FormEditProduct like this then i will change this to edit product like this save then I will make a few more pages I will copy from AddUser I will copy this then I will create a new page new file then here I name it AddProduct.jsx enter I will paste it here then I 'll import its FormAddProduct here import FormAddProduct and I will change this to FormAddProduct like this save the reason we made a page like this so that later when we render some components we just enter here, import here and directly enter here thus our project will be easier to develop then I will change this to AddProduct then here is also AddProduct like this same as the file name save then I will copy this copy then I will create a new file and name it EditProduct.jsx then paste here I will change this to EditProduct then here is also EditProduct like this then I will import the components here import FormEditProduct then i will parse here like this save then go to App.js here then second import AddProduct and also EditProduct import AddProduct then import EditProduct like this then i will duplicate this like this then here /add then here /edit/ then we need the id here and here I will render AddProduct then here I will render EditProduct like this save back to browser now I will go to Products then if I access /add like this then I will be directed to Add New Product like this then if /edit/1 for example then it will be directed to Edit Product like this back to vs code Now we have finished creating the user interface then we just run the function then go to the index.js file here is the most important part if you skip this part then everything will not work here I import axios import axios from axios here I will set the default credentials axios.defaults.withCredentials and I will set it to true if you don't do this then you have to set it manually in every request the reason why I did this in the index.js file so that every request we make to the server always include the credentials because this applies globally so we no longer need to manually include the credentials in every request save then in the features folder I will create a file here I named it authSlice.js then here I will import createSlice and createAsyncThunk import createSlice from @reduxjs/toolkit like this then comma here createAsyncThunk like this then I will also import axios because we will interact with the API import axios from axios then I make the initial state here const initialState then the first state is user I will set the default to null like this then isError by default I will set it to false then isSuccess by default I will set it to false then isLoading and I will set the default to false like this then here I will also add a message and by default I will enter here an empty string like this then here I will make the slice here I will export directly export const I named authSlice then createSlice then here's the name I named auth like this then initial state we take the initialState from here then here there are reducers in reducers here I will create a method that is reset this serves to reset this state then here brings the state then I will reset its value to initialState again if we dispatch this method then the value will be returned like this then here I will create a method to make a request to our API that is login export const I named it LoginUser createAsyncThunk then here I give the name user/LoginUser like this I will adjust the name of the function so that it will be easier to monitor later then here is async and here brings user data then here there is a thunkAPI like this this will be useful later for error handling then I'll use a try-catch block here then here I will create a variable const response = axios I will use await here .post then here the endpoint is http://localhost our server port is 5000 then the endpoint is /login like this then here the data are email and password we take the email from user.email like this come then password we take the password from user.password like this then here I will return the response response.data like this then if there is an error I will check if error.response I will check the error response and I will get the message from the backend this way const then I will create a message . variable then we take the data from error.response.data.msg because we set the error message in the msg on the backend then I will return here return thunkAPI.rejectWithValue then I will enter the message here like this then to handle this createAsyncThunk we use extra reducer i add here extraReducers here bring the builder then builder.addCase then LoginUser then .pending come then here I will take the state when he is pending then I will set the loading to true state.isLoading = true like this then builder.addCase then LoginUser again .fulfilled if he succeeds then I took the state state and also action like this then when he succeeds then I will set the loading to false I will copy this I will set the loading to false then my state.isSuccess will be set to true then I will enter the user state state.user I will take the data from action.payload like this because we have data in the payload which we return from here then when an error occurs builder.addCase then LoginUser.rejected means there is an error I will take the state state then I will also take the action then I will also set the loading to false like this then state.isError and I will set the error to true like this then state.message I will insert the message here and we take the message from action.payload because when an error occurs here we take the error message from here then we send it here Therefore we have data from action.payload from here when it's rejected like this then we just export this export default then authSlice.reducer like this then we also need to export this reset function as an action I will export here export const reset = authSlice.actions like this save then we go to store.js here which is in the app folder then we add here the reducer import I named authReducer like this from ../ then features/authSlice like this then here auth and I will take the reducer from authReducer like this save then we just dispatch the action on the login component I will go to Login here then here i will use useState hook I will add here useState then i will also use useEffect then here I will also use useDispatch and useSelector import useDispatch from react-redux then I will also import useSelector then i will also import useNavigate from react-router-dom because we will redirect the user after login import useNavigate from react-router-dom then we need to import the action from redux import from ../ then features then the file is authSlice like this then I will call the method, namely LoginUser and then reset it like this then I will create a new state here const email setEmail = useState and the initial value I will put here an empty string like this I will duplicate this then the second state is password then here setPassword like this then here in my email I will add value here then we take the value from the email then i will also add onChange like this then I will catch the event here event then here the function to change the state is setEmail then e.target.value like this I will tidy up the code first like this then I will copy this and paste here then here is the password and here setPassword save then I will create another variable here const dispatch = useDispatch() then here const navigate = useNavigate() then I will take the value from the redux store const I will destructure directly like this the first is the user then isError like this then isSuccess then isLoading then the message = useSelector then here is the state and here we take the state from state.auth like this save then on the form here i will add onSubmit then here I will make the Auth method like this then I will make this method here const Auth then I'll catch the event here Then I will prevent the default so that when we submit the page it doesn't reload e.preventDefault() then we just dispatch this LoginUser function dispatch LoginUser then here is the data We take the data from the email and then the password is like this then after we dispatch , the user state will be set and if the user has been set then I will redirect to the dashboard and that means we have successfully logged in I use here useEffect Then here I will check if if there is a user like this or isSuccess then I will redirect to the dashboard navigate then /dashboard like this then after that we will reset the state again I will dispatch reset like this then I will add the dependencies here the dependency is user then isSuccess then dispatch then navigate like this save then if there is an error I will show the error I will do it here I will use paragraph tags here then i will give class the class is has-text-centered like this so that later the text is in the middle then I will parse the error message here, namely from the message here before that we will check first if there is an error or not I can check this way then i will close here here I will check isError like this then we will render this and we display the message from a message like this I will check again here on the button I will add here the type then the type is submit like this save then here is isLoading and I will use this isLoading I will use it here on the button I will check here in this way isLoading if the loading is true then I will render loading like this then if the loading is false then I will render this login like this save then go to browser then i will go to localhost port 3000 then I will try to login for example I will log in like this login then we get the message user not found and if I login with mfikri@gmail.com user not found and I use here admin@gmail.com then the password is 123456 login then now I am directed to the dashboard then I will return it here I will refresh then I will inspect here here I use redux devtool i will go here here there are states, namely user, isError, isSuccess, loading and the message then if I login for example here admin@gmail.com then the password is here and when i login then go here when the login is successful then the state will be set like this the uuid then the name, email and also role then the error is false, success is true like this then we reset again now we don't protect this dashboard page so I can access it even though I'm not logged in now the state is undefined but i can access the dashboard here That's why we need to protect this dashboard back to vs code go to authSlice.js here then here I will also create a method to get user login and also logout I will copy this then paste it here then here I will change the method to getMe like this because we have the Me function on the backend then here I will change to user/getMe and we don't need data here I will change to underscore like this then the method is get like this then the endpoint is /me like this and we don't need data here i will delete like this then I will also create a method to logout I will copy this paste here and I will change this to LogOut and I will change this to user/LogOut and we don't need any parameters here I will remove the try-catch block then I'll also delete this because we don't need it and i will also delete this then this then here the method I will change to delete because to logout we use the delete method then the endpoint is /logout like this then we don't need to add extraReducers to logout it but in the getMe method we need to add extraReducers I will copy this then I put a label here get user login then paste here then I will change this to getMe like this I will copy this paste here and also here save then go to pages not on the components dashboard here and I will protect this dashboard the reason we protect this dashboard so that later every component in this dashboard can access its state I will import here useDispatch and useSelector import useDispatch then useSelector like this from react-redux then I will also use useNavigate import useNavigate from react-router-dom then I will also call the function getMe from redux import getMe from ../features/authSlice like this then here I will also use the useEffect hook i will add here useEffect then here const dispatch = useDispatch() then const navigate = useNavigate() then const I will take the error from the state isError = useSelector() then here is the state then state.auth like this then I will dispatch this getMe function when the component is mounted to the DOM I will add here useEffect useEffect then i will dispatch getMe like this then i add the dependency here which is dispatch like this then I will add one more useEffect here paste here the reason we use two useEffect here because I want him to be dispatched first and then we will validate it later then I will validate here if if there is an error isError then we will redirect to login again navigate() then here "/" like this then here in the dependencies I will add here isError and then here I'm going to change dispatch to navigate because we don't need dispatch in this useEffect save back to browser now if i access the dashboard here then I get the state here the reason we managed to fetch data from this getMe because we have logged in and the session is set in Cookie I will check here on the application then here Cookies then the session has been set here back to redux devtool Then I will dispatch the logout so that later we can see the changes back to vs code then go to sidebar then i will copy some code from login I will copy this useDispatch, useSelector and LoginUser and reset it I will copy this then go to sidebar and i will paste it here here we have imported the react-router-dom then I will cut this then I will paste it here I will delete this then back to login and I will copy this useDispatch and its useNavigate go back to the sidebar and I'll paste it here then I will select the user from the redux store const user = useSelector() then here is the state state.auth like this then here there is a logout button i will add here onClick then here I will make the method, namely logout like this then I will make the method here const logout then here I just dispatch logout it turns out that I haven't called LogOut here, it shouldn't be LoginUser but LogOut like this and I will dispatch this like this then after dispatch logout then we reset the state again dispatch reset like this then after we reset and we redirect again to login navigate("/") seperti ini save then I will copy this and go to navbar and i will paste it here back to sidebar and I will copy this then go to navbar again and paste here then we need to add here useNavigate like this and we just call this logout function here because we have a logout button here on the navbar I will add here onClick and logout like this save then now we have two logout buttons one in navbar and one in sidebar then go to browser I will refresh so now we get the data here it means we have successfully logged in and now when i log out here then I will be directed again to the login form and when we see here LogOut/fulfilled then we reset the state again if now i access the dashboard like this then I will be directed again to the login form and here there is a message please login to your account means we can no longer access the dashboard without logging in back to vs code then I can do the same way to protect all these pages i will go to dashboard then I will copy this copy then I will paste it in AddProduct I will paste it here then go to AddUser then paste again go to EditProduct paste again then go to EditUser Paste again here then we go to Products we don't need it in Layout Paste again here then in Users Paste again here then back to Dashboard and I will copy this copy then go to AddProduct again paste here and don't forget to add here useEffect useEffect like this save then go to AddUser Paste again here add useEffect save then go to EditProduct Paste again here don't forget to add useEffect save go to EditUser and paste again here then here useEffect save then go to Products then paste here add useEffect save go to Users then paste here and add useEffect like this now every page we can't access if we don't login then this Users page, AddUser, and EditUser can only be accessed by admin while if we login as user we can't access it Therefore I will add here a user like this this is from the global state then I will validate again here if then here user we can't make it like this user.role because this user will be null when he is pending Therefore we need to make it like this user then we add && like this if the user.role is not the same as admin then we will redirect to a certain page actually we can make one more page for Forbidden but I will only redirect to the dashboard if the user is logged in not admin and when he accesses this user's page then I will redirect to the dashboard and I don't want him to log out directly I will redirect here navigate then I will redirect to the dashboard like this then in the dependencies I will add here user like this save then I will copy this copy then go to AddUser and I will replace this and don't forget to add a user like this here save then go to EditUser I will also replace this then here is also the user save while in AddProduct and EditProduct it's still the same then back to browser I will close this I will refresh again then I will login as admin@gmail.com then here is the password now i have successfully logged in and if I refresh I'm still logged in then here Products and Users now i can access this user if i log out i log out here and login as user we have a user account that is john@gmail.com then the password now if I access Products I can access Products then if I access Users then I will redirect to the dashboard means I can't access these users then I just remove this menu if we log in as a user back to vs code then go to sidebar then here we have a user here from the global state then we can use this then here there is the users menu I will block this here I will check the user we need to make it like this because the user will be set to null while pending user.role like this same as admin then we will render this like this then here we can't render two tags like this we can only render one tag I will add a div here then in this div I will cut this then drag here save then back to browser now we no longer have users menu here then i will log out and I will login as admin again admin@gmail.com then the password now we have users . menu because I'm logged in as admin now then I want to display the name of the user who is currently logged in here back to vs code then go to Welcome then here I just import useSelector from react-redux import useSelector from react-redux like this then const I will call the user from the global state useSelector then here is the state state.auth like this then we just show it here I will use strong text here then here I will render the username user && like this then user.name like this save now back to browser then here is M Fikri here if i refresh then we still get M Fikri here we can access Products and refresh again we are still logged in and also Users and refresh we are still logged in then we just show the product and also the user here back to vs code then go to ProductList here i will start with ProductList then here I will use useState and useEffect i will add here useState then useEffect like this then here I will also use the link from react-router-dom import then here the link from react-router-dom then I will also import axios because we will interact with the API import axios from axios actually we can create a redux store for this product but in this video I will not do that because I also don't need this Product to be accessed from other components i just want to access it from this component therefore I will fetch the data directly here I will create a new state here const I name the products then setProducts = useState() then the initial value I will put here empty array like this then here I will create a method for fetching data const getProducts like this then i will use asyncronous function then here const response then await axios.get() then here the endpoint is http://localhost then the port is 5000 then /products like this then we will enter the response into this state setProducts then response.data like this then I will call this method in it useEffect useEffect getProducts() like this then here I add the dependencies empty array like this because I want this function to run when on mounted then we just loop the data here in the table I will loop here products.map then here for each item I will name the product like this then I will take the index as well then I will cut this then drag here I'll fix the code first then here every loop has a unique key I will add the key here then I will take the key from product.uuid like this because we have a uuid field then here the number and the number I took from index + 1 like this then here product.name then here product.price and then here product.user.name like this and then here I need the edit and delete buttons first i will use here link then this link has 'to' attribute I will use a backtick like this here then /products like this then edit then here's the id we take the id from product.uuid like this then here the label I will give here Edit then here I will also give className here the class is button I will use the bulma class then is-small then is-info like this then i will duplicate this then here I will change it to button I will use the button here then we don't need this then here is the button like this here I will use here is-danger then here Delete to delete I will add here the event, namely onClick and here I will call the delete product method I will do like this because this method will take permeter then here the method is deleteProduct like this and we take the parameters from product.uuid then I will create the deleteProduct method here const deleteProduct bring the parameter i.e. I name here productId like this then i will delete it right away await axios.delete() then here is the endpoint I will use a backtick like this http://localhost the port is 5000 then /products/id we take the id from the productId like this then if it is successfully deleted I will call this getProducts method again so we can see the changes to the user interface save then I will also add a button here on the table I will use the link I will add here class the class is button then is-primary and I will also give here the margin-bottom and I will set it to 2 like this so that later there is a space between this button and the table then here I will point to /products/add like this here I will give the Add New label like this save back to browser here there is an error await back to vs code I forgot to add here asyncronous I will add here async save back back to browser now go to Products here I can access all products here including products made by John Doe because now I'm logged in as admin if I click add new it will be redirected here and then if I click edit, it will be directed to the edit form and here is the uuid and if I click delete for example I will delete one here it will be removed from the list if i log out and I will login as John here john@gmail.com then the password and login here welcome back John Doe then I will go to Products then I can only see the product input by John Doe I can't see the product entered by the admin then i will log out again and I will login as admin again then the password go to Products then I will run this add new method back to vs code then go to FormAddProduct here then here i will use useState hook I will add here useState then i will also import axios then i will also import useNavigate from react-router-dom import useNavigate then here I will create some state const the first is name then setName then here useState() then the initial value I will enter here empty string I will duplicate this then here is the price and then here also setPrice then here's the message I will display the message if there is an error then here setMessage then const navigate = useNavigate() then here in the input text I will add here the value then we take the value from name then here there is onChange and I will catch the event here then here is the function to update the state setName then here e.target.value like this then I will copy this then paste here I will fix the code then here the value is price then here setPrice like this on the save button I will add here the type then the type is submit like this then here on the form I will add here onSubmit like this and I will create the saveProduct method like this then I will make this method here const saveProduct then I will catch the event here Then I will prevent the default so that when we submit the page it doesn't reload e.preventDefault() like this then i will use asyncronous function here and I will also use try-catch block then here await axios.post then here the endpoint is http://localhost the port is 5000 then /products like this then here is the data that we want to submit the first is name the name we take from the name of the state then price we take the price from the state, the price is like this then if there is an error I will check if error.response if there is an error in the response I will take the error and I will set it in this state setMsg and I will take the error from here error.response.data.msg like this then we just call this message I will show it in this form here I will use paragraph tags and I will give className here the className is has-text-centered like this and then I will parse the message here like this save back to browser then I reload We are still logged in then if i submit then there is a validation error here if I enter here product 5 for example then I didn't enter the price save So there is a validation error here we can customize the model on the backend but I'm using the default here because this is just a tutorial while here I will enter it here like this save looks like i forgot to redirect back to vs code after we save I will redirect here navigate then I will redirect to /products like this save back to browser I will use here 6 more then like this save now we have redirected here This is the data we entered earlier then we just run the edit function here back to vs code and I will copy this go to FormEditProduct then paste here and I will also use here useState dan useEffect like this back to FormAddProduct and I will copy this then paste here back to FormAddProduct and I will copy this then paste here back to FormAddProduct copy this then I will paste it here I will fix the code like this then here on the update button I will add here the type then the type is submit like this save then here I will add here onSubmit then I named the method, namely updateProduct like this I will create the updateProduct function here I will change this saveProduct like this then for update we need parameter id and we take the id parameter from parameter we can add here useParams then here const I will take the id directly here id useParams() like this then here I will change the method to patch because to update we use the patch method then here I will change it to a backtick then here is the backtick then / here the id we take the id from the parameter , namely the id here then we just show this message here use paragraph tags then here message then I will give the class here has-text-centered like this save then when onMount I want to display the data in the form I can use here useEffect i will add here useEffect like this then in useEffect I will create a method const I named it getProductById like this and I will also use asyncronous here then I will also use a try-catch block const response = await axios.get() then here is the endpoint I will copy this because coincidentally the endpoints are the same only different method then here I will set the response in its state the first one is setName then response.data.name and I will duplicate this then here setPrice then here's response.data.price like this then if there is an error I will copy this then paste here then after that we will call this method getProductById I will call here like this then in the dependencies we need id here like this save go to browser now if i reload the data will appear here and if i update like this Product 5 updated update so now I managed to update Product 5 like this that means our project is going well I will delete this again then it will disappear from the list then we just focus on users here back to vs code then go to the UserList component here then here i will use useState and useEffect then I will also use axios import axios from axios then I will also use the link from react-router-dom import link from react-router-dom like this then I will copy the code from the ProductList here I will copy all of this then back to UserList and paste here then i will change this I changed to Users like this then here setUsers then here getUsers and here the method is also getUsers and here too getUsers then here setUsers then here deleteUser like this then here userId and I will parse the userId here then here users and here are also users like this then I live this data users loop here users.map then here the user then the index and I will cut this then drag here I'll fix the code first then here every loop has a unique key I will add the key here the key comes from user.uuid like this then here is the number we take the number from index+1 like this then here user.name then here user.email then here the user.role is like this then here there is a button then I will copy from ProductList go to ProductList here and I will copy this copy then back to UserList and i will paste it here then I will change this to user/edit/user.uuid like this then here I will change to deleteUser then here user.uuid like this Then I will add a button above the table I will copy from ProductList here this link copy then back to UserList and paste here here I will point to users/add like this save back to browser now here there are two data users namely John and M Fikri here with the roles as user and admin then we just run the function to add this new back to vs code then go to FormAddUser here then I will copy the code from FormAddProduct I will copy from here then return to FormAddUser and paste it here then back to FormAddProduct and I will copy this then paste in FormAddUser here here we need some state here are name, email, password, confirm password, and role then here's the name and then here email and here setEmail and I will create another state I will duplicate this then here is the password and here setPassword like this then here confPassword like this then here setConfPassword and then i will duplicate again and here is the role then here setRole like this then here is the message I will change this function to saveUser then here on the form I will add onSubmit then here saveUser like this then input the text here I will add here the value then we take the value from name then i will add here onChange Then here I will catch the event here event then here setName e.target.value like this I will copy this then paste it here here is e-mail then here setEmail then paste again here and here is the password then here setPassword like this Paste again here then here confPassword then here setConfPassword like this on the role here there is select and here is the value the value is role then there is onChange and here is the event then setRole e.target.value like this then on the button I will add here type then the type is submit like this then on the saveUser method I will change this to email then we also take the email from the email here then password and we take the password from a password like this then confPassword we take it from confPassword then roll and we take it from a role like this then if successfully saved we will redirect to /users like this and also there is an error then I will set the error in this state then i will show it here I will use paragraph tags I will post the message here like this I will give a class here has-text-centered like this save then back to browser I will refresh this then I will insert new data here for example here Joko then email joko@gmail.com then the password is like this then the role is user save then there is a message here product price cannot be null it turns out that there is an error here product price back to vs code I will check here turns out we sent a request to the /products endpoint here should be /users like this save back to browser I will check again I will enter the password here then here is the password again save then we have successfully entered the data here then we just run the edit function I will be here and I will display the data here back to vs code then I will copy this go to FormEditUser then paste it here and go to FormEditUser again then I will copy this state come here go to FormEditUser again and paste here then I changed this to updateUser then here on the form I will add onSubmit then here updateUser like this I will take this field here from FormAddUser here I will copy the contents of this form from here until closing this form I will copy this copy then go to FormEditUser and I will paste it here paste like this and I will change it to this update then we just add here useEffect useEffect like this then I will copy some code from FormEditProduct I will copy this then I will take this useEffect back to FormEditUser then paste here and back again to FormEditProduct then I will take the parameters here back to FormEditUser and I will paste it here then we add here useParams like this then I change this to getUserById then here's the endpoint we access it /users like this and we will set the response name then here setEmail then response.data.email then i will duplicate this again then here setRole like this response.data.role like this we don't need to enter the password because it's sensitive information then we just call this method getUserById and then parse here then here we will change the method to patch like this because we update using the patch method then save back to browser here, the data appears, namely Joko 's email, then the password is empty then here is the role of the user I will change this to Joko Updated then I will change to admin update I will check if there is an error and I will inspect element go to the console I will update it turns out that here there is an error because we did not include the id in the update back to vs code I need to add his id here I will copy this copy coincidentally the endpoint is the same I will delete this then I will change it to a backtick like this paste save back back to browser I reloaded then now it will update the data again update so now the data has been updated like this and there are no more errors if I delete then the data is successfully deleted like this then I will try to insert one more data here then I will login with that user add new then here I will add Laura for example then here laura@gmail.com then the password is here and here confirm the password then here's the role as a user then save then here is Laura and I will log out then I will login as Laura laura@gmail.com then the password is here login then here welcome back Laura here then I go to Products now Laura has no product then I will add new here for example, here Product Laura 1 for example the price is like this save then I will insert another data Product Laura 2 save then i will edit edit like this then Laura two then Updated like this update then successfully updated and if I delete then it was successfully deleted now i don't have Users menu here because I am logged in as a user then i will log out again and I'm logged in as admin@gmail.com then the password login now I'm logged in as M Fikri and here there is a menu Users here because I'm logged in as admin then if i go to Products then now I can access all Products this is the product that was input by John this is the product that was inputted by the admin then is the product entered by the user that is Laura if I refresh we are still logged in and if i log out and I try to access products like this then I will be redirected to the login page again and here there is a message that please login to your account so many tutorials this time If it's your first time watching a video on this channel, please subscribe And don't forget to turn on the notification bell so that every time I upload a useful video like this you will receive a notification and see you in the next video
Info
Channel: Coder Media
Views: 79,192
Rating: undefined out of 5
Keywords: login react js, react js login and registration, react login, react js login, login node js, node js express, react js indonesia, node js authentication, node js login, node js mysql, belajar node js, node js login system, react mysql, login register react js, belajar react js, express mysql, react login and registration, react node js
Id: OJU0L9D-Zdo
Channel Id: undefined
Length: 221min 16sec (13276 seconds)
Published: Tue Jul 26 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.