├── backend └── to-do-list │ ├── src │ ├── main │ │ ├── resources │ │ │ └── application.properties │ │ └── java │ │ │ └── com │ │ │ └── backend │ │ │ └── todolist │ │ │ ├── errorhandler │ │ │ ├── BadRequestException.java │ │ │ ├── InvalidPageException.java │ │ │ ├── ResourceNotFoundException.java │ │ │ ├── InvalidJwtAuthenticationException.java │ │ │ ├── ResponseEntityBuilder.java │ │ │ ├── CustomException.java │ │ │ └── GlobalExceptionHandler.java │ │ │ ├── auth │ │ │ ├── repository │ │ │ │ └── UserRepository.java │ │ │ ├── controller │ │ │ │ ├── UserSigninResponse.java │ │ │ │ ├── UserSignupResponse.java │ │ │ │ ├── UserSigninRequest.java │ │ │ │ ├── UserSignupRequest.java │ │ │ │ └── UserController.java │ │ │ ├── jwt │ │ │ │ ├── JwtConfigurer.java │ │ │ │ ├── JwtTokenFilter.java │ │ │ │ └── JwtTokenGenerator.java │ │ │ ├── service │ │ │ │ ├── CustomUserDetailsService.java │ │ │ │ └── UserService.java │ │ │ └── model │ │ │ │ └── User.java │ │ │ ├── ToDoListApplication.java │ │ │ ├── controller │ │ │ ├── CountResponse.java │ │ │ ├── TodoCreateRequest.java │ │ │ ├── TodoUpdateRequest.java │ │ │ └── TodoController.java │ │ │ ├── repository │ │ │ ├── TodoPagingRepository.java │ │ │ └── TodoRepository.java │ │ │ ├── config │ │ │ ├── SwaggerConfig.java │ │ │ └── WebSecurityConfiguration.java │ │ │ ├── model │ │ │ └── Todo.java │ │ │ └── service │ │ │ └── TodoService.java │ └── test │ │ └── java │ │ └── com │ │ └── backend │ │ └── todolist │ │ └── ToDoListApplicationTests.java │ ├── Dockerfile │ ├── .mvn │ └── wrapper │ │ ├── maven-wrapper.jar │ │ ├── maven-wrapper.properties │ │ └── MavenWrapperDownloader.java │ ├── .gitignore │ ├── openshift │ └── deployment.yaml │ ├── pom.xml │ ├── mvnw.cmd │ └── mvnw ├── frontend ├── public │ ├── robots.txt │ ├── favicon.ico │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── index.html ├── src │ ├── index.js │ ├── App.css │ ├── components │ │ ├── page │ │ │ ├── NotFound.js │ │ │ ├── About.js │ │ │ └── Landing.js │ │ ├── auth │ │ │ ├── Signout.js │ │ │ ├── Signin.js │ │ │ └── Signup.js │ │ ├── header │ │ │ └── Header.js │ │ └── todo │ │ │ ├── AddTodo.js │ │ │ ├── UpdateTodo.js │ │ │ └── ViewTodos.js │ └── App.js ├── Dockerfile ├── index.js ├── openshift │ └── deployment.yaml └── package.json ├── README.md └── .gitignore /backend/to-do-list/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=3001 2 | -------------------------------------------------------------------------------- /frontend/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /frontend/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alvinsenjaya/to-do-list-spring-boot-react/HEAD/frontend/public/favicon.ico -------------------------------------------------------------------------------- /frontend/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alvinsenjaya/to-do-list-spring-boot-react/HEAD/frontend/public/logo192.png -------------------------------------------------------------------------------- /frontend/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alvinsenjaya/to-do-list-spring-boot-react/HEAD/frontend/public/logo512.png -------------------------------------------------------------------------------- /backend/to-do-list/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM openjdk:11-jre-slim 2 | EXPOSE 3001 3 | COPY target/to-do-list-0.0.1-SNAPSHOT.jar app.jar 4 | ENTRYPOINT ["java","-jar","/app.jar"] -------------------------------------------------------------------------------- /backend/to-do-list/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alvinsenjaya/to-do-list-spring-boot-react/HEAD/backend/to-do-list/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /frontend/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './App'; 4 | 5 | ReactDOM.render(, document.getElementById('root')); 6 | -------------------------------------------------------------------------------- /frontend/Dockerfile: -------------------------------------------------------------------------------- 1 | #FROM nginxinc/nginx-unprivileged:stable 2 | #COPY build /usr/share/nginx/html 3 | 4 | FROM ubuntu 5 | RUN apt-get update 6 | RUN apt-get install nginx -y 7 | COPY build /var/www/html/ 8 | EXPOSE 80 9 | CMD [“nginx”,”-g”,”daemon off;”] -------------------------------------------------------------------------------- /frontend/src/App.css: -------------------------------------------------------------------------------- 1 | tr.completed { 2 | background-color: #c4ffbd 3 | } 4 | 5 | a { 6 | color: rgb(253, 254, 255); 7 | text-decoration: none; 8 | } 9 | a:hover { 10 | color: rgb(159, 159, 255); 11 | text-decoration: none; 12 | } 13 | -------------------------------------------------------------------------------- /frontend/src/components/page/NotFound.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | export default function About() { 4 | return ( 5 |
6 |

Not Found

7 |

Requested page not found

8 |
9 | ) 10 | } -------------------------------------------------------------------------------- /frontend/src/components/page/About.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | export default function About() { 4 | return ( 5 |
6 |

About

7 |

This is todo list app version 1.0.0

8 |
9 | ) 10 | } -------------------------------------------------------------------------------- /backend/to-do-list/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar 3 | -------------------------------------------------------------------------------- /backend/to-do-list/src/test/java/com/backend/todolist/ToDoListApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class ToDoListApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /backend/to-do-list/src/main/java/com/backend/todolist/errorhandler/BadRequestException.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist.errorhandler; 2 | 3 | public class BadRequestException extends RuntimeException { 4 | private static final long serialVersionUID = 1L; 5 | 6 | public BadRequestException(String message) { 7 | super(message); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /backend/to-do-list/src/main/java/com/backend/todolist/errorhandler/InvalidPageException.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist.errorhandler; 2 | 3 | public class InvalidPageException extends RuntimeException { 4 | private static final long serialVersionUID = 1L; 5 | 6 | public InvalidPageException(String message) { 7 | super(message); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /backend/to-do-list/src/main/java/com/backend/todolist/auth/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist.auth.repository; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | 5 | import com.backend.todolist.auth.model.User; 6 | 7 | public interface UserRepository extends JpaRepository { 8 | User findByUsername(String username); 9 | } -------------------------------------------------------------------------------- /backend/to-do-list/src/main/java/com/backend/todolist/errorhandler/ResourceNotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist.errorhandler; 2 | 3 | public class ResourceNotFoundException extends RuntimeException { 4 | private static final long serialVersionUID = 1L; 5 | 6 | public ResourceNotFoundException(String message) { 7 | super(message); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /frontend/index.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const path = require('path'); 3 | const app = express(); 4 | 5 | app.use(express.static(path.join(__dirname, 'build'))); 6 | 7 | app.get('/', function (req, res) { 8 | res.sendFile(path.join(__dirname, 'build', 'index.html')); 9 | }); 10 | 11 | app.listen(3000, () => { 12 | console.log('Listening on port 3000'); 13 | }); -------------------------------------------------------------------------------- /backend/to-do-list/src/main/java/com/backend/todolist/errorhandler/InvalidJwtAuthenticationException.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist.errorhandler; 2 | 3 | public class InvalidJwtAuthenticationException extends RuntimeException { 4 | private static final long serialVersionUID = 1L; 5 | 6 | public InvalidJwtAuthenticationException(String message) { 7 | super(message); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /backend/to-do-list/src/main/java/com/backend/todolist/errorhandler/ResponseEntityBuilder.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist.errorhandler; 2 | 3 | import org.springframework.http.ResponseEntity; 4 | 5 | public class ResponseEntityBuilder { 6 | public static ResponseEntity build(CustomException customException) { 7 | return new ResponseEntity<>(customException, customException.getStatus()); 8 | } 9 | } -------------------------------------------------------------------------------- /backend/to-do-list/src/main/java/com/backend/todolist/ToDoListApplication.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class ToDoListApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(ToDoListApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /backend/to-do-list/src/main/java/com/backend/todolist/controller/CountResponse.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist.controller; 2 | 3 | public class CountResponse { 4 | private long count; 5 | 6 | protected CountResponse() { 7 | 8 | } 9 | 10 | public CountResponse(long count) { 11 | super(); 12 | this.count = count; 13 | } 14 | 15 | public long getCount() { 16 | return count; 17 | } 18 | 19 | public void setCount(long count) { 20 | this.count = count; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /backend/to-do-list/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/**/target/ 5 | !**/src/test/**/target/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | !**/src/main/**/build/ 30 | !**/src/test/**/build/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | -------------------------------------------------------------------------------- /frontend/src/components/auth/Signout.js: -------------------------------------------------------------------------------- 1 | import React, { useEffect } from 'react'; 2 | import { useHistory } from "react-router-dom"; 3 | 4 | function Signout({isAuthenticated, setIsAuthenticated}) { 5 | let history = useHistory(); 6 | 7 | useEffect(() => { 8 | sessionStorage.removeItem('token'); 9 | sessionStorage.removeItem('name'); 10 | setIsAuthenticated(false); 11 | history.push("/"); 12 | }, [history, setIsAuthenticated]) 13 | 14 | return ( 15 |
16 |

Successfully sign out

17 |
18 | ) 19 | } 20 | 21 | export default Signout; -------------------------------------------------------------------------------- /frontend/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /backend/to-do-list/src/main/java/com/backend/todolist/repository/TodoPagingRepository.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist.repository; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.data.domain.Pageable; 6 | import org.springframework.data.repository.PagingAndSortingRepository; 7 | import org.springframework.stereotype.Repository; 8 | 9 | import com.backend.todolist.model.Todo; 10 | 11 | @Repository 12 | public interface TodoPagingRepository extends PagingAndSortingRepository { 13 | List findAllByUsername(String username, Pageable pageable); 14 | List findAllByUsernameAndIsCompleted(String username, boolean isCompleted, Pageable pageable); 15 | } 16 | -------------------------------------------------------------------------------- /frontend/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 14 | ToDoList 15 | 16 | 17 | 18 |
19 | 20 | 21 | -------------------------------------------------------------------------------- /backend/to-do-list/src/main/java/com/backend/todolist/repository/TodoRepository.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist.repository; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.stereotype.Repository; 7 | 8 | import com.backend.todolist.model.Todo; 9 | 10 | @Repository 11 | public interface TodoRepository extends JpaRepository { 12 | List findAllByUsername(String username); 13 | List findAllByUsernameAndIsCompleted(String username, boolean isCompleted); 14 | 15 | Todo findByUsernameAndId(String username, long Id); 16 | 17 | Long countByUsername(String username); 18 | Long countByUsernameAndIsCompleted(String username, boolean isCompleted); 19 | } 20 | -------------------------------------------------------------------------------- /backend/to-do-list/src/main/java/com/backend/todolist/auth/controller/UserSigninResponse.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist.auth.controller; 2 | 3 | public class UserSigninResponse { 4 | private String username; 5 | private String token; 6 | 7 | protected UserSigninResponse() { 8 | 9 | } 10 | 11 | public UserSigninResponse(String username, String token) { 12 | super(); 13 | this.username = username; 14 | this.token = token; 15 | } 16 | 17 | public String getUsername() { 18 | return username; 19 | } 20 | 21 | public void setUsername(String username) { 22 | this.username = username; 23 | } 24 | 25 | public String getToken() { 26 | return token; 27 | } 28 | 29 | public void setToken(String token) { 30 | this.token = token; 31 | } 32 | 33 | 34 | } 35 | -------------------------------------------------------------------------------- /backend/to-do-list/src/main/java/com/backend/todolist/auth/controller/UserSignupResponse.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist.auth.controller; 2 | 3 | public class UserSignupResponse { 4 | private String username; 5 | private String token; 6 | 7 | protected UserSignupResponse() { 8 | 9 | } 10 | 11 | public UserSignupResponse(String username, String token) { 12 | super(); 13 | this.username = username; 14 | this.token = token; 15 | } 16 | 17 | public String getUsername() { 18 | return username; 19 | } 20 | 21 | public void setUsername(String username) { 22 | this.username = username; 23 | } 24 | 25 | public String getToken() { 26 | return token; 27 | } 28 | 29 | public void setToken(String token) { 30 | this.token = token; 31 | } 32 | 33 | 34 | } 35 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ToDoList App 2 | 3 | ### Overview 4 | Todo list application that can create, read, update, delete, and mark completed. This application also implement filtering and pagination. Front end is developed using react and backend is developed using spring boot. 5 | 6 | ### How to Run Application 7 | 8 | 1. Install node to run react app (frontend) and maven to run spring boot app (backend). 9 | 2. In /frontend directory, run the application 10 | 11 | `cd /frontend` 12 | 13 | `npm run production` 14 | 15 | 3. in /backend/to-do-list directory, run spring boot aplication using maven 16 | 17 | `cd /backend/to-do-list` 18 | 19 | `mvn spring-boot:run` 20 | 21 | 4. Open your browser and browse to http://localhost:3000 22 | 23 | ### Snapshot of Application 24 | 25 | ![ToDoList App](https://i.imgur.com/7bjdoTW.png) 26 | -------------------------------------------------------------------------------- /backend/to-do-list/src/main/java/com/backend/todolist/auth/controller/UserSigninRequest.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist.auth.controller; 2 | 3 | public class UserSigninRequest { 4 | private String username; 5 | 6 | private String password; 7 | 8 | protected UserSigninRequest() { 9 | 10 | } 11 | 12 | public UserSigninRequest(String username, String password) { 13 | super(); 14 | this.username = username; 15 | this.password = password; 16 | } 17 | 18 | public String getUsername() { 19 | return username; 20 | } 21 | 22 | public String getPassword() { 23 | return password; 24 | } 25 | 26 | public void setUsername(String username) { 27 | this.username = username; 28 | } 29 | 30 | public void setPassword(String password) { 31 | this.password = password; 32 | } 33 | 34 | 35 | } 36 | -------------------------------------------------------------------------------- /frontend/openshift/deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | name: todolist-frontend-deployment 5 | labels: 6 | app: todolist-frontend 7 | spec: 8 | selector: 9 | matchLabels: 10 | app: todolist-frontend 11 | template: 12 | metadata: 13 | labels: 14 | app: todolist-frontend 15 | spec: 16 | containers: 17 | - name: todolist-frontend-container 18 | image: localhost:5000/todolist-frontend:0.0.1-SNAPSHOT-dev 19 | ports: 20 | - containerPort: 80 21 | --- 22 | apiVersion: v1 23 | kind: Service 24 | metadata: 25 | name: todolist-frontend-service 26 | spec: 27 | selector: 28 | app: todolist-frontend 29 | ports: 30 | - protocol: TCP 31 | port: 80 32 | --- 33 | apiVersion: v1 34 | kind: Route 35 | metadata: 36 | name: todolist-frontend-route 37 | spec: 38 | to: 39 | kind: Service 40 | name: todolist-frontend-service 41 | -------------------------------------------------------------------------------- /backend/to-do-list/openshift/deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | name: todolist-backend-deployment 5 | labels: 6 | app: todolist-backend 7 | spec: 8 | selector: 9 | matchLabels: 10 | app: todolist-backend 11 | template: 12 | metadata: 13 | labels: 14 | app: todolist-backend 15 | spec: 16 | containers: 17 | - name: todolist-backend-container 18 | image: localhost:5000/todolist-backend:0.0.1-SNAPSHOT-dev 19 | ports: 20 | - containerPort: 3001 21 | --- 22 | apiVersion: v1 23 | kind: Service 24 | metadata: 25 | name: todolist-backend-service 26 | spec: 27 | selector: 28 | app: todolist-backend 29 | ports: 30 | - protocol: TCP 31 | port: 3001 32 | --- 33 | apiVersion: v1 34 | kind: Route 35 | metadata: 36 | name: todolist-backend-route 37 | spec: 38 | to: 39 | kind: Service 40 | name: todolist-backend-service 41 | -------------------------------------------------------------------------------- /backend/to-do-list/src/main/java/com/backend/todolist/controller/TodoCreateRequest.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist.controller; 2 | 3 | import java.util.Date; 4 | 5 | import javax.validation.constraints.NotEmpty; 6 | import javax.validation.constraints.NotNull; 7 | 8 | public class TodoCreateRequest { 9 | @NotEmpty(message = "Title is required") 10 | private String title; 11 | 12 | @NotNull(message = "Target date is required") 13 | private Date targetDate; 14 | 15 | protected TodoCreateRequest() { 16 | 17 | } 18 | 19 | public TodoCreateRequest(String title, Date targetDate) { 20 | super(); 21 | this.title = title; 22 | this.targetDate = targetDate; 23 | } 24 | 25 | public String getTitle() { 26 | return title; 27 | } 28 | 29 | public void setTitle(String title) { 30 | this.title = title; 31 | } 32 | 33 | public Date getTargetDate() { 34 | return targetDate; 35 | } 36 | 37 | public void setTargetDate(Date targetDate) { 38 | this.targetDate = targetDate; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /backend/to-do-list/src/main/java/com/backend/todolist/controller/TodoUpdateRequest.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist.controller; 2 | 3 | import java.util.Date; 4 | 5 | import javax.validation.constraints.NotEmpty; 6 | import javax.validation.constraints.NotNull; 7 | 8 | public class TodoUpdateRequest { 9 | @NotEmpty(message = "Title is required") 10 | private String title; 11 | 12 | @NotNull(message = "Target date is required") 13 | private Date targetDate; 14 | 15 | protected TodoUpdateRequest() { 16 | 17 | } 18 | 19 | public TodoUpdateRequest(String title, Date targetDate) { 20 | super(); 21 | this.title = title; 22 | this.targetDate = targetDate; 23 | } 24 | 25 | public String getTitle() { 26 | return title; 27 | } 28 | 29 | public void setTitle(String title) { 30 | this.title = title; 31 | } 32 | 33 | public Date getTargetDate() { 34 | return targetDate; 35 | } 36 | 37 | public void setTargetDate(Date targetDate) { 38 | this.targetDate = targetDate; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # dependencies 2 | **/node_modules 3 | **/.pnp 4 | .pnp.js 5 | 6 | # testing 7 | **/coverage 8 | 9 | # production 10 | **/build 11 | 12 | # misc 13 | .DS_Store 14 | .env.local 15 | .env.development.local 16 | .env.test.local 17 | .env.production.local 18 | 19 | npm-debug.log* 20 | yarn-debug.log* 21 | yarn-error.log* 22 | 23 | 24 | # Compiled class file 25 | *.class 26 | 27 | # Log file 28 | *.log 29 | 30 | # BlueJ files 31 | *.ctxt 32 | 33 | # Mobile Tools for Java (J2ME) 34 | .mtj.tmp/ 35 | 36 | # Package Files # 37 | *.jar 38 | *.war 39 | *.nar 40 | *.ear 41 | *.zip 42 | *.tar.gz 43 | *.rar 44 | 45 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 46 | hs_err_pid* 47 | 48 | target/ 49 | pom.xml.tag 50 | pom.xml.releaseBackup 51 | pom.xml.versionsBackup 52 | pom.xml.next 53 | release.properties 54 | dependency-reduced-pom.xml 55 | buildNumber.properties 56 | .mvn/timing.properties 57 | # https://github.com/takari/maven-wrapper#usage-without-binary-jar 58 | .mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /backend/to-do-list/src/main/java/com/backend/todolist/auth/jwt/JwtConfigurer.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist.auth.jwt; 2 | 3 | import org.springframework.security.config.annotation.SecurityConfigurerAdapter; 4 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 5 | import org.springframework.security.web.DefaultSecurityFilterChain; 6 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 7 | 8 | public class JwtConfigurer extends SecurityConfigurerAdapter { 9 | private JwtTokenGenerator jwtTokenGenerator; 10 | 11 | public JwtConfigurer(JwtTokenGenerator jwtTokenGenerator) { 12 | this.jwtTokenGenerator = jwtTokenGenerator; 13 | } 14 | 15 | @Override 16 | public void configure(HttpSecurity httpSecurity) throws Exception { 17 | JwtTokenFilter customFilter = new JwtTokenFilter(jwtTokenGenerator); 18 | httpSecurity.addFilterBefore(customFilter, UsernamePasswordAuthenticationFilter.class); 19 | } 20 | } -------------------------------------------------------------------------------- /backend/to-do-list/src/main/java/com/backend/todolist/auth/controller/UserSignupRequest.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist.auth.controller; 2 | 3 | import javax.validation.constraints.NotEmpty; 4 | import javax.validation.constraints.Size; 5 | 6 | public class UserSignupRequest { 7 | @NotEmpty(message = "Username is required") 8 | private String username; 9 | 10 | @NotEmpty(message = "Password is required") 11 | @Size(min=8, message = "Password length should be 8 characters or more") 12 | private String password; 13 | 14 | protected UserSignupRequest() { 15 | 16 | } 17 | 18 | public UserSignupRequest(String username, String password) { 19 | super(); 20 | this.username = username; 21 | this.password = password; 22 | } 23 | 24 | public String getUsername() { 25 | return username; 26 | } 27 | 28 | public String getPassword() { 29 | return password; 30 | } 31 | 32 | public void setUsername(String username) { 33 | this.username = username; 34 | } 35 | 36 | public void setPassword(String password) { 37 | this.password = password; 38 | } 39 | 40 | 41 | } 42 | -------------------------------------------------------------------------------- /frontend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "frontend", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@testing-library/jest-dom": "^5.11.5", 7 | "@testing-library/react": "^11.1.1", 8 | "@testing-library/user-event": "^12.2.0", 9 | "axios": "^0.21.0", 10 | "formik": "^2.2.5", 11 | "moment": "^2.29.1", 12 | "react": "^17.0.1", 13 | "react-dom": "^17.0.1", 14 | "react-router-dom": "^5.2.0", 15 | "react-scripts": "4.0.0", 16 | "uuid": "^8.3.1", 17 | "web-vitals": "^0.2.4" 18 | }, 19 | "scripts": { 20 | "start": "react-scripts start", 21 | "production": "node index.js", 22 | "build": "react-scripts build", 23 | "test": "react-scripts test", 24 | "eject": "react-scripts eject" 25 | }, 26 | "eslintConfig": { 27 | "extends": [ 28 | "react-app", 29 | "react-app/jest" 30 | ] 31 | }, 32 | "browserslist": { 33 | "production": [ 34 | ">0.2%", 35 | "not dead", 36 | "not op_mini all" 37 | ], 38 | "development": [ 39 | "last 1 chrome version", 40 | "last 1 firefox version", 41 | "last 1 safari version" 42 | ] 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /frontend/src/components/header/Header.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { Link } from 'react-router-dom'; 3 | 4 | function Header({isAuthenticated, setIsAuthenticated}) { 5 | return ( 6 |
7 | 19 |
20 | ) 21 | } 22 | 23 | export default Header; -------------------------------------------------------------------------------- /backend/to-do-list/src/main/java/com/backend/todolist/errorhandler/CustomException.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist.errorhandler; 2 | 3 | import java.time.LocalDateTime; 4 | 5 | import org.springframework.http.HttpStatus; 6 | 7 | import com.fasterxml.jackson.annotation.JsonFormat; 8 | 9 | public class CustomException { 10 | @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss") 11 | private LocalDateTime timestamp; 12 | private HttpStatus status; 13 | private String message; 14 | 15 | public CustomException(LocalDateTime timestamp, HttpStatus status, String message) { 16 | this.timestamp = timestamp; 17 | this.status = status; 18 | this.message = message; 19 | } 20 | 21 | public LocalDateTime getTimestamp() { 22 | return timestamp; 23 | } 24 | public HttpStatus getStatus() { 25 | return status; 26 | } 27 | public String getMessage() { 28 | return message; 29 | } 30 | public void setTimestamp(LocalDateTime timestamp) { 31 | this.timestamp = timestamp; 32 | } 33 | public void setStatus(HttpStatus status) { 34 | this.status = status; 35 | } 36 | public void setMessage(String message) { 37 | this.message = message; 38 | } 39 | 40 | @Override 41 | public String toString() { 42 | return "CustomException [timestamp=" + timestamp + ", status=" + status + ", message=" + message + "]"; 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /backend/to-do-list/src/main/java/com/backend/todolist/auth/service/CustomUserDetailsService.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist.auth.service; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import org.springframework.security.core.GrantedAuthority; 7 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 8 | import org.springframework.security.core.userdetails.UserDetails; 9 | import org.springframework.security.core.userdetails.UserDetailsService; 10 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 11 | import org.springframework.stereotype.Component; 12 | 13 | import com.backend.todolist.auth.model.User; 14 | import com.backend.todolist.auth.repository.UserRepository; 15 | 16 | @Component 17 | public class CustomUserDetailsService implements UserDetailsService { 18 | private UserRepository userRepository; 19 | 20 | public CustomUserDetailsService(UserRepository userRepository) { 21 | this.userRepository = userRepository; 22 | } 23 | 24 | @Override 25 | public UserDetails loadUserByUsername(String username) { 26 | User user = userRepository.findByUsername(username); 27 | if (user == null) throw new UsernameNotFoundException("Expired or invalid JWT token"); 28 | 29 | List grantedAuthorities = new ArrayList<>(); 30 | for (String role : user.getRoleAsList()){ 31 | grantedAuthorities.add(new SimpleGrantedAuthority(role)); 32 | } 33 | 34 | return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), grantedAuthorities); 35 | } 36 | } -------------------------------------------------------------------------------- /backend/to-do-list/src/main/java/com/backend/todolist/config/SwaggerConfig.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist.config; 2 | 3 | import java.security.Principal; 4 | import java.util.Collections; 5 | import java.util.List; 6 | 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | 10 | import springfox.documentation.builders.ParameterBuilder; 11 | import springfox.documentation.builders.RequestHandlerSelectors; 12 | import springfox.documentation.schema.ModelRef; 13 | import springfox.documentation.service.Parameter; 14 | import springfox.documentation.spi.DocumentationType; 15 | import springfox.documentation.spring.web.plugins.Docket; 16 | import springfox.documentation.swagger2.annotations.EnableSwagger2; 17 | 18 | @Configuration 19 | @EnableSwagger2 20 | public class SwaggerConfig { 21 | 22 | @Bean 23 | public Docket todoApi() { 24 | return new Docket(DocumentationType.SWAGGER_2) 25 | .forCodeGeneration(true) 26 | .ignoredParameterTypes(Principal.class) 27 | .globalOperationParameters(globalParameterList()) 28 | .select() 29 | .apis(RequestHandlerSelectors.basePackage("com.backend.todolist")) 30 | .build(); 31 | } 32 | 33 | private List globalParameterList() { 34 | Parameter authTokenHeader = 35 | new ParameterBuilder() 36 | .name("Authorization") // name of the header 37 | .modelRef(new ModelRef("string")) 38 | .required(false) 39 | .parameterType("header") 40 | .description("Bearer ") 41 | .build(); 42 | 43 | return Collections.singletonList(authTokenHeader); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /backend/to-do-list/src/main/java/com/backend/todolist/auth/model/User.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist.auth.model; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | import javax.persistence.Column; 7 | import javax.persistence.Entity; 8 | import javax.persistence.GeneratedValue; 9 | import javax.persistence.Id; 10 | import javax.validation.constraints.NotEmpty; 11 | 12 | @Entity 13 | public class User { 14 | @Id 15 | @GeneratedValue 16 | private Long id; 17 | 18 | @NotEmpty(message = "Username is required") 19 | @Column(unique = true) 20 | private String username; 21 | 22 | @NotEmpty(message = "Password is required") 23 | private String password; 24 | 25 | private String role; 26 | 27 | protected User() { 28 | 29 | } 30 | 31 | public User(String username, String password) { 32 | super(); 33 | this.username = username; 34 | this.password = password; 35 | this.role = "User"; 36 | } 37 | 38 | public Long getId() { 39 | return id; 40 | } 41 | 42 | public void setId(Long id) { 43 | this.id = id; 44 | } 45 | 46 | public String getUsername() { 47 | return username; 48 | } 49 | 50 | public void setUsername(String username) { 51 | this.username = username; 52 | } 53 | 54 | public String getPassword() { 55 | return password; 56 | } 57 | 58 | public void setPassword(String password) { 59 | this.password = password; 60 | } 61 | 62 | public List getRoleAsList() { 63 | return Arrays.asList(this.role); 64 | } 65 | 66 | public String getRole() { 67 | return role; 68 | } 69 | 70 | public void setRoles(String role) { 71 | this.role = role; 72 | } 73 | } -------------------------------------------------------------------------------- /backend/to-do-list/src/main/java/com/backend/todolist/model/Todo.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist.model; 2 | 3 | import java.util.Date; 4 | 5 | import javax.persistence.Entity; 6 | import javax.persistence.GeneratedValue; 7 | import javax.persistence.Id; 8 | import javax.validation.constraints.NotEmpty; 9 | import javax.validation.constraints.NotNull; 10 | 11 | @Entity 12 | public class Todo { 13 | 14 | @Id 15 | @GeneratedValue 16 | private long id; 17 | 18 | @NotEmpty(message = "Title is required") 19 | private String title; 20 | 21 | @NotNull(message = "Target date is required") 22 | private Date targetDate; 23 | 24 | private String username; 25 | 26 | private boolean isCompleted; 27 | 28 | protected Todo() { 29 | 30 | } 31 | 32 | public Todo(String title, Date targetDate, String username) { 33 | super(); 34 | this.title = title; 35 | this.targetDate = targetDate; 36 | this.username = username; 37 | this.isCompleted = false; 38 | } 39 | 40 | public long getId() { 41 | return id; 42 | } 43 | 44 | public void setIdd(long id) { 45 | this.id = id; 46 | } 47 | 48 | public String getUsername() { 49 | return username; 50 | } 51 | 52 | public void setUsername(String username) { 53 | this.username = username; 54 | } 55 | 56 | public String getTitle() { 57 | return title; 58 | } 59 | 60 | public void setTitle(String title) { 61 | this.title = title; 62 | } 63 | 64 | public Date getTargetDate() { 65 | return targetDate; 66 | } 67 | 68 | public void setTargetDate(Date targetDate) { 69 | this.targetDate = targetDate; 70 | } 71 | 72 | public boolean getIsCompleted() { 73 | return isCompleted; 74 | } 75 | 76 | public void setIsCompleted(boolean isCompleted) { 77 | this.isCompleted = isCompleted; 78 | } 79 | 80 | @Override 81 | public String toString() { 82 | return "Todo [id=" + id + ", title=" + title + ", targetDate=" + targetDate + ", username=" + username 83 | + ", isCompleted=" + isCompleted + "]"; 84 | } 85 | 86 | } 87 | -------------------------------------------------------------------------------- /backend/to-do-list/src/main/java/com/backend/todolist/auth/jwt/JwtTokenFilter.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist.auth.jwt; 2 | 3 | import java.io.IOException; 4 | import java.time.LocalDateTime; 5 | 6 | import javax.servlet.FilterChain; 7 | import javax.servlet.ServletException; 8 | import javax.servlet.ServletRequest; 9 | import javax.servlet.ServletResponse; 10 | import javax.servlet.http.HttpServletRequest; 11 | import javax.servlet.http.HttpServletResponse; 12 | 13 | import org.springframework.http.HttpStatus; 14 | import org.springframework.security.core.Authentication; 15 | import org.springframework.security.core.context.SecurityContextHolder; 16 | import org.springframework.web.filter.GenericFilterBean; 17 | 18 | import com.backend.todolist.errorhandler.CustomException; 19 | import com.fasterxml.jackson.databind.ObjectMapper; 20 | 21 | public class JwtTokenFilter extends GenericFilterBean { 22 | private JwtTokenGenerator jwtTokenGenerator; 23 | 24 | public JwtTokenFilter(JwtTokenGenerator jwtTokenGenerator) { 25 | this.jwtTokenGenerator = jwtTokenGenerator; 26 | } 27 | 28 | @Override 29 | public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException { 30 | try { 31 | String token = jwtTokenGenerator.resolveToken((HttpServletRequest) req); 32 | if (token != null && jwtTokenGenerator.validateToken(token)) { 33 | Authentication auth = jwtTokenGenerator.getAuthentication(token); 34 | SecurityContextHolder.getContext().setAuthentication(auth); 35 | } 36 | filterChain.doFilter(req, res); 37 | } catch (Exception ex) { 38 | sendErrorResponse(HttpStatus.BAD_REQUEST, (HttpServletResponse) res, ex); 39 | } 40 | 41 | } 42 | 43 | public void sendErrorResponse(HttpStatus status, HttpServletResponse response, Exception ex){ 44 | response.setStatus(status.value()); 45 | response.setContentType("application/json"); 46 | 47 | CustomException customException = new CustomException(LocalDateTime.now(), status, ex.getMessage()); 48 | 49 | try { 50 | response.getWriter().write(new ObjectMapper().writeValueAsString(customException)); 51 | } catch (IOException e) { 52 | 53 | } 54 | } 55 | } -------------------------------------------------------------------------------- /backend/to-do-list/src/main/java/com/backend/todolist/config/WebSecurityConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist.config; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.security.authentication.AuthenticationManager; 6 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 7 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 8 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 9 | import org.springframework.security.config.http.SessionCreationPolicy; 10 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 11 | 12 | import com.backend.todolist.auth.jwt.JwtConfigurer; 13 | import com.backend.todolist.auth.jwt.JwtTokenGenerator; 14 | 15 | @EnableWebSecurity 16 | public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { 17 | @Bean 18 | public BCryptPasswordEncoder passwordEncoder() { 19 | return new BCryptPasswordEncoder(); 20 | } 21 | 22 | private static final String[] AUTH_WHITELIST = { 23 | "/v2/api-docs", 24 | "/swagger-resources", 25 | "/swagger-resources/**", 26 | "/configuration/ui", 27 | "/configuration/security", 28 | "/swagger-ui.html", 29 | "/webjars/**" 30 | }; 31 | 32 | @Autowired 33 | JwtTokenGenerator jwtTokenGenerator; 34 | 35 | @Bean 36 | @Override 37 | public AuthenticationManager authenticationManagerBean() throws Exception { 38 | return super.authenticationManagerBean(); 39 | } 40 | 41 | @Override 42 | protected void configure(HttpSecurity httpSecurity) throws Exception { 43 | httpSecurity 44 | .httpBasic().disable() 45 | .cors().and() 46 | .csrf().disable() 47 | .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) 48 | .and() 49 | .authorizeRequests() 50 | .antMatchers(AUTH_WHITELIST).permitAll() 51 | .antMatchers("/api/auth/signin").permitAll() 52 | .antMatchers("/api/auth/signup").permitAll() 53 | .antMatchers("/api/todo/**/**").authenticated() 54 | .antMatchers("/api/todo/**").authenticated() 55 | .anyRequest().authenticated() 56 | .and() 57 | .apply(new JwtConfigurer(jwtTokenGenerator)); 58 | } 59 | } -------------------------------------------------------------------------------- /frontend/src/App.js: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useState } from 'react'; 2 | import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; 3 | 4 | import Header from './components/header/Header'; 5 | import About from './components/page/About'; 6 | import Todos from './components/todo/ViewTodos' 7 | import AddTodo from './components/todo/AddTodo'; 8 | import UpdateTodo from './components/todo/UpdateTodo'; 9 | import Signin from './components/auth/Signin'; 10 | import Signup from './components/auth/Signup'; 11 | import Signout from './components/auth/Signout'; 12 | import Landing from './components/page/Landing'; 13 | import NotFound from './components/page/NotFound'; 14 | 15 | import './bootstrap.min.css'; 16 | import './App.css'; 17 | 18 | function App () { 19 | const [isAuthenticated, setIsAuthenticated] = useState(false); 20 | 21 | useEffect(() => { 22 | if(sessionStorage.getItem('token') !== null){ 23 | setIsAuthenticated(true); 24 | } 25 | }, []) 26 | 27 | return ( 28 | 29 |
30 |
31 |
32 | 33 | ()} /> 34 | ()} /> 35 | ()} /> 36 | ()} /> 37 | ()} /> 38 | ()} /> 39 | ()} /> 40 | 41 | 42 | 43 |
44 |
45 |
46 | ); 47 | } 48 | 49 | export default App; 50 | -------------------------------------------------------------------------------- /frontend/src/components/page/Landing.js: -------------------------------------------------------------------------------- 1 | import axios from 'axios'; 2 | import React, { useEffect, useState } from 'react'; 3 | 4 | export default function Landing({isAuthenticated, setIsAuthenticated}) { 5 | const [message, setMessage] = useState('') 6 | const [numberAllTodoNotCompleted, setNumberAllTodoNotCompleted] = useState(0); 7 | const [numberAllTodo, setNumberAllTodo] = useState(0); 8 | const [errorMessage, setErrorMessage] = useState(''); 9 | 10 | const showErrorMessage = () => { 11 | if(errorMessage === ''){ 12 | return
13 | } 14 | 15 | return
16 | {errorMessage} 17 |
18 | } 19 | 20 | useEffect(() => { 21 | async function getAndSetNumberAllTodo() { 22 | try{ 23 | const response = await axios.get('http://localhost:3001/api/todo/count', { 24 | headers: { 25 | 'Authorization': `Bearer ${sessionStorage.getItem('token')}`, 26 | } 27 | }); 28 | setNumberAllTodo(response.data.count); 29 | } catch (error) { 30 | setMessage(''); 31 | if (error.response) { 32 | setErrorMessage(error.response.data.message); 33 | } else { 34 | setErrorMessage('Error: something happened'); 35 | } 36 | } 37 | } 38 | 39 | async function getAndSetNumberAllTodoNotCompleted() { 40 | try{ 41 | const response = await axios.get('http://localhost:3001/api/todo/count?isCompleted=false', { 42 | headers: { 43 | 'Authorization': `Bearer ${sessionStorage.getItem('token')}`, 44 | } 45 | }); 46 | 47 | setNumberAllTodoNotCompleted(response.data.count); 48 | } catch (error) { 49 | setMessage(''); 50 | if (error.response) { 51 | setErrorMessage(error.response.data.message); 52 | } else { 53 | setErrorMessage('Error: something happened'); 54 | } 55 | } 56 | 57 | } 58 | if(isAuthenticated){ 59 | getAndSetNumberAllTodo(); 60 | getAndSetNumberAllTodoNotCompleted(); 61 | setMessage(`Welcome, ${sessionStorage.getItem('name')}. You have ${numberAllTodoNotCompleted} todo not completed out of ${numberAllTodo} todo.`); 62 | } else { 63 | setMessage('Please sign in to continue'); 64 | } 65 | }, [isAuthenticated, numberAllTodo, numberAllTodoNotCompleted]) 66 | 67 | return ( 68 |
69 |

Todo List Application

70 | {showErrorMessage()} 71 | {message} 72 |
73 | ) 74 | } -------------------------------------------------------------------------------- /backend/to-do-list/src/main/java/com/backend/todolist/auth/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist.auth.controller; 2 | 3 | import javax.validation.Valid; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.http.HttpStatus; 7 | import org.springframework.http.ResponseEntity; 8 | import org.springframework.security.authentication.AuthenticationManager; 9 | import org.springframework.security.crypto.password.PasswordEncoder; 10 | import org.springframework.web.bind.annotation.CrossOrigin; 11 | import org.springframework.web.bind.annotation.RequestBody; 12 | import org.springframework.web.bind.annotation.RequestMapping; 13 | import org.springframework.web.bind.annotation.RequestMethod; 14 | import org.springframework.web.bind.annotation.ResponseStatus; 15 | import org.springframework.web.bind.annotation.RestController; 16 | 17 | import com.backend.todolist.auth.jwt.JwtTokenGenerator; 18 | import com.backend.todolist.auth.repository.UserRepository; 19 | import com.backend.todolist.auth.service.UserService; 20 | import com.backend.todolist.errorhandler.CustomException; 21 | 22 | import io.swagger.annotations.ApiResponse; 23 | import io.swagger.annotations.ApiResponses; 24 | 25 | @RestController 26 | @CrossOrigin(origins = "*", allowCredentials = "true") 27 | @ApiResponses(value = { 28 | @ApiResponse(code=400, message = "Bad Request", response = CustomException.class), 29 | @ApiResponse(code=401, message = "Unauthorized", response = CustomException.class), 30 | @ApiResponse(code=403, message = "Forbidden", response = CustomException.class), 31 | @ApiResponse(code=404, message = "Not Found", response = CustomException.class) 32 | }) 33 | public class UserController { 34 | @Autowired 35 | AuthenticationManager authenticationManager; 36 | 37 | @Autowired 38 | PasswordEncoder passwordEncoder; 39 | 40 | @Autowired 41 | JwtTokenGenerator jwtTokenGenerator; 42 | 43 | @Autowired 44 | UserRepository userRepository; 45 | 46 | @Autowired 47 | UserService userService; 48 | 49 | @ResponseStatus(code = HttpStatus.OK) 50 | @RequestMapping(value = "/api/auth/signin", method = RequestMethod.POST) 51 | public ResponseEntity signin(@Valid @RequestBody UserSigninRequest userSigninRequest) { 52 | return new ResponseEntity<>(userService.signin(userSigninRequest), HttpStatus.OK); 53 | } 54 | 55 | @ResponseStatus(code = HttpStatus.OK) 56 | @RequestMapping(value = "/api/auth/signup", method = RequestMethod.POST) 57 | public ResponseEntity signup(@Valid @RequestBody UserSignupRequest userSignupRequest) { 58 | return new ResponseEntity<>(userService.signup(userSignupRequest), HttpStatus.OK); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /frontend/src/components/todo/AddTodo.js: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useState } from 'react'; 2 | import axios from 'axios'; 3 | import { useHistory } from "react-router-dom"; 4 | 5 | function AddTodo({isAuthenticated, setIsAuthenticated}) { 6 | const [title, setTitle] = useState(''); 7 | const [targetDate, setTargetDate] = useState(''); 8 | const [message, setMessage] = useState(''); 9 | const [errorMessage, setErrorMessage] = useState(''); 10 | let history = useHistory(); 11 | 12 | useEffect(() => { 13 | if(!isAuthenticated){ 14 | history.push("/"); 15 | } 16 | }, [isAuthenticated, history]) 17 | 18 | const onSubmit = async (e) => { 19 | e.preventDefault(); 20 | 21 | try { 22 | await axios.post('http://localhost:3001/api/todo', {title, targetDate}, { 23 | headers: { 24 | 'Authorization': `Bearer ${sessionStorage.getItem('token')}`, 25 | } 26 | }) 27 | } catch(error){ 28 | setMessage(''); 29 | if (error.response) { 30 | setErrorMessage(error.response.data.message); 31 | } else { 32 | setErrorMessage('Error: something happened'); 33 | } 34 | return; 35 | } 36 | 37 | setTitle(''); 38 | setTargetDate(''); 39 | setErrorMessage(''); 40 | setMessage('Todo successfully created'); 41 | } 42 | 43 | useEffect(() => { 44 | setMessage('') 45 | }, [title, targetDate]) 46 | 47 | const showMessage = () => { 48 | if(message === ''){ 49 | return
50 | } 51 | return
52 | {message} 53 |
54 | } 55 | 56 | const showErrorMessage = () => { 57 | if(errorMessage === ''){ 58 | return
59 | } 60 | 61 | return
62 | {errorMessage} 63 |
64 | } 65 | 66 | return ( 67 |
68 |
69 |

Add New Todo

70 |
71 | 72 | setTitle(e.target.value)} 75 | placeholder="Title" 76 | className="form-control"> 77 | 78 |
79 |
80 | 81 | setTargetDate(e.target.value)} 85 | className="form-control"> 86 | 87 |
88 | 89 |
90 | {showMessage()} 91 | {showErrorMessage()} 92 |
93 | ) 94 | } 95 | 96 | export default AddTodo; -------------------------------------------------------------------------------- /frontend/src/components/auth/Signin.js: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useState } from 'react'; 2 | import axios from 'axios'; 3 | import { useHistory } from "react-router-dom"; 4 | 5 | function Signin({isAuthenticated, setIsAuthenticated}) { 6 | const [username, setUsername] = useState(''); 7 | const [password, setPassword] = useState(''); 8 | const [message, setMessage] = useState(''); 9 | const [errorMessage, setErrorMessage] = useState(''); 10 | let history = useHistory(); 11 | 12 | function timeout(delay) { 13 | return new Promise( res => setTimeout(res, delay) ); 14 | } 15 | 16 | const onSubmit = async (e) => { 17 | e.preventDefault(); 18 | 19 | try { 20 | const response = await axios.post('http://localhost:3001/api/auth/signin', {username, password}); 21 | sessionStorage.setItem('token', response.data.token); 22 | sessionStorage.setItem('name', response.data.username); 23 | setIsAuthenticated(true); 24 | } catch(error){ 25 | setMessage(''); 26 | if (error.response) { 27 | setErrorMessage(error.response.data.message); 28 | } else { 29 | setErrorMessage('Error: something happened'); 30 | } 31 | setIsAuthenticated(false); 32 | return; 33 | } 34 | 35 | setUsername(''); 36 | setPassword(''); 37 | setErrorMessage(''); 38 | setMessage('Sign in successful'); 39 | await timeout(1000); 40 | history.push("/"); 41 | } 42 | 43 | useEffect(() => { 44 | setMessage('') 45 | }, [username, password]) 46 | 47 | const showMessage = () => { 48 | if(message === ''){ 49 | return
50 | } 51 | return
52 | {message} 53 |
54 | } 55 | 56 | const showErrorMessage = () => { 57 | if(errorMessage === ''){ 58 | return
59 | } 60 | 61 | return
62 | {errorMessage} 63 |
64 | } 65 | 66 | return ( 67 |
68 |
69 |

Sign In

70 |
71 | 72 | setUsername(e.target.value)} 75 | placeholder="Username" 76 | className="form-control"> 77 | 78 |
79 |
80 | 81 | setPassword(e.target.value)} 85 | placeholder="Password" 86 | className="form-control"> 87 | 88 |
89 | 90 |
91 | {showMessage()} 92 | {showErrorMessage()} 93 |
94 | ) 95 | } 96 | 97 | export default Signin; -------------------------------------------------------------------------------- /frontend/src/components/auth/Signup.js: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useState } from 'react'; 2 | import axios from 'axios'; 3 | import { useHistory } from "react-router-dom"; 4 | 5 | function Signup({isAuthenticated, setIsAuthenticated}) { 6 | const [username, setUsername] = useState(''); 7 | const [password, setPassword] = useState(''); 8 | const [message, setMessage] = useState(''); 9 | const [errorMessage, setErrorMessage] = useState(''); 10 | let history = useHistory(); 11 | 12 | function timeout(delay) { 13 | return new Promise( res => setTimeout(res, delay) ); 14 | } 15 | 16 | const onSubmit = async (e) => { 17 | e.preventDefault(); 18 | 19 | try { 20 | const response = await axios.post('http://localhost:3001/api/auth/signup', {username, password}); 21 | sessionStorage.setItem('token', response.data.token); 22 | sessionStorage.setItem('name', response.data.username); 23 | setIsAuthenticated(true); 24 | } catch(error){ 25 | setMessage(''); 26 | if (error.response) { 27 | setErrorMessage(error.response.data.message); 28 | } else { 29 | setErrorMessage('Error: something happened'); 30 | } 31 | setIsAuthenticated(false); 32 | return; 33 | } 34 | 35 | setUsername(''); 36 | setPassword(''); 37 | setErrorMessage(''); 38 | setMessage('Sign up successful'); 39 | await timeout(1000); 40 | history.push("/"); 41 | } 42 | 43 | useEffect(() => { 44 | setMessage('') 45 | }, [username, password]) 46 | 47 | const showMessage = () => { 48 | if(message === ''){ 49 | return
50 | } 51 | return
52 | {message} 53 |
54 | } 55 | 56 | const showErrorMessage = () => { 57 | if(errorMessage === ''){ 58 | return
59 | } 60 | 61 | return
62 | {errorMessage} 63 |
64 | } 65 | 66 | return ( 67 |
68 |
69 |

Sign Up

70 |
71 | 72 | setUsername(e.target.value)} 75 | placeholder="Username" 76 | className="form-control"> 77 | 78 |
79 |
80 | 81 | setPassword(e.target.value)} 85 | placeholder="Password" 86 | className="form-control"> 87 | 88 |
89 | 90 |
91 | {showMessage()} 92 | {showErrorMessage()} 93 |
94 | ) 95 | } 96 | 97 | export default Signup; -------------------------------------------------------------------------------- /backend/to-do-list/src/main/java/com/backend/todolist/auth/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist.auth.service; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.security.authentication.AuthenticationManager; 5 | import org.springframework.security.authentication.BadCredentialsException; 6 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 7 | import org.springframework.security.core.AuthenticationException; 8 | import org.springframework.security.crypto.password.PasswordEncoder; 9 | import org.springframework.stereotype.Service; 10 | 11 | import com.backend.todolist.auth.controller.UserSigninRequest; 12 | import com.backend.todolist.auth.controller.UserSigninResponse; 13 | import com.backend.todolist.auth.controller.UserSignupRequest; 14 | import com.backend.todolist.auth.controller.UserSignupResponse; 15 | import com.backend.todolist.auth.jwt.JwtTokenGenerator; 16 | import com.backend.todolist.auth.model.User; 17 | import com.backend.todolist.auth.repository.UserRepository; 18 | import com.backend.todolist.errorhandler.BadRequestException; 19 | 20 | @Service 21 | public class UserService { 22 | @Autowired 23 | UserRepository userRepository; 24 | 25 | @Autowired 26 | AuthenticationManager authenticationManager; 27 | 28 | @Autowired 29 | PasswordEncoder passwordEncoder; 30 | 31 | @Autowired 32 | JwtTokenGenerator jwtTokenGenerator; 33 | 34 | public UserSignupResponse signup(UserSignupRequest userSignupRequest) { 35 | try { 36 | String username = userSignupRequest.getUsername(); 37 | String password = userSignupRequest.getPassword(); 38 | 39 | User user = userRepository.findByUsername(username); 40 | if(user != null) { 41 | throw new BadRequestException("Username is already exist"); 42 | } 43 | 44 | User _user = new User(username, passwordEncoder.encode(password)); 45 | _user = userRepository.save(_user); 46 | 47 | String token = jwtTokenGenerator.createToken(_user.getUsername(), _user.getRoleAsList()); 48 | 49 | return new UserSignupResponse(username, token); 50 | } catch (AuthenticationException e) { 51 | throw new BadCredentialsException("Invalid username/password"); 52 | } 53 | } 54 | 55 | public UserSigninResponse signin(UserSigninRequest userSigninRequest) { 56 | try { 57 | String username = userSigninRequest.getUsername(); 58 | authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, userSigninRequest.getPassword())); 59 | String token = jwtTokenGenerator.createToken(username, this.userRepository.findByUsername(username).getRoleAsList()); 60 | 61 | return new UserSigninResponse(username, token); 62 | } catch (AuthenticationException e) { 63 | throw new BadCredentialsException("Invalid username/password"); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /backend/to-do-list/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.3.5.RELEASE 9 | 10 | 11 | com.backend 12 | to-do-list 13 | 0.0.1-SNAPSHOT 14 | jar 15 | to-do-list 16 | To-do-list application backend using spring boot 17 | 18 | 19 | 11 20 | 21 | 22 | 23 | 24 | org.springframework.boot 25 | spring-boot-starter-data-jpa 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-web 30 | 31 | 32 | org.springframework.boot 33 | spring-boot-starter-validation 34 | 35 | 36 | org.springframework.boot 37 | spring-boot-starter-security 38 | 39 | 40 | io.jsonwebtoken 41 | jjwt 42 | 0.9.1 43 | 44 | 45 | 46 | io.springfox 47 | springfox-swagger2 48 | 2.9.2 49 | 50 | 51 | io.springfox 52 | springfox-swagger-ui 53 | 2.9.2 54 | 55 | 56 | 57 | org.springframework.boot 58 | spring-boot-devtools 59 | runtime 60 | true 61 | 62 | 63 | com.h2database 64 | h2 65 | runtime 66 | 67 | 68 | org.springframework.boot 69 | spring-boot-starter-test 70 | test 71 | 72 | 73 | org.junit.vintage 74 | junit-vintage-engine 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | org.springframework.boot 84 | spring-boot-maven-plugin 85 | 86 | 87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /backend/to-do-list/src/main/java/com/backend/todolist/auth/jwt/JwtTokenGenerator.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist.auth.jwt; 2 | 3 | import java.util.Base64; 4 | import java.util.Date; 5 | import java.util.List; 6 | 7 | import javax.annotation.PostConstruct; 8 | import javax.servlet.http.HttpServletRequest; 9 | 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 12 | import org.springframework.security.core.Authentication; 13 | import org.springframework.security.core.userdetails.UserDetails; 14 | import org.springframework.stereotype.Component; 15 | 16 | import com.backend.todolist.auth.service.CustomUserDetailsService; 17 | import com.backend.todolist.errorhandler.InvalidJwtAuthenticationException; 18 | 19 | import io.jsonwebtoken.Claims; 20 | import io.jsonwebtoken.Jws; 21 | import io.jsonwebtoken.JwtException; 22 | import io.jsonwebtoken.Jwts; 23 | import io.jsonwebtoken.SignatureAlgorithm; 24 | 25 | @Component 26 | public class JwtTokenGenerator { 27 | private String secretKey = "thisissupersecretkey"; 28 | 29 | private long validityInMilliseconds = 3600000; // 1h 30 | 31 | @Autowired 32 | private CustomUserDetailsService customUserDetailsService; 33 | 34 | @PostConstruct 35 | protected void init() { 36 | secretKey = Base64.getEncoder().encodeToString(secretKey.getBytes()); 37 | } 38 | 39 | public String createToken(String username, List roles) { 40 | Claims claims = Jwts.claims().setSubject(username); 41 | claims.put("roles", roles); 42 | Date now = new Date(); 43 | Date validity = new Date(now.getTime() + validityInMilliseconds); 44 | return Jwts.builder() 45 | .setClaims(claims) 46 | .setIssuedAt(now) 47 | .setExpiration(validity) 48 | .signWith(SignatureAlgorithm.HS256, secretKey) 49 | .compact(); 50 | } 51 | 52 | public Authentication getAuthentication(String token) { 53 | UserDetails userDetails = this.customUserDetailsService.loadUserByUsername(getUsername(token)); 54 | return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities()); 55 | } 56 | 57 | public String getUsername(String token) { 58 | return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject(); 59 | } 60 | 61 | public String resolveToken(HttpServletRequest req) { 62 | String bearerToken = req.getHeader("Authorization"); 63 | if (bearerToken != null && bearerToken.startsWith("Bearer ")) { 64 | return bearerToken.substring(7, bearerToken.length()); 65 | } 66 | return null; 67 | } 68 | 69 | public boolean validateToken(String token) { 70 | try { 71 | Jws claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token); 72 | if (claims.getBody().getExpiration().before(new Date())) { 73 | return false; 74 | } 75 | return true; 76 | } catch (JwtException | IllegalArgumentException e) { 77 | throw new InvalidJwtAuthenticationException("Expired or invalid JWT token"); 78 | } 79 | } 80 | } -------------------------------------------------------------------------------- /frontend/src/components/todo/UpdateTodo.js: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useState } from 'react'; 2 | import axios from 'axios'; 3 | import moment from 'moment'; 4 | import { useHistory } from "react-router-dom"; 5 | 6 | function UpdateTodo({isAuthenticated, setIsAuthenticated, match}) { 7 | const [title, setTitle] = useState(''); 8 | const [targetDate, setTargetDate] = useState(''); 9 | const [message, setMessage] = useState(''); 10 | const [errorMessage, setErrorMessage] = useState(''); 11 | let history = useHistory(); 12 | 13 | useEffect(() => { 14 | if(!isAuthenticated){ 15 | history.push("/"); 16 | } 17 | }, [isAuthenticated, history]) 18 | 19 | function timeout(delay) { 20 | return new Promise( res => setTimeout(res, delay) ); 21 | } 22 | 23 | const onSubmit = async (e) => { 24 | e.preventDefault(); 25 | 26 | try { 27 | await axios.put(`http://localhost:3001/api/todo/${match.params.id}`, {title, targetDate}, { 28 | headers: { 29 | 'Authorization': `Bearer ${sessionStorage.getItem('token')}` 30 | } 31 | }); 32 | } catch(error){ 33 | setMessage(''); 34 | if (error.response) { 35 | setErrorMessage(error.response.data.message); 36 | } else { 37 | setErrorMessage('Error: something happened'); 38 | } 39 | return; 40 | } 41 | 42 | setErrorMessage(''); 43 | setMessage('Todo successfully updated'); 44 | await timeout(1000); 45 | history.push("/todo"); 46 | } 47 | 48 | useEffect(() => { 49 | const loadData = async () => { 50 | let response = null; 51 | try { 52 | response = await axios.get(`http://localhost:3001/api/todo/${match.params.id}`, { 53 | headers: { 54 | 'Authorization': `Bearer ${sessionStorage.getItem('token')}` 55 | } 56 | }); 57 | } catch(error){ 58 | setMessage(''); 59 | if (error.response) { 60 | setErrorMessage(error.response.data.message); 61 | } else { 62 | setErrorMessage('Error: something happened'); 63 | } 64 | return; 65 | } 66 | setErrorMessage(''); 67 | setTitle(response.data.title); 68 | setTargetDate(moment(response.data.targetDate).format('YYYY-MM-DD')); 69 | } 70 | 71 | loadData(); 72 | }, [match.params.id]); 73 | 74 | useEffect(() => { 75 | setMessage('') 76 | }, [title, targetDate]) 77 | 78 | const showMessage = () => { 79 | if(message === ''){ 80 | return
81 | } 82 | return
83 | {message} 84 |
85 | } 86 | 87 | const showErrorMessage = () => { 88 | if(errorMessage === ''){ 89 | return
90 | } 91 | 92 | return
93 | {errorMessage} 94 |
95 | } 96 | 97 | return ( 98 |
99 |
100 |

Update Todo

101 |
102 | 103 | setTitle(e.target.value)} 106 | className="form-control"> 107 | 108 |
109 |
110 | 111 | setTargetDate(e.target.value)} 115 | className="form-control"> 116 | 117 |
118 | 119 |
120 | {showMessage()} 121 | {showErrorMessage()} 122 |
123 | ) 124 | } 125 | 126 | export default UpdateTodo; -------------------------------------------------------------------------------- /backend/to-do-list/src/main/java/com/backend/todolist/errorhandler/GlobalExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist.errorhandler; 2 | 3 | import java.time.LocalDateTime; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | import org.springframework.http.HttpStatus; 8 | import org.springframework.http.ResponseEntity; 9 | import org.springframework.http.converter.HttpMessageNotReadableException; 10 | import org.springframework.security.authentication.BadCredentialsException; 11 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 12 | import org.springframework.web.bind.MethodArgumentNotValidException; 13 | import org.springframework.web.bind.annotation.ControllerAdvice; 14 | import org.springframework.web.bind.annotation.ExceptionHandler; 15 | 16 | import org.springframework.validation.BindingResult; 17 | 18 | @ControllerAdvice 19 | public class GlobalExceptionHandler { 20 | @ExceptionHandler(ResourceNotFoundException.class) 21 | public ResponseEntity handleResourceNotFoundException(ResourceNotFoundException ex) { 22 | CustomException err = new CustomException(LocalDateTime.now(), HttpStatus.NOT_FOUND, ex.getMessage()); 23 | return ResponseEntityBuilder.build(err); 24 | } 25 | 26 | @ExceptionHandler(BadRequestException.class) 27 | public ResponseEntity handleBadRequestException(BadRequestException ex) { 28 | CustomException err = new CustomException(LocalDateTime.now(), HttpStatus.BAD_REQUEST, ex.getMessage()); 29 | return ResponseEntityBuilder.build(err); 30 | } 31 | 32 | @ExceptionHandler(InvalidPageException.class) 33 | public ResponseEntity handleInvalidPageException(InvalidPageException ex) { 34 | CustomException err = new CustomException(LocalDateTime.now(), HttpStatus.BAD_REQUEST, ex.getMessage()); 35 | return ResponseEntityBuilder.build(err); 36 | } 37 | 38 | @ExceptionHandler(BadCredentialsException.class) 39 | public ResponseEntity handleUsernameNotFoundException(BadCredentialsException ex) { 40 | CustomException err = new CustomException(LocalDateTime.now(), HttpStatus.BAD_REQUEST, ex.getMessage()); 41 | return ResponseEntityBuilder.build(err); 42 | } 43 | 44 | @ExceptionHandler(InvalidJwtAuthenticationException.class) 45 | public ResponseEntity handleInvalidJwtAuthenticationException(InvalidJwtAuthenticationException ex) { 46 | CustomException err = new CustomException(LocalDateTime.now(), HttpStatus.UNAUTHORIZED, ex.getMessage()); 47 | return ResponseEntityBuilder.build(err); 48 | } 49 | 50 | @ExceptionHandler(UsernameNotFoundException.class) 51 | public ResponseEntity handleUsernameNotFoundException(UsernameNotFoundException ex) { 52 | CustomException err = new CustomException(LocalDateTime.now(), HttpStatus.UNAUTHORIZED, "Expired or invalid JWT token"); 53 | return ResponseEntityBuilder.build(err); 54 | } 55 | 56 | @ExceptionHandler(MethodArgumentNotValidException.class) 57 | public ResponseEntity handleMethodArgumentNotValidException (MethodArgumentNotValidException ex) { 58 | BindingResult result = ex.getBindingResult(); 59 | List fieldErrors = result.getFieldErrors(); 60 | 61 | List errorMessage = new ArrayList<>(); 62 | 63 | for (org.springframework.validation.FieldError fieldError: fieldErrors) { 64 | errorMessage.add(fieldError.getDefaultMessage()); 65 | } 66 | 67 | CustomException err = new CustomException(LocalDateTime.now(), HttpStatus.BAD_REQUEST, errorMessage.toString().substring(1, errorMessage.toString().length()-1)); 68 | return ResponseEntityBuilder.build(err); 69 | } 70 | 71 | @ExceptionHandler(HttpMessageNotReadableException.class) 72 | public ResponseEntity handleHttpMessageNotReadableException (HttpMessageNotReadableException ex) { 73 | CustomException err = new CustomException(LocalDateTime.now(), HttpStatus.BAD_REQUEST, "Invalid input"); 74 | return ResponseEntityBuilder.build(err); 75 | } 76 | 77 | @ExceptionHandler(Exception.class) 78 | public ResponseEntity handleAll(Exception ex) { 79 | CustomException err = new CustomException(LocalDateTime.now(), HttpStatus.INTERNAL_SERVER_ERROR, "Something happened"); 80 | return ResponseEntityBuilder.build(err); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /backend/to-do-list/src/main/java/com/backend/todolist/controller/TodoController.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist.controller; 2 | 3 | import java.security.Principal; 4 | import java.util.List; 5 | 6 | import javax.validation.Valid; 7 | 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.http.HttpStatus; 10 | import org.springframework.http.ResponseEntity; 11 | import org.springframework.web.bind.annotation.CrossOrigin; 12 | import org.springframework.web.bind.annotation.PathVariable; 13 | import org.springframework.web.bind.annotation.RequestBody; 14 | import org.springframework.web.bind.annotation.RequestMapping; 15 | import org.springframework.web.bind.annotation.RequestMethod; 16 | import org.springframework.web.bind.annotation.RequestParam; 17 | import org.springframework.web.bind.annotation.ResponseStatus; 18 | import org.springframework.web.bind.annotation.RestController; 19 | 20 | import com.backend.todolist.errorhandler.CustomException; 21 | import com.backend.todolist.model.Todo; 22 | import com.backend.todolist.service.TodoService; 23 | 24 | import io.swagger.annotations.ApiResponse; 25 | import io.swagger.annotations.ApiResponses; 26 | 27 | @RestController 28 | @CrossOrigin(origins = "*", allowCredentials = "true") 29 | @ApiResponses(value = { 30 | @ApiResponse(code=400, message = "Bad Request", response = CustomException.class), 31 | @ApiResponse(code=401, message = "Unauthorized", response = CustomException.class), 32 | @ApiResponse(code=403, message = "Forbidden", response = CustomException.class), 33 | @ApiResponse(code=404, message = "Not Found", response = CustomException.class) 34 | }) 35 | public class TodoController { 36 | @Autowired 37 | private TodoService todoService; 38 | 39 | @ResponseStatus(code = HttpStatus.CREATED) 40 | @RequestMapping(value = "/api/todo", method = RequestMethod.POST) 41 | public ResponseEntity create(@Valid @RequestBody TodoCreateRequest todoCreateRequest, Principal principal) { 42 | return new ResponseEntity<>(todoService.create(todoCreateRequest, principal.getName()), HttpStatus.CREATED); 43 | } 44 | 45 | @ResponseStatus(code = HttpStatus.OK) 46 | @RequestMapping(value = "/api/todo", method = RequestMethod.GET) 47 | public ResponseEntity> readAll(Principal principal, @RequestParam(required = false) String isCompleted){ 48 | if(isCompleted != null) { 49 | return new ResponseEntity<>(todoService.readAllByIsCompleted(principal.getName(), isCompleted), HttpStatus.OK); 50 | } 51 | return new ResponseEntity<>(todoService.readAll(principal.getName()), HttpStatus.OK); 52 | } 53 | 54 | @ResponseStatus(code = HttpStatus.OK) 55 | @RequestMapping(value = "/api/todo/count", method = RequestMethod.GET) 56 | public ResponseEntity countAll(Principal principal, @RequestParam(required = false) String isCompleted){ 57 | if(isCompleted != null) { 58 | return new ResponseEntity<>(todoService.countAllByIsCompleted(principal.getName(), isCompleted), HttpStatus.OK); 59 | } 60 | return new ResponseEntity<>(todoService.countAll(principal.getName()), HttpStatus.OK); 61 | } 62 | 63 | @ResponseStatus(code = HttpStatus.OK) 64 | @RequestMapping(value = "/api/todo/{pageNumber}/{pageSize}", method = RequestMethod.GET) 65 | public ResponseEntity> readAllPageable(Principal principal, @PathVariable String pageNumber, @PathVariable String pageSize, @RequestParam(required = false) String isCompleted){ 66 | if(isCompleted != null) { 67 | return new ResponseEntity<>(todoService.readAllByIsCompletedPageable(principal.getName(), isCompleted, pageNumber, pageSize), HttpStatus.OK); 68 | } 69 | return new ResponseEntity<>(todoService.readAllPageable(principal.getName(), pageNumber, pageSize), HttpStatus.OK); 70 | } 71 | 72 | @ResponseStatus(code = HttpStatus.OK) 73 | @RequestMapping(value = "/api/todo/{id}", method = RequestMethod.GET) 74 | public ResponseEntity read(@PathVariable long id, Principal principal) { 75 | return new ResponseEntity<>(todoService.readById(id, principal.getName()), HttpStatus.OK); 76 | } 77 | 78 | @ResponseStatus(code = HttpStatus.OK) 79 | @RequestMapping(value = "/api/todo/{id}/markcomplete", method = RequestMethod.PUT) 80 | public ResponseEntity markComplete(@PathVariable long id, Principal principal) { 81 | return new ResponseEntity<>(todoService.markCompleteById(id, principal.getName()), HttpStatus.OK); 82 | } 83 | 84 | @ResponseStatus(code = HttpStatus.OK) 85 | @RequestMapping(value = "/api/todo/{id}", method = RequestMethod.PUT) 86 | public ResponseEntity update(@PathVariable long id, @Valid @RequestBody TodoUpdateRequest todoUpdateRequest, Principal principal) { 87 | return new ResponseEntity<>(todoService.updateById(id, todoUpdateRequest, principal.getName()), HttpStatus.OK); 88 | } 89 | 90 | @ResponseStatus(code = HttpStatus.NO_CONTENT) 91 | @RequestMapping(value = "/api/todo/{id}", method = RequestMethod.DELETE) 92 | public ResponseEntity delete(@PathVariable long id, Principal principal) { 93 | todoService.deleteById(id, principal.getName()); 94 | return new ResponseEntity<>(null, HttpStatus.NO_CONTENT); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /backend/to-do-list/.mvn/wrapper/MavenWrapperDownloader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2007-present the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | import java.net.*; 17 | import java.io.*; 18 | import java.nio.channels.*; 19 | import java.util.Properties; 20 | 21 | public class MavenWrapperDownloader { 22 | 23 | private static final String WRAPPER_VERSION = "0.5.6"; 24 | /** 25 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. 26 | */ 27 | private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" 28 | + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; 29 | 30 | /** 31 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to 32 | * use instead of the default one. 33 | */ 34 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH = 35 | ".mvn/wrapper/maven-wrapper.properties"; 36 | 37 | /** 38 | * Path where the maven-wrapper.jar will be saved to. 39 | */ 40 | private static final String MAVEN_WRAPPER_JAR_PATH = 41 | ".mvn/wrapper/maven-wrapper.jar"; 42 | 43 | /** 44 | * Name of the property which should be used to override the default download url for the wrapper. 45 | */ 46 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; 47 | 48 | public static void main(String args[]) { 49 | System.out.println("- Downloader started"); 50 | File baseDirectory = new File(args[0]); 51 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); 52 | 53 | // If the maven-wrapper.properties exists, read it and check if it contains a custom 54 | // wrapperUrl parameter. 55 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); 56 | String url = DEFAULT_DOWNLOAD_URL; 57 | if(mavenWrapperPropertyFile.exists()) { 58 | FileInputStream mavenWrapperPropertyFileInputStream = null; 59 | try { 60 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); 61 | Properties mavenWrapperProperties = new Properties(); 62 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); 63 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); 64 | } catch (IOException e) { 65 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); 66 | } finally { 67 | try { 68 | if(mavenWrapperPropertyFileInputStream != null) { 69 | mavenWrapperPropertyFileInputStream.close(); 70 | } 71 | } catch (IOException e) { 72 | // Ignore ... 73 | } 74 | } 75 | } 76 | System.out.println("- Downloading from: " + url); 77 | 78 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); 79 | if(!outputFile.getParentFile().exists()) { 80 | if(!outputFile.getParentFile().mkdirs()) { 81 | System.out.println( 82 | "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); 83 | } 84 | } 85 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); 86 | try { 87 | downloadFileFromURL(url, outputFile); 88 | System.out.println("Done"); 89 | System.exit(0); 90 | } catch (Throwable e) { 91 | System.out.println("- Error downloading"); 92 | e.printStackTrace(); 93 | System.exit(1); 94 | } 95 | } 96 | 97 | private static void downloadFileFromURL(String urlString, File destination) throws Exception { 98 | if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { 99 | String username = System.getenv("MVNW_USERNAME"); 100 | char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); 101 | Authenticator.setDefault(new Authenticator() { 102 | @Override 103 | protected PasswordAuthentication getPasswordAuthentication() { 104 | return new PasswordAuthentication(username, password); 105 | } 106 | }); 107 | } 108 | URL website = new URL(urlString); 109 | ReadableByteChannel rbc; 110 | rbc = Channels.newChannel(website.openStream()); 111 | FileOutputStream fos = new FileOutputStream(destination); 112 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 113 | fos.close(); 114 | rbc.close(); 115 | } 116 | 117 | } 118 | -------------------------------------------------------------------------------- /backend/to-do-list/src/main/java/com/backend/todolist/service/TodoService.java: -------------------------------------------------------------------------------- 1 | package com.backend.todolist.service; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.data.domain.PageRequest; 7 | import org.springframework.data.domain.Pageable; 8 | import org.springframework.data.domain.Sort; 9 | import org.springframework.stereotype.Service; 10 | 11 | import com.backend.todolist.controller.CountResponse; 12 | import com.backend.todolist.controller.TodoCreateRequest; 13 | import com.backend.todolist.controller.TodoUpdateRequest; 14 | import com.backend.todolist.errorhandler.BadRequestException; 15 | import com.backend.todolist.errorhandler.InvalidPageException; 16 | import com.backend.todolist.errorhandler.ResourceNotFoundException; 17 | import com.backend.todolist.model.Todo; 18 | import com.backend.todolist.repository.TodoRepository; 19 | import com.backend.todolist.repository.TodoPagingRepository; 20 | 21 | @Service 22 | public class TodoService { 23 | @Autowired 24 | private TodoRepository todoRepository; 25 | 26 | @Autowired 27 | private TodoPagingRepository todoPagingRepository; 28 | 29 | public Todo create(TodoCreateRequest todoCreateRequest, String username) { 30 | Todo todo = new Todo(todoCreateRequest.getTitle(), todoCreateRequest.getTargetDate(), username); 31 | return todoRepository.save(todo); 32 | } 33 | 34 | public Todo readById(long id, String username) { 35 | Todo todo = todoRepository.findByUsernameAndId(username, id); 36 | if(todo == null) { 37 | throw new ResourceNotFoundException("Todo not found"); 38 | } 39 | return todo; 40 | } 41 | 42 | public List readAll(String username) { 43 | return todoRepository.findAllByUsername(username); 44 | } 45 | 46 | public List readAllPageable(String username, String pageNumber, String pageSize) { 47 | int _pageNumber = pageNumberStringToInteger(pageNumber); 48 | int _pageSize = pageSizeStringToInteger(pageSize); 49 | 50 | Pageable pageable = PageRequest.of(_pageNumber, _pageSize, Sort.by(Sort.Direction.ASC, "targetDate")); 51 | return todoPagingRepository.findAllByUsername(username, pageable); 52 | } 53 | 54 | public List readAllByIsCompleted(String username, String isCompleted) { 55 | boolean _isCompleted = isCompletedStringToBoolean(isCompleted); 56 | return todoRepository.findAllByUsernameAndIsCompleted(username, _isCompleted); 57 | } 58 | 59 | public List readAllByIsCompletedPageable(String username, String isCompleted, String pageNumber, String pageSize) { 60 | boolean _isCompleted = isCompletedStringToBoolean(isCompleted); 61 | int _pageNumber = pageNumberStringToInteger(pageNumber); 62 | int _pageSize = pageSizeStringToInteger(pageSize); 63 | 64 | Pageable pageable = PageRequest.of(_pageNumber, _pageSize, Sort.by(Sort.Direction.ASC, "targetDate")); 65 | return todoPagingRepository.findAllByUsernameAndIsCompleted(username, _isCompleted, pageable); 66 | } 67 | 68 | public void deleteById(long id, String username) { 69 | Todo todo = todoRepository.findByUsernameAndId(username, id); 70 | if(todo == null) { 71 | throw new ResourceNotFoundException("Todo not found"); 72 | } 73 | todoRepository.deleteById(id); 74 | } 75 | 76 | public Todo updateById(long id, TodoUpdateRequest todoUpdateRequest, String username) { 77 | Todo todo = todoRepository.findByUsernameAndId(username, id); 78 | if(todo == null) { 79 | throw new ResourceNotFoundException("Todo not found"); 80 | } 81 | 82 | todo.setTitle(todoUpdateRequest.getTitle()); 83 | todo.setTargetDate(todoUpdateRequest.getTargetDate()); 84 | return todoRepository.save(todo); 85 | } 86 | 87 | public Todo markCompleteById(long id, String username) { 88 | Todo todo = todoRepository.findByUsernameAndId(username, id); 89 | if(todo == null) { 90 | throw new ResourceNotFoundException("Todo not found"); 91 | } 92 | 93 | todo.setIsCompleted(!todo.getIsCompleted()); 94 | return todoRepository.save(todo); 95 | } 96 | 97 | public CountResponse countAll(String username) { 98 | return new CountResponse(todoRepository.countByUsername(username)); 99 | } 100 | 101 | public CountResponse countAllByIsCompleted(String username, String isCompleted) { 102 | boolean _isCompleted = isCompletedStringToBoolean(isCompleted); 103 | return new CountResponse(todoRepository.countByUsernameAndIsCompleted(username, _isCompleted)); 104 | } 105 | 106 | private boolean isCompletedStringToBoolean(String isCompleted) { 107 | try { 108 | return Boolean.parseBoolean(isCompleted); 109 | } catch (Exception e) { 110 | throw new BadRequestException("Invalid isCompleted"); 111 | } 112 | } 113 | 114 | private int pageNumberStringToInteger(String pageNumber) { 115 | int _pageNumber; 116 | 117 | try { 118 | _pageNumber = Integer.parseInt(pageNumber); 119 | } catch(Exception e) { 120 | throw new InvalidPageException("Invalid Page Number"); 121 | } 122 | 123 | if(_pageNumber < 0) { 124 | throw new InvalidPageException("Invalid page number"); 125 | } 126 | 127 | return _pageNumber; 128 | } 129 | 130 | private int pageSizeStringToInteger(String pageSize) { 131 | int _pageSize; 132 | 133 | try { 134 | _pageSize = Integer.parseInt(pageSize); 135 | } catch(Exception e) { 136 | throw new InvalidPageException("Invalid Page Size"); 137 | } 138 | 139 | if(_pageSize < 1) { 140 | throw new InvalidPageException("Invalid page size"); 141 | } 142 | 143 | return _pageSize; 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /frontend/src/components/todo/ViewTodos.js: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect } from 'react'; 2 | import axios from 'axios'; 3 | import { Link } from 'react-router-dom'; 4 | import moment from 'moment'; 5 | import { useHistory } from "react-router-dom"; 6 | 7 | function Todos({isAuthenticated, setIsAuthenticated}) { 8 | const [todos, setTodos] = useState([]); 9 | const [changed, setChanged] = useState(false); 10 | const [errorMessage, setErrorMessage] = useState(''); 11 | const [pageNumber, setPageNumber] = useState(1); 12 | const [pageSize, setPageSize] = useState(5); 13 | const [inputPageNumber, setInputPageNumber] = useState(pageNumber); 14 | const [inputPageSize, setInputPageSize] = useState(pageSize); 15 | const [filter, setFilter] = useState("All"); 16 | let history = useHistory(); 17 | 18 | useEffect(() => { 19 | if(!isAuthenticated){ 20 | history.push("/"); 21 | } 22 | }, [isAuthenticated, history]) 23 | 24 | useEffect(() => { 25 | const loadData = async () => { 26 | let response = null; 27 | try { 28 | let url = `http://localhost:3001/api/todo/${pageNumber - 1}/${pageSize}`; 29 | 30 | if(filter === 'Completed'){ 31 | url = `http://localhost:3001/api/todo/${pageNumber - 1}/${pageSize}?isCompleted=true`; 32 | } else if(filter === 'Not Completed'){ 33 | url = `http://localhost:3001/api/todo/${pageNumber - 1}/${pageSize}?isCompleted=false`; 34 | } 35 | 36 | response = await axios.get(url, {headers: {'Authorization': `Bearer ${sessionStorage.getItem('token')}`,}}); 37 | } catch(error){ 38 | if (error.response) { 39 | setErrorMessage(error.response.data.message); 40 | } else { 41 | setErrorMessage('Error: something happened'); 42 | } 43 | return; 44 | } 45 | setErrorMessage(''); 46 | setTodos(response.data); 47 | } 48 | 49 | loadData(); 50 | }, [changed, pageNumber, pageSize, filter]) 51 | 52 | const nextPage = () => { 53 | setPageNumber(pageNumber + 1); 54 | setInputPageNumber(pageNumber + 1); 55 | } 56 | 57 | const previousPage = () => { 58 | if(pageNumber > 1){ 59 | setPageNumber(pageNumber - 1); 60 | setInputPageNumber(pageNumber - 1); 61 | } 62 | } 63 | 64 | const enterPageNumber = (enteredPageNumber) => { 65 | if(enteredPageNumber >= 1){ 66 | setPageNumber(parseInt(enteredPageNumber)); 67 | } else { 68 | setPageNumber(1); 69 | setInputPageNumber(1); 70 | } 71 | } 72 | 73 | const enterPageSize = (enteredPageSize) => { 74 | if(enteredPageSize >= 1){ 75 | setPageSize(parseInt(enteredPageSize)); 76 | } else { 77 | setPageSize(1); 78 | setInputPageSize(1); 79 | } 80 | } 81 | 82 | const pageNumberControl = () => { 83 | return
84 |
85 |
86 |
87 | 88 |
89 | setInputPageNumber(e.target.value)} onKeyPress={e => { 90 | if (e.key === 'Enter') { 91 | enterPageNumber(e.target.value) 92 | } 93 | }}/> 94 |
95 | 96 |
97 |
98 |
99 |
100 | } 101 | 102 | const pageSizeControl = () => { 103 | return
104 |
105 |
106 | Todo per page: 107 |
108 | setInputPageSize(e.target.value)} onKeyPress={e => { 109 | if (e.key === 'Enter') { 110 | enterPageSize(e.target.value) 111 | } 112 | }} 113 | /> 114 |
115 |
116 | } 117 | 118 | const filterControl = () => { 119 | return
120 |
121 | 122 | 127 |
128 |
129 | } 130 | 131 | const markCompleted = async (id) => { 132 | try { 133 | await axios.put(`http://localhost:3001/api/todo/${id}/markcomplete`, {}, { 134 | headers: { 135 | 'Authorization': `Bearer ${sessionStorage.getItem('token')}` 136 | } 137 | }); 138 | } catch(error){ 139 | if (error.response) { 140 | setErrorMessage(error.response.data.message); 141 | } else { 142 | setErrorMessage('Error: something happened'); 143 | } 144 | return; 145 | } 146 | setErrorMessage(''); 147 | setChanged(!changed); 148 | } 149 | 150 | const deleteTodo = async (id) => { 151 | try { 152 | await axios.delete(`http://localhost:3001/api/todo/${id}`, { 153 | headers: { 154 | 'Authorization': `Bearer ${sessionStorage.getItem('token')}` 155 | } 156 | }); 157 | } catch(error){ 158 | if (error.response) { 159 | setErrorMessage(error.response.data.message); 160 | } else { 161 | setErrorMessage('Error: something happened'); 162 | } 163 | return; 164 | } 165 | setErrorMessage(''); 166 | setChanged(!changed); 167 | } 168 | 169 | const showErrorMessage = () => { 170 | if(errorMessage === ''){ 171 | return
172 | } 173 | 174 | return
175 | {errorMessage} 176 |
177 | } 178 | 179 | return ( 180 |
181 |

Todo List

182 | {showErrorMessage()} 183 | 184 | {filterControl()} 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | { 199 | todos.map((todo) => { 200 | return 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | }) 209 | } 210 | 211 |
TitleTarget DateIs Completed?Mark CompletedUpdateDelete
{todo.title}{moment(todo.targetDate).format('ll')}{todo.isCompleted.toString()}
212 | {pageSizeControl()} 213 | {pageNumberControl()} 214 |
215 | ); 216 | } 217 | 218 | export default Todos; -------------------------------------------------------------------------------- /backend/to-do-list/mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM https://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 124 | 125 | FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 127 | ) 128 | 129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 131 | if exist %WRAPPER_JAR% ( 132 | if "%MVNW_VERBOSE%" == "true" ( 133 | echo Found %WRAPPER_JAR% 134 | ) 135 | ) else ( 136 | if not "%MVNW_REPOURL%" == "" ( 137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 138 | ) 139 | if "%MVNW_VERBOSE%" == "true" ( 140 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 141 | echo Downloading from: %DOWNLOAD_URL% 142 | ) 143 | 144 | powershell -Command "&{"^ 145 | "$webclient = new-object System.Net.WebClient;"^ 146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 148 | "}"^ 149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ 150 | "}" 151 | if "%MVNW_VERBOSE%" == "true" ( 152 | echo Finished downloading %WRAPPER_JAR% 153 | ) 154 | ) 155 | @REM End of extension 156 | 157 | @REM Provide a "standardized" way to retrieve the CLI args that will 158 | @REM work with both Windows and non-Windows executions. 159 | set MAVEN_CMD_LINE_ARGS=%* 160 | 161 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 162 | if ERRORLEVEL 1 goto error 163 | goto end 164 | 165 | :error 166 | set ERROR_CODE=1 167 | 168 | :end 169 | @endlocal & set ERROR_CODE=%ERROR_CODE% 170 | 171 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 172 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 173 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 174 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 175 | :skipRcPost 176 | 177 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 178 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 179 | 180 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 181 | 182 | exit /B %ERROR_CODE% 183 | -------------------------------------------------------------------------------- /backend/to-do-list/mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # https://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Mingw, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | fi 118 | 119 | if [ -z "$JAVA_HOME" ]; then 120 | javaExecutable="`which javac`" 121 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 122 | # readlink(1) is not available as standard on Solaris 10. 123 | readLink=`which readlink` 124 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 125 | if $darwin ; then 126 | javaHome="`dirname \"$javaExecutable\"`" 127 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 128 | else 129 | javaExecutable="`readlink -f \"$javaExecutable\"`" 130 | fi 131 | javaHome="`dirname \"$javaExecutable\"`" 132 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 133 | JAVA_HOME="$javaHome" 134 | export JAVA_HOME 135 | fi 136 | fi 137 | fi 138 | 139 | if [ -z "$JAVACMD" ] ; then 140 | if [ -n "$JAVA_HOME" ] ; then 141 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 142 | # IBM's JDK on AIX uses strange locations for the executables 143 | JAVACMD="$JAVA_HOME/jre/sh/java" 144 | else 145 | JAVACMD="$JAVA_HOME/bin/java" 146 | fi 147 | else 148 | JAVACMD="`which java`" 149 | fi 150 | fi 151 | 152 | if [ ! -x "$JAVACMD" ] ; then 153 | echo "Error: JAVA_HOME is not defined correctly." >&2 154 | echo " We cannot execute $JAVACMD" >&2 155 | exit 1 156 | fi 157 | 158 | if [ -z "$JAVA_HOME" ] ; then 159 | echo "Warning: JAVA_HOME environment variable is not set." 160 | fi 161 | 162 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 163 | 164 | # traverses directory structure from process work directory to filesystem root 165 | # first directory with .mvn subdirectory is considered project base directory 166 | find_maven_basedir() { 167 | 168 | if [ -z "$1" ] 169 | then 170 | echo "Path not specified to find_maven_basedir" 171 | return 1 172 | fi 173 | 174 | basedir="$1" 175 | wdir="$1" 176 | while [ "$wdir" != '/' ] ; do 177 | if [ -d "$wdir"/.mvn ] ; then 178 | basedir=$wdir 179 | break 180 | fi 181 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 182 | if [ -d "${wdir}" ]; then 183 | wdir=`cd "$wdir/.."; pwd` 184 | fi 185 | # end of workaround 186 | done 187 | echo "${basedir}" 188 | } 189 | 190 | # concatenates all lines of a file 191 | concat_lines() { 192 | if [ -f "$1" ]; then 193 | echo "$(tr -s '\n' ' ' < "$1")" 194 | fi 195 | } 196 | 197 | BASE_DIR=`find_maven_basedir "$(pwd)"` 198 | if [ -z "$BASE_DIR" ]; then 199 | exit 1; 200 | fi 201 | 202 | ########################################################################################## 203 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 204 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 205 | ########################################################################################## 206 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 207 | if [ "$MVNW_VERBOSE" = true ]; then 208 | echo "Found .mvn/wrapper/maven-wrapper.jar" 209 | fi 210 | else 211 | if [ "$MVNW_VERBOSE" = true ]; then 212 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 213 | fi 214 | if [ -n "$MVNW_REPOURL" ]; then 215 | jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 216 | else 217 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 218 | fi 219 | while IFS="=" read key value; do 220 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 221 | esac 222 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 223 | if [ "$MVNW_VERBOSE" = true ]; then 224 | echo "Downloading from: $jarUrl" 225 | fi 226 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 227 | if $cygwin; then 228 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` 229 | fi 230 | 231 | if command -v wget > /dev/null; then 232 | if [ "$MVNW_VERBOSE" = true ]; then 233 | echo "Found wget ... using wget" 234 | fi 235 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 236 | wget "$jarUrl" -O "$wrapperJarPath" 237 | else 238 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" 239 | fi 240 | elif command -v curl > /dev/null; then 241 | if [ "$MVNW_VERBOSE" = true ]; then 242 | echo "Found curl ... using curl" 243 | fi 244 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 245 | curl -o "$wrapperJarPath" "$jarUrl" -f 246 | else 247 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f 248 | fi 249 | 250 | else 251 | if [ "$MVNW_VERBOSE" = true ]; then 252 | echo "Falling back to using Java to download" 253 | fi 254 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 255 | # For Cygwin, switch paths to Windows format before running javac 256 | if $cygwin; then 257 | javaClass=`cygpath --path --windows "$javaClass"` 258 | fi 259 | if [ -e "$javaClass" ]; then 260 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 261 | if [ "$MVNW_VERBOSE" = true ]; then 262 | echo " - Compiling MavenWrapperDownloader.java ..." 263 | fi 264 | # Compiling the Java class 265 | ("$JAVA_HOME/bin/javac" "$javaClass") 266 | fi 267 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 268 | # Running the downloader 269 | if [ "$MVNW_VERBOSE" = true ]; then 270 | echo " - Running MavenWrapperDownloader.java ..." 271 | fi 272 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 273 | fi 274 | fi 275 | fi 276 | fi 277 | ########################################################################################## 278 | # End of extension 279 | ########################################################################################## 280 | 281 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 282 | if [ "$MVNW_VERBOSE" = true ]; then 283 | echo $MAVEN_PROJECTBASEDIR 284 | fi 285 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 286 | 287 | # For Cygwin, switch paths to Windows format before running java 288 | if $cygwin; then 289 | [ -n "$M2_HOME" ] && 290 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 291 | [ -n "$JAVA_HOME" ] && 292 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 293 | [ -n "$CLASSPATH" ] && 294 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 295 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 296 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 297 | fi 298 | 299 | # Provide a "standardized" way to retrieve the CLI args that will 300 | # work with both Windows and non-Windows executions. 301 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 302 | export MAVEN_CMD_LINE_ARGS 303 | 304 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 305 | 306 | exec "$JAVACMD" \ 307 | $MAVEN_OPTS \ 308 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 309 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 310 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 311 | --------------------------------------------------------------------------------