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

CSOC_WEEK3 #24

Open
wants to merge 6 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
8 changes: 6 additions & 2 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
{
"extends": ["next/babel", "next/core-web-vitals"]
}
"extends": ["next", "next/core-web-vitals"],
"rules": {
// Other rules
"@next/next/no-img-element": "off"
}
}
34 changes: 29 additions & 5 deletions components/AddTask.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,41 @@
import axios from "axios"
import { useState } from "react"
import { useAuth } from "../context/auth"

export default function AddTask() {
const [task, setTask] = useState("")
const { token } = useAuth()
const addTask = () => {
/**
* @todo Complete this function.
* @todo 1. Send the request to add the task to the backend server.
* @todo 2. Add the task in the dom.
*/
axios({
url : 'https://todo-app-csoc.herokuapp.com/todo/create/',
method : "post",
headers: {
Authorization: 'Token ' + token,
},
data : {
title: task
}
}

)
.then(function ({ data, status }) {
setTask("");


})
.catch(function (err) {
})


}
return (
<div className='flex items-center max-w-sm mt-24'>
<input
type='text'
className='todo-add-task-input px-4 py-2 placeholder-blueGray-300 text-blueGray-600 bg-white rounded text-sm border border-blueGray-300 outline-none focus:outline-none focus:ring w-full'
placeholder='Enter Task'
value={task}
onChange = {(e)=> {setTask(e.target.value)}}
/>
<button
type='button'
Expand Down
47 changes: 40 additions & 7 deletions components/LoginForm.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,40 @@
import React, { useState } from 'react'
import axios from '../utils/axios'
import { useAuth } from '../context/auth'
import { useRouter } from 'next/router'
import { API_URL } from "../utils/constants"
import {no_auth_required} from "../middlewares/no_auth_required";
import { toast } from "react-toastify";


export default function RegisterForm() {
no_auth_required();
const { setToken } = useAuth()
const router = useRouter()
const [password, setPassword] = useState('')
const [username, setUsername] = useState('')
const login = () => {
/***
* @todo Complete this function.
* @todo 1. Write code for form validation.
* @todo 2. Fetch the auth token from backend and login the user.
* @todo 3. Set the token in the context (See context/auth.js)
*/
axios({
url : API_URL+"auth/login/",
method : "post",
data : {username: username , password: password}
}
)
.then(function ({ data, status }) {
setToken(data.token)
router.reload()
console.log("success")
})
.catch(function (err) {
console.log(
'An account using same email or username is already created');
toast("Please Enter correct credentials");

})




}

return (
Expand All @@ -18,7 +47,9 @@ export default function RegisterForm() {
className='block border border-grey-light w-full p-3 rounded mb-4'
name='inputUsername'
id='inputUsername'
placeholder='Username'
placeholder='username'
onChange={(e) => setUsername(e.target.value)}
value={username}
/>

<input
Expand All @@ -27,6 +58,8 @@ export default function RegisterForm() {
name='inputPassword'
id='inputPassword'
placeholder='Password'
onChange={(e) => setPassword(e.target.value)}
value={password}
/>

<button
Expand Down
8 changes: 5 additions & 3 deletions components/Nav.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { useAuth } from '../context/auth'
*/

export default function Nav() {
const { logout, profileName, avatarImage } = useAuth()
const { logout, profileName, avatarImage,token } = useAuth()

return (
<nav className='bg-blue-600'>
Expand All @@ -22,6 +22,7 @@ export default function Nav() {
</Link>
</li>
</ul>

<ul className='flex'>
<li className='text-white mr-2'>
<Link href='/login'>Login</Link>
Expand All @@ -33,8 +34,8 @@ export default function Nav() {
<div className='inline-block relative w-28'>
<div className='group inline-block relative'>
<button className='bg-gray-300 text-gray-700 font-semibold py-2 px-4 rounded inline-flex items-center'>
<img src={avatarImage} />
<span className='mr-1'>{profileName}</span>
<img src={token!==undefined&&avatarImage} />
<span className='mr-1'>{token!==undefined&&profileName}</span>
<svg
className='fill-current h-4 w-4'
xmlns='http://www.w3.org/2000/svg'
Expand All @@ -56,6 +57,7 @@ export default function Nav() {
</ul>
</div>
</div>

</ul>
</nav>
)
Expand Down
10 changes: 7 additions & 3 deletions components/RegisterForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ import React, { useState } from 'react'
import axios from '../utils/axios'
import { useAuth } from '../context/auth'
import { useRouter } from 'next/router'
import {no_auth_required} from "../middlewares/no_auth_required";

export default function Register() {
no_auth_required();
const { setToken } = useAuth()
const router = useRouter()

Expand Down Expand Up @@ -52,9 +54,11 @@ export default function Register() {
password: password,
}

axios.post(
'auth/register/',
dataForApiRequest,
axios({
url : 'https://todo-app-csoc.herokuapp.com/auth/register/',
method : "post",
data : dataForApiRequest
}
)
.then(function ({ data, status }) {
setToken(data.token)
Expand Down
93 changes: 63 additions & 30 deletions components/TodoListItem.js
Original file line number Diff line number Diff line change
@@ -1,56 +1,89 @@
/* eslint-disable @next/next/no-img-element */
import axios from "axios";
import { useState } from "react";
import { useAuth } from "../context/auth";

export default function TodoListItem() {
export default function TodoListItem(e) {
const [showedit, setShowEdit] = useState(false);
const [updateData, setUpdateData] = useState();
const { token } = useAuth();
const editTask = (id) => {
/**
* @todo Complete this function.
* @todo 1. Update the dom accordingly
*/
setShowEdit(!showedit);

}

const deleteTask = (id) => {
/**
* @todo Complete this function.
* @todo 1. Send the request to delete the task to the backend server.
* @todo 2. Remove the task from the dom.
*/
axios({
url:"https://todo-app-csoc.herokuapp.com/todo/"+id+"/",
headers:{
Authorization: 'Token ' + token
},
method:"DELETE"

}).then((res)=>{
console.log("success")
}).catch((err)=>{
console.log("error")
})

}

const updateTask = (id) => {
/**
* @todo Complete this function.
* @todo 1. Send the request to update the task to the backend server.
* @todo 2. Update the task in the dom.
*/
const dataForUpdate = {
title: updateData
}
if(token){
axios({
url:"https://todo-app-csoc.herokuapp.com/todo/"+id+"/",
headers:{
Authorization: 'Token ' + token
},
data:dataForUpdate,
method:"patch"

}).then((res)=>{
setShowEdit(!showedit)
setUpdateData('')
}).catch((err)=>{
console.log("error")
})
}

}

return (
<>
<li className='border flex border-gray-500 rounded px-2 py-2 justify-between items-center mb-2'>
<input
id='input-button-1'
type='text'
className='hideme appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:ring todo-edit-task-input'
placeholder='Edit The Task'
id={"input-button-"+e.id}
type="text"
className={`${
showedit ? "" : "hideme"
} appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:ring todo-edit-task-input`}
placeholder="Edit The Task"
onChange={(e) => {
setUpdateData(e.target.value);
}}
value={updateData}
/>
<div id='done-button-1' className='hideme'>
<div id={'done-button-'+e.id} className={`${showedit ? "" : "hideme"}`}>
<button
className='bg-transparent hover:bg-gray-500 text-gray-700 text-sm hover:text-white py-2 px-3 border border-gray-500 hover:border-transparent rounded todo-update-task'
type='button'
onClick={updateTask(1)}
onClick={() => updateTask(e.id)}
>
Done

</button>
</div>
<div id='task-1' className='todo-task text-gray-600'>
Sample Task 1
<div id={'task-'+e.id} className='todo-task text-gray-600'>
{e.title}
</div>
<span id='task-actions-1' className=''>
<span id={'task-actions-'+e.id} className={`${!showedit ? "" : "hideme"}`}>
<button
style={{ marginRight: '5px' }}
type='button'
onClick={editTask(1)}
className='bg-transparent hover:bg-yellow-500 hover:text-white border border-yellow-500 hover:border-transparent rounded px-2 py-2'
style={{ marginRight: "5px" }}
type="button"
onClick={() => editTask(e.id)}
className="bg-transparent hover:bg-yellow-500 hover:text-white border border-yellow-500 hover:border-transparent rounded px-2 py-2"
>
<img
src='https://res.cloudinary.com/nishantwrp/image/upload/v1587486663/CSOC/edit.png'
Expand All @@ -62,7 +95,7 @@ export default function TodoListItem() {
<button
type='button'
className='bg-transparent hover:bg-red-500 hover:text-white border border-red-500 hover:border-transparent rounded px-2 py-2'
onClick={deleteTask(1)}
onClick={() => deleteTask (e.id)}
>
<img
src='https://res.cloudinary.com/nishantwrp/image/upload/v1587486661/CSOC/delete.svg'
Expand Down
5 changes: 3 additions & 2 deletions context/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { useEffect, useState, useContext, createContext } from 'react'
import { useCookies } from 'react-cookie'
import axios from '../utils/axios'
import { useRouter } from 'next/router'
import {auth_required} from '../middlewares/auth_required'

const AuthContext = createContext({})

Expand All @@ -11,12 +12,12 @@ export const AuthProvider = ({ children }) => {
const [avatarImage, setAvatarImage] = useState('#')
const [cookies, setCookies, removeCookies] = useCookies(['auth'])
const token = cookies.token

auth_required();
const setToken = (newToken) => setCookies('token', newToken, { path: '/' })
const deleteToken = () => removeCookies('token')
const logout = () => {
deleteToken()
router.push('/login')
router.reload()
}

useEffect(() => {
Expand Down
22 changes: 19 additions & 3 deletions middlewares/auth_required.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
/***
* @todo Redirect the user to login page if token is not present.
*/
import { useEffect} from 'react'

import { useAuth } from '../context/auth'
import { useRouter } from 'next/router'

export function auth_required(){

const { token } = useAuth()

const router = useRouter()

useEffect(()=>{
if(token===undefined){
router.push('/login');
}
},[token])


} ;
21 changes: 18 additions & 3 deletions middlewares/no_auth_required.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,18 @@
/***
* @todo Redirect the user to main page if token is present.
*/
import { useEffect, useState } from 'react'
import { useAuth } from '../context/auth'
import { useRouter } from 'next/router'

export function no_auth_required(){

const { token } = useAuth()

const router = useRouter()

useEffect(()=>{
if(token){
router.push('/');
}
},[token])


};
Loading