Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Done with 01-easy-todo-app of week 4 #261

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
173 changes: 149 additions & 24 deletions week-3/04-course-app-hard/index.js
Original file line number Diff line number Diff line change
@@ -1,52 +1,177 @@
const express = require('express');
const jwt = require('jsonwebtoken')
const mongoose = require('mongoose')
const app = express();

app.use(express.json());
app.use(express.json()); // to read body

const SECRET = 'wow,wow,Encryption'

// Mongoose Schemas

const userSchema = new mongoose.Schema({
username : {type : String}, //below is same
password: String,
purchasedCourses : [{type: mongoose.Schema.Types.ObjectId, ref: 'Course'}]
});

const adminSchema = new mongoose.Schema({
username : String,
password : String
});

const courseSchema = new mongoose.Schema({
title : String,
description : String,
price : Number,
imageLink : String,
published : Boolean
});


//Defining mongoose models

const User = mongoose.model('User',userSchema);
const Admin = mongoose.model('Admin',adminSchema);
const Course = mongoose.model('Course', courseSchema);

// middleware for authentication using Jwt

function authenticateJwt(req,res,next){
const authHeader = req.headers.authorization;
if(authHeader){
const token = authHeader.split(" ")[1];
jwt.verify(token,SECRET,(err,user)=>{
if(err){
return res.sendStatus(403);
}
req.user = user;
next();
})
}
else{
res.sendStatus(401);
}
}

//connecting to MongoDB

mongoose.connect('mongodb+srv://naman19feb:[email protected]/',{useNewUrlParser : true, useUnifiedTopology: true, dbName:"courses"});



let ADMINS = [];
let USERS = [];
let COURSES = [];

// Admin routes
app.post('/admin/signup', (req, res) => {
// logic to sign up admin
app.post('/admin/signup', async (req, res) => {
const {username,password} = req.body;
const admin = await Admin.findOne({username : username});
if(admin){
res.send("User Already Exsist!")
}
else{
const obj = {username : username, password : password};
const newAdmin = new Admin(obj);
await newAdmin.save();
const token = jwt.sign({username, role: 'admin'},SECRET,{expiresIn : '1h'});
res.json({message : 'Admin created Successfully', token})
}
});

app.post('/admin/login', (req, res) => {
// logic to log in admin
app.post('/admin/login', async (req, res) => {
const {username, password} = req.body;
const admin = await Admin.findOne({username: username, password: password});
if(admin){
const token = jwt.sign({username , role:"admin"},SECRET,{expiresIn:"1h"});
res.json({message : "Login Successfull!", token})
}
else{
res.status(403).json({message : 'Wrong credentials'})
}

});

app.post('/admin/courses', (req, res) => {
// logic to create a course
app.post('/admin/courses',authenticateJwt, async(req, res) => {
const course = new Course(req.body);
await course.save();
res.status(200).json({message : "Course added Successfully", course})
});

app.put('/admin/courses/:courseId', (req, res) => {
// logic to edit a course
app.put('/admin/courses/:courseId',authenticateJwt, async(req, res) => {
const update = await Course.findByIdAndUpdate(req.params.courseId,req.body,{new : true});
if(update){
res.json({message: "Updated successfully", update})
}
else{
res.status(404).json({message: "Course not found!"})
}
});

app.get('/admin/courses', (req, res) => {
// logic to get all courses
app.get('/admin/courses',authenticateJwt, async (req, res) => {
const courses = await Course.find({});
res.json(courses);
});

// User routes
app.post('/users/signup', (req, res) => {
// logic to sign up user
app.post('/users/signup',async (req, res) => {
const {username, password} = req.body;
const user = await User.findOne({username : username})
if(user){
res.status(403).json({message : "User already exists"})
}
else{
const newUser = new User({username : username, password : password});
await newUser.save();
const token = jwt.sign({username, role :"user"},SECRET,{expiresIn : '1h'});
res.status(200).json({message:"User added successfully ", token});
}

});

app.post('/users/login', (req, res) => {
// logic to log in user
app.post('/users/login', async(req, res) => {
const {username,password} = req.headers;
const user = await User.findOne({username:username , password:password});
if(user){
const token = jwt.sign({username, role:"user"},SECRET,{expiresIn:'1h'});
res.status(200).json({message : "Login Successfull",token});
}
else{
res.status(403).json({message : "Authentication failed"})
}

});

app.get('/users/courses', (req, res) => {
// logic to list all courses
app.get('/users/courses',authenticateJwt, async (req, res) => {
const courses = await Course.find({published: true});
res.json(courses);
});

app.post('/users/courses/:courseId', (req, res) => {
// logic to purchase a course
app.post('/users/courses/:courseId',authenticateJwt, async (req, res) => {
const course = await Course.findById(req.params.courseId);
if(course){
const user = await User.findOne({username: req.headers.username});
if(user){
user.purchasedCourses.push(course);
await user.save();
res.json("Course Purchased Successfully!");
}
else{
res.status(403).json({message : "User not found"});
}
}
else{
res.status(404).json({message : "Course not found"});
}
});

app.get('/users/purchasedCourses', (req, res) => {
// logic to view purchased courses

app.get('/users/purchasedCourses',authenticateJwt, async(req, res) => {
const user = await User.findOne({username : req.headers.username}).populate('purchasedCourses');
if(user){
res.json({purchasedCourses: user.purchasedCourses || []});
}
else{
res.status(403).json({message : "User not found"});
}
});

app.listen(3000, () => {
Expand Down
59 changes: 46 additions & 13 deletions week-4/01-easy-todo-app/src/App.jsx
Original file line number Diff line number Diff line change
@@ -1,27 +1,60 @@
import { useState } from 'react'
import { useState, useEffect } from 'react'
import axios from "axios";
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import React from 'react';
import './App.css'


function getTodos(){
let todos = [];
React.useEffect(()=>{
axios.get("http://localhost:3000/todos").then((res)=>{
todos = res.data;
})
})
return todos;
}
function deleteTodos(id){
axios.delete("http://localhost:3000/todos"+"/"+id)
}
function createTodo(){
axios.post("http://localhost:3000/todos",{
title : "added from postButton",
description : "wow added"
})
}
function App() {
const [todos, setTodos] = useState([])
// fetch all todos from server
var [todos, setTodos] = useState([])
React.useEffect(()=>{
axios.get("http://localhost:3000/todos").then((res)=>{
setTodos(res.data);
})
})


return (
<>
<div>
<h1>Easy Todo App</h1>
<input type="text" />
</div>
</>
)
<button onClick={createTodo}>Add Todo</button>
{todos.map((todo)=>(
<div>
<Todo title = {todo.title} description = {todo.description} id = {todo.id} deleteTodoFun = {()=> deleteTodos(todo.id)}></Todo>
</div>
),[])}
</>
)


}

function Todo(props) {
// Add a delete button here so user can delete a TODO.
return <div>
{props.title}
</div>
return (<div>
{props.title} {' '}
{props.description}{' '}
<button onClick={props.deleteTodoFun}>Delete</button>
</div>)
}
export default App;


export default App