├── .gitignore ├── README.md ├── application.properties ├── build.gradle ├── db.sql ├── settings.gradle └── src └── main ├── java └── org │ └── nagyadam2092 │ └── tripchecker │ ├── Application.java │ ├── controller │ ├── AppController.java │ ├── TripNamesController.java │ └── UserLocationController.java │ ├── database │ ├── TripNames.java │ ├── TripNamesRepository.java │ ├── UserLocation.java │ └── UserLocationRepository.java │ └── security │ ├── AccountCredentials.java │ ├── JWTAuthenticationFilter.java │ ├── JWTLoginFilter.java │ ├── TokenAuthenticationService.java │ ├── WebMvcConfig.java │ └── WebSecurityConfig.java ├── js ├── .babelrc ├── .editorconfig ├── .eslintignore ├── .eslintrc.js ├── .gitignore ├── .postcssrc.js ├── README.md ├── build │ ├── build.js │ ├── check-versions.js │ ├── dev-client.js │ ├── dev-server.js │ ├── utils.js │ ├── vue-loader.conf.js │ ├── webpack.base.conf.js │ ├── webpack.dev.conf.js │ ├── webpack.prod.conf.js │ └── webpack.test.conf.js ├── config │ ├── dev.env.js │ ├── index.js │ ├── prod.env.js │ └── test.env.js ├── index.html ├── package-lock.json ├── package.json ├── src │ ├── App.vue │ ├── assets │ │ └── logo.png │ ├── components │ │ ├── Home.vue │ │ └── Login.vue │ ├── main.js │ ├── router │ │ └── index.js │ ├── store │ │ ├── actions.js │ │ ├── getters.js │ │ ├── index.js │ │ ├── mutation-types.js │ │ └── mutations.js │ └── utils │ │ └── check-geolocation.js ├── static │ └── .gitkeep └── test │ └── unit │ ├── .eslintrc │ ├── index.js │ ├── karma.conf.js │ └── specs │ └── Hello.spec.js └── resources └── static └── logo.png /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | .build/ 3 | .gradle/ 4 | node_modules/ 5 | public/ 6 | log/ -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JWT Spring Boot VueJS authentication 2 | 3 | Ohai, Marv! 4 | -------------------------------------------------------------------------------- /application.properties: -------------------------------------------------------------------------------- 1 | logging.file=log/tripchecker.log 2 | 3 | spring.jpa.hibernate.ddl-auto=none 4 | spring.datasource.url=jdbc:mysql://localhost:3306/trip_checker 5 | spring.datasource.username=adam 6 | spring.datasource.password=adam 7 | 8 | 9 | spring.queries.users-query=select username, password, enabled from users where username=? 10 | spring.queries.roles-query=select username, role from roles where username=? -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | group 'org.nagyadam2092' 2 | version '1.0-SNAPSHOT' 3 | 4 | apply plugin: 'java' 5 | apply plugin: 'org.springframework.boot' 6 | 7 | sourceCompatibility = 1.8 8 | 9 | buildscript { 10 | ext { 11 | springBootVersion = '1.5.4.RELEASE' 12 | } 13 | repositories { 14 | mavenCentral() 15 | } 16 | dependencies { 17 | classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") 18 | } 19 | } 20 | 21 | repositories { 22 | mavenCentral() 23 | } 24 | 25 | dependencies { 26 | compile('org.springframework.boot:spring-boot-starter-data-jpa') 27 | compile('mysql:mysql-connector-java') 28 | compile('org.springframework.boot:spring-boot-starter-security') 29 | compile 'io.jsonwebtoken:jjwt:0.7.0' 30 | compile('org.springframework.boot:spring-boot-starter-web') 31 | testCompile group: 'junit', name: 'junit', version: '4.12' 32 | } 33 | -------------------------------------------------------------------------------- /db.sql: -------------------------------------------------------------------------------- 1 | -- -------------------------------------------------------- 2 | -- Host: 127.0.0.1 3 | -- Server version: 5.7.18-log - MySQL Community Server (GPL) 4 | -- Server OS: Win64 5 | -- HeidiSQL Verzió: 9.4.0.5125 6 | -- -------------------------------------------------------- 7 | 8 | /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; 9 | /*!40101 SET NAMES utf8 */; 10 | /*!50503 SET NAMES utf8mb4 */; 11 | /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; 12 | /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; 13 | 14 | 15 | -- Dumping database structure for trip_checker 16 | DROP DATABASE IF EXISTS `trip_checker`; 17 | CREATE DATABASE IF NOT EXISTS `trip_checker` /*!40100 DEFAULT CHARACTER SET utf8 */; 18 | USE `trip_checker`; 19 | 20 | -- Dumping structure for tábla trip_checker.roles 21 | DROP TABLE IF EXISTS `roles`; 22 | CREATE TABLE IF NOT EXISTS `roles` ( 23 | `username` varchar(50) NOT NULL, 24 | `role` varchar(50) NOT NULL DEFAULT 'plebs', 25 | PRIMARY KEY (`username`) 26 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 27 | 28 | -- Dumping data for table trip_checker.roles: ~1 rows (approximately) 29 | /*!40000 ALTER TABLE `roles` DISABLE KEYS */; 30 | REPLACE INTO `roles` (`username`, `role`) VALUES 31 | ('adam', 'boss'); 32 | /*!40000 ALTER TABLE `roles` ENABLE KEYS */; 33 | 34 | -- Dumping structure for tábla trip_checker.trips 35 | DROP TABLE IF EXISTS `trips`; 36 | CREATE TABLE IF NOT EXISTS `trips` ( 37 | `id` int(11) NOT NULL AUTO_INCREMENT, 38 | `trip_name_id` int(11) NOT NULL, 39 | `stop_name` varchar(150) NOT NULL DEFAULT 'UNDEFINED STOP NAME', 40 | `stop_lat` varchar(50) DEFAULT NULL, 41 | `stop_lon` varchar(50) DEFAULT NULL, 42 | PRIMARY KEY (`id`), 43 | KEY `FK__trip_names_trips` (`trip_name_id`), 44 | CONSTRAINT `FK__trip_names_trips` FOREIGN KEY (`trip_name_id`) REFERENCES `trip_names` (`id`) 45 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 46 | 47 | -- Dumping data for table trip_checker.trips: ~0 rows (approximately) 48 | /*!40000 ALTER TABLE `trips` DISABLE KEYS */; 49 | /*!40000 ALTER TABLE `trips` ENABLE KEYS */; 50 | 51 | -- Dumping structure for tábla trip_checker.trip_names 52 | DROP TABLE IF EXISTS `trip_names`; 53 | CREATE TABLE IF NOT EXISTS `trip_names` ( 54 | `id` int(11) NOT NULL AUTO_INCREMENT, 55 | `name` varchar(50) NOT NULL, 56 | PRIMARY KEY (`id`) 57 | ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; 58 | 59 | -- Dumping data for table trip_checker.trip_names: ~0 rows (approximately) 60 | /*!40000 ALTER TABLE `trip_names` DISABLE KEYS */; 61 | REPLACE INTO `trip_names` (`id`, `name`) VALUES 62 | (1, 'Karika2017'); 63 | /*!40000 ALTER TABLE `trip_names` ENABLE KEYS */; 64 | 65 | -- Dumping structure for tábla trip_checker.users 66 | DROP TABLE IF EXISTS `users`; 67 | CREATE TABLE IF NOT EXISTS `users` ( 68 | `id` int(11) NOT NULL AUTO_INCREMENT, 69 | `username` varchar(50) COLLATE utf8_hungarian_ci NOT NULL DEFAULT '0', 70 | `email` varchar(50) COLLATE utf8_hungarian_ci NOT NULL DEFAULT '0', 71 | `password` varchar(250) COLLATE utf8_hungarian_ci NOT NULL DEFAULT '0', 72 | `enabled` tinyint(4) NOT NULL DEFAULT '1', 73 | PRIMARY KEY (`id`), 74 | UNIQUE KEY `username` (`username`) 75 | ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_hungarian_ci; 76 | 77 | -- Dumping data for table trip_checker.users: ~1 rows (approximately) 78 | /*!40000 ALTER TABLE `users` DISABLE KEYS */; 79 | REPLACE INTO `users` (`id`, `username`, `email`, `password`, `enabled`) VALUES 80 | (1, 'adam', 'nagyadam2092@gmail.com', '$2a$10$xLGNLwrJRzRyn.Ihex5QBewu7LuZZ35e299LTYQRYPWHOCNXKekaS', 1); 81 | /*!40000 ALTER TABLE `users` ENABLE KEYS */; 82 | 83 | -- Dumping structure for tábla trip_checker.user_trips 84 | DROP TABLE IF EXISTS `user_trips`; 85 | CREATE TABLE IF NOT EXISTS `user_trips` ( 86 | `id` int(11) NOT NULL AUTO_INCREMENT, 87 | `user_id` int(11) NOT NULL, 88 | `trip_name_id` int(11) NOT NULL, 89 | PRIMARY KEY (`id`), 90 | KEY `FK__users` (`user_id`), 91 | KEY `FK__trip_names` (`trip_name_id`), 92 | CONSTRAINT `FK__trip_names` FOREIGN KEY (`trip_name_id`) REFERENCES `trip_names` (`id`), 93 | CONSTRAINT `FK__users` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) 94 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 95 | 96 | -- Dumping data for table trip_checker.user_trips: ~0 rows (approximately) 97 | /*!40000 ALTER TABLE `user_trips` DISABLE KEYS */; 98 | /*!40000 ALTER TABLE `user_trips` ENABLE KEYS */; 99 | 100 | /*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */; 101 | /*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */; 102 | /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; 103 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'tripchecker' 2 | 3 | -------------------------------------------------------------------------------- /src/main/java/org/nagyadam2092/tripchecker/Application.java: -------------------------------------------------------------------------------- 1 | package org.nagyadam2092.tripchecker; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | @RestController 8 | @SpringBootApplication 9 | public class Application { 10 | public static void main(String[] args) { 11 | SpringApplication.run(Application.class, args); 12 | } 13 | 14 | public String hello() { 15 | return "Ohai Marv!"; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/org/nagyadam2092/tripchecker/controller/AppController.java: -------------------------------------------------------------------------------- 1 | package org.nagyadam2092.tripchecker.controller; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RestController; 5 | 6 | /** 7 | * Created by adam on 2017.06.27.. 8 | */ 9 | @RestController 10 | public class AppController { 11 | @GetMapping(value = "/app") 12 | public String index() { 13 | return "index"; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/org/nagyadam2092/tripchecker/controller/TripNamesController.java: -------------------------------------------------------------------------------- 1 | package org.nagyadam2092.tripchecker.controller; 2 | 3 | import org.nagyadam2092.tripchecker.database.TripNamesRepository; 4 | import org.nagyadam2092.tripchecker.database.TripNames; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Controller; 7 | import org.springframework.web.bind.annotation.CrossOrigin; 8 | import org.springframework.web.bind.annotation.GetMapping; 9 | import org.springframework.web.bind.annotation.RequestMapping; 10 | import org.springframework.web.bind.annotation.ResponseBody; 11 | 12 | @Controller 13 | @RequestMapping("/api") 14 | public class TripNamesController { 15 | 16 | @Autowired 17 | private TripNamesRepository tripNamesRepository; 18 | 19 | @CrossOrigin 20 | @GetMapping(path = "/tripnames") 21 | public @ResponseBody Iterable getAllTripNames() { 22 | return tripNamesRepository.findAll(); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/org/nagyadam2092/tripchecker/controller/UserLocationController.java: -------------------------------------------------------------------------------- 1 | package org.nagyadam2092.tripchecker.controller; 2 | 3 | import org.nagyadam2092.tripchecker.database.UserLocation; 4 | import org.nagyadam2092.tripchecker.database.UserLocationRepository; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.http.HttpStatus; 8 | import org.springframework.http.ResponseEntity; 9 | import org.springframework.stereotype.Controller; 10 | import org.springframework.web.bind.annotation.*; 11 | import org.slf4j.Logger; 12 | import org.slf4j.LoggerFactory; 13 | 14 | import javax.servlet.http.HttpServletResponse; 15 | 16 | /** 17 | * Created by anagy on 2017. 07. 13.. 18 | */ 19 | @Controller 20 | @RequestMapping("/api") 21 | public class UserLocationController { 22 | private final Logger log = LoggerFactory.getLogger(this.getClass()); 23 | 24 | @Autowired 25 | private UserLocationRepository userLocationRepository; 26 | 27 | @CrossOrigin 28 | @GetMapping(path = "/userlocation") 29 | public @ResponseBody 30 | Iterable getAllUserLocations() { 31 | return userLocationRepository.findAll(); 32 | } 33 | 34 | // @CrossOrigin 35 | // @GetMapping(path = "/userlastlocation") 36 | // public ResponseBody 37 | // UserLocation getLastUserLocation() { 38 | // return userLocationRepository. 39 | // } 40 | 41 | @CrossOrigin 42 | @PostMapping(path = "/userlocation") 43 | public ResponseEntity saveUserLocation(@RequestBody UserLocation userLocation) { 44 | log.info("user location changed: " + userLocation.getUsername(), ", lat: " 45 | + userLocation.getLat() + ", lng: " + userLocation.getLng()); 46 | userLocationRepository.save(userLocation); 47 | return null; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/org/nagyadam2092/tripchecker/database/TripNames.java: -------------------------------------------------------------------------------- 1 | package org.nagyadam2092.tripchecker.database; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.GeneratedValue; 5 | import javax.persistence.GenerationType; 6 | import javax.persistence.Id; 7 | 8 | @Entity 9 | public class TripNames { 10 | 11 | @Id 12 | @GeneratedValue(strategy= GenerationType.AUTO) 13 | private Integer id; 14 | 15 | private String name; 16 | 17 | public Integer getId() { 18 | return id; 19 | } 20 | 21 | public void setId(Integer id) { 22 | this.id = id; 23 | } 24 | 25 | public String getName() { 26 | return name; 27 | } 28 | 29 | public void setName(String name) { 30 | this.name = name; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/org/nagyadam2092/tripchecker/database/TripNamesRepository.java: -------------------------------------------------------------------------------- 1 | package org.nagyadam2092.tripchecker.database; 2 | 3 | import org.springframework.data.repository.CrudRepository; 4 | 5 | /** 6 | * Created by adam on 2017.06.17.. 7 | */ 8 | public interface TripNamesRepository extends CrudRepository { 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/org/nagyadam2092/tripchecker/database/UserLocation.java: -------------------------------------------------------------------------------- 1 | package org.nagyadam2092.tripchecker.database; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.GeneratedValue; 5 | import javax.persistence.GenerationType; 6 | import javax.persistence.Id; 7 | import java.util.Date; 8 | 9 | /** 10 | * Created by anagy on 2017. 07. 13.. 11 | */ 12 | @Entity 13 | public class UserLocation { 14 | @Id 15 | @GeneratedValue(strategy= GenerationType.AUTO) 16 | private Integer id; 17 | 18 | private String username; 19 | private double lat; 20 | private double lng; 21 | 22 | private Integer timestamp; 23 | 24 | public Integer getId() { 25 | return id; 26 | } 27 | 28 | public void setId(Integer id) { 29 | this.id = id; 30 | } 31 | 32 | public String getUsername() { 33 | return username; 34 | } 35 | 36 | public void setUsername(String username) { 37 | this.username = username; 38 | } 39 | 40 | public double getLat() { 41 | return lat; 42 | } 43 | 44 | public void setLat(double lat) { 45 | this.lat = lat; 46 | } 47 | 48 | public double getLng() { 49 | return lng; 50 | } 51 | 52 | public void setLng(double lng) { 53 | this.lng = lng; 54 | } 55 | 56 | public Integer getTimestamp() { 57 | return timestamp; 58 | } 59 | 60 | public void setTimestamp(Integer timestamp) { 61 | this.timestamp = timestamp; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/org/nagyadam2092/tripchecker/database/UserLocationRepository.java: -------------------------------------------------------------------------------- 1 | package org.nagyadam2092.tripchecker.database; 2 | 3 | import org.springframework.data.repository.CrudRepository; 4 | 5 | /** 6 | * Created by anagy on 2017. 07. 13.. 7 | */ 8 | public interface UserLocationRepository extends CrudRepository { 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/org/nagyadam2092/tripchecker/security/AccountCredentials.java: -------------------------------------------------------------------------------- 1 | package org.nagyadam2092.tripchecker.security; 2 | 3 | public class AccountCredentials { 4 | private String username; 5 | private String password; 6 | 7 | public String getUsername() { 8 | return username; 9 | } 10 | 11 | public void setUsername(String username) { 12 | this.username = username; 13 | } 14 | 15 | public String getPassword() { 16 | return password; 17 | } 18 | 19 | public void setPassword(String password) { 20 | this.password = password; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/org/nagyadam2092/tripchecker/security/JWTAuthenticationFilter.java: -------------------------------------------------------------------------------- 1 | package org.nagyadam2092.tripchecker.security; 2 | 3 | import org.springframework.security.core.context.SecurityContextHolder; 4 | import org.springframework.web.filter.GenericFilterBean; 5 | import org.springframework.security.core.Authentication; 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 java.io.IOException; 12 | 13 | public class JWTAuthenticationFilter extends GenericFilterBean { 14 | 15 | @Override 16 | public void doFilter(ServletRequest request, 17 | ServletResponse response, 18 | FilterChain filterChain) 19 | throws IOException, ServletException { 20 | Authentication authentication = TokenAuthenticationService 21 | .getAuthentication((HttpServletRequest)request); 22 | 23 | SecurityContextHolder.getContext() 24 | .setAuthentication(authentication); 25 | filterChain.doFilter(request,response); 26 | } 27 | } -------------------------------------------------------------------------------- /src/main/java/org/nagyadam2092/tripchecker/security/JWTLoginFilter.java: -------------------------------------------------------------------------------- 1 | package org.nagyadam2092.tripchecker.security; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import org.springframework.security.authentication.AuthenticationManager; 5 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 6 | import org.springframework.security.core.Authentication; 7 | import org.springframework.security.core.AuthenticationException; 8 | import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; 9 | import org.springframework.security.web.util.matcher.AntPathRequestMatcher; 10 | 11 | import javax.servlet.FilterChain; 12 | import javax.servlet.ServletException; 13 | import javax.servlet.http.HttpServletRequest; 14 | import javax.servlet.http.HttpServletResponse; 15 | import java.io.IOException; 16 | import java.util.Collections; 17 | import org.slf4j.Logger; 18 | import org.slf4j.LoggerFactory; 19 | 20 | public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter { 21 | private final Logger log = LoggerFactory.getLogger(this.getClass()); 22 | static final String ORIGIN = "http://localhost:3000"; 23 | 24 | public JWTLoginFilter(String url, AuthenticationManager authManager) { 25 | super(new AntPathRequestMatcher(url)); 26 | setAuthenticationManager(authManager); 27 | } 28 | 29 | @Override 30 | public Authentication attemptAuthentication( 31 | HttpServletRequest req, HttpServletResponse res) 32 | throws AuthenticationException, IOException, ServletException { 33 | 34 | // CORS - should be deleted! 35 | String origin = req.getHeader(ORIGIN); 36 | res.setHeader("Access-Control-Allow-Origin", "*");//* or origin as u prefer 37 | res.setHeader("Access-Control-Allow-Credentials", "true"); 38 | res.setHeader("Access-Control-Allow-Headers", 39 | req.getHeader("Access-Control-Request-Headers")); 40 | // end of CORS 41 | 42 | AccountCredentials creds = new ObjectMapper() 43 | .readValue(req.getInputStream(), AccountCredentials.class); 44 | log.info("User logged in: " + creds.getUsername()); 45 | return getAuthenticationManager().authenticate( 46 | new UsernamePasswordAuthenticationToken( 47 | creds.getUsername(), 48 | creds.getPassword(), 49 | Collections.emptyList() 50 | ) 51 | ); 52 | } 53 | 54 | @Override 55 | protected void successfulAuthentication( 56 | HttpServletRequest req, 57 | HttpServletResponse res, FilterChain chain, 58 | Authentication auth) throws IOException, ServletException { 59 | TokenAuthenticationService 60 | .addAuthentication(res, auth.getName()); 61 | } 62 | } -------------------------------------------------------------------------------- /src/main/java/org/nagyadam2092/tripchecker/security/TokenAuthenticationService.java: -------------------------------------------------------------------------------- 1 | package org.nagyadam2092.tripchecker.security; 2 | 3 | import io.jsonwebtoken.Jwts; 4 | import io.jsonwebtoken.SignatureAlgorithm; 5 | import org.springframework.security 6 | .authentication.UsernamePasswordAuthenticationToken; 7 | import org.springframework.security.core.Authentication; 8 | 9 | import javax.servlet.http.HttpServletRequest; 10 | import javax.servlet.http.HttpServletResponse; 11 | import java.io.IOException; 12 | import java.util.Date; 13 | 14 | import static java.util.Collections.emptyList; 15 | 16 | class TokenAuthenticationService { 17 | static final long EXPIRATIONTIME = 864_000_000; // 10 days 18 | static final String SECRET = "ThisIsASecret"; 19 | static final String TOKEN_PREFIX = "Bearer"; 20 | static final String HEADER_STRING = "Authorization"; 21 | 22 | static void addAuthentication(HttpServletResponse res, String username) throws IOException { 23 | String JWT = Jwts.builder() 24 | .setSubject(username) 25 | .setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME)) 26 | .signWith(SignatureAlgorithm.HS512, SECRET) 27 | .compact(); 28 | res.addHeader(HEADER_STRING, TOKEN_PREFIX + " " + JWT); 29 | res.getWriter().write("{\"token\":\"" + JWT + "\"}"); 30 | } 31 | 32 | static Authentication getAuthentication(HttpServletRequest request) { 33 | String token = request.getHeader(HEADER_STRING); 34 | if (token != null) { 35 | // parse the token. 36 | String user = Jwts.parser() 37 | .setSigningKey(SECRET) 38 | .parseClaimsJws(token.replace(TOKEN_PREFIX, "")) 39 | .getBody() 40 | .getSubject(); 41 | 42 | return user != null ? 43 | new UsernamePasswordAuthenticationToken(user, null, emptyList()) : 44 | null; 45 | } 46 | return null; 47 | } 48 | } -------------------------------------------------------------------------------- /src/main/java/org/nagyadam2092/tripchecker/security/WebMvcConfig.java: -------------------------------------------------------------------------------- 1 | package org.nagyadam2092.tripchecker.security; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 6 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 7 | 8 | @Configuration 9 | public class WebMvcConfig extends WebMvcConfigurerAdapter { 10 | @Bean 11 | public BCryptPasswordEncoder passwordEncoder() { 12 | BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(); 13 | return bCryptPasswordEncoder; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/org/nagyadam2092/tripchecker/security/WebSecurityConfig.java: -------------------------------------------------------------------------------- 1 | package org.nagyadam2092.tripchecker.security; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.beans.factory.annotation.Value; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.http.HttpMethod; 7 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 8 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 9 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 10 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 11 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 12 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 13 | 14 | import javax.sql.DataSource; 15 | 16 | @Configuration 17 | @EnableWebSecurity 18 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 19 | 20 | @Autowired 21 | private BCryptPasswordEncoder bCryptPasswordEncoder; 22 | 23 | @Autowired 24 | private DataSource dataSource; 25 | 26 | @Value("${spring.queries.users-query}") 27 | private String usersQuery; 28 | 29 | @Value("${spring.queries.roles-query}") 30 | private String rolesQuery; 31 | 32 | @Override 33 | protected void configure(HttpSecurity http) throws Exception { 34 | http.cors().and().csrf().disable().authorizeRequests() 35 | .antMatchers("/").permitAll() 36 | .antMatchers(HttpMethod.POST, "/api/login").permitAll() 37 | .antMatchers("public/static/**/**").permitAll() 38 | .anyRequest().authenticated() 39 | .and() 40 | // We filter the api/login requests 41 | .addFilterBefore(new JWTLoginFilter("/api/login", authenticationManager()), 42 | UsernamePasswordAuthenticationFilter.class) 43 | // And filter other requests to check the presence of JWT in header 44 | .addFilterBefore(new JWTAuthenticationFilter(), 45 | UsernamePasswordAuthenticationFilter.class); 46 | } 47 | 48 | @Override 49 | protected void configure(AuthenticationManagerBuilder auth) throws Exception { 50 | // Create a default account 51 | auth 52 | .jdbcAuthentication() 53 | .usersByUsernameQuery(usersQuery) 54 | .authoritiesByUsernameQuery(rolesQuery) 55 | .dataSource(dataSource) 56 | .passwordEncoder(bCryptPasswordEncoder); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/js/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | ["env", { "modules": false }], 4 | "stage-2" 5 | ], 6 | "plugins": ["transform-runtime"], 7 | "env": { 8 | "test": { 9 | "presets": ["env", "stage-2"], 10 | "plugins": [ "istanbul" ] 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/js/.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | indent_style = space 6 | indent_size = 2 7 | end_of_line = lf 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | -------------------------------------------------------------------------------- /src/main/js/.eslintignore: -------------------------------------------------------------------------------- 1 | build/*.js 2 | config/*.js 3 | -------------------------------------------------------------------------------- /src/main/js/.eslintrc.js: -------------------------------------------------------------------------------- 1 | // http://eslint.org/docs/user-guide/configuring 2 | 3 | module.exports = { 4 | root: true, 5 | parser: 'babel-eslint', 6 | parserOptions: { 7 | sourceType: 'module' 8 | }, 9 | env: { 10 | browser: true, 11 | }, 12 | // https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style 13 | extends: 'standard', 14 | // required to lint *.vue files 15 | plugins: [ 16 | 'html' 17 | ], 18 | // add your custom rules here 19 | 'rules': { 20 | // allow paren-less arrow functions 21 | 'arrow-parens': 0, 22 | // allow async-await 23 | 'generator-star-spacing': 0, 24 | // allow debugger during development 25 | 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/js/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules/ 3 | dist/ 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | test/unit/coverage 8 | -------------------------------------------------------------------------------- /src/main/js/.postcssrc.js: -------------------------------------------------------------------------------- 1 | // https://github.com/michael-ciniawsky/postcss-load-config 2 | 3 | module.exports = { 4 | "plugins": { 5 | // to edit target browsers: use "browserlist" field in package.json 6 | "autoprefixer": {} 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/js/README.md: -------------------------------------------------------------------------------- 1 | # tripchecker 2 | 3 | > A Vue.js project 4 | 5 | ## Build Setup 6 | 7 | ``` bash 8 | # install dependencies 9 | npm install 10 | 11 | # serve with hot reload at localhost:8080 12 | npm run dev 13 | 14 | # build for production with minification 15 | npm run build 16 | 17 | # build for production and view the bundle analyzer report 18 | npm run build --report 19 | 20 | # run unit tests 21 | npm run unit 22 | 23 | # run all tests 24 | npm test 25 | ``` 26 | 27 | For detailed explanation on how things work, checkout the [guide](http://vuejs-templates.github.io/webpack/) and [docs for vue-loader](http://vuejs.github.io/vue-loader). 28 | -------------------------------------------------------------------------------- /src/main/js/build/build.js: -------------------------------------------------------------------------------- 1 | require('./check-versions')() 2 | 3 | process.env.NODE_ENV = 'production' 4 | 5 | var ora = require('ora') 6 | var rm = require('rimraf') 7 | var path = require('path') 8 | var chalk = require('chalk') 9 | var webpack = require('webpack') 10 | var config = require('../config') 11 | var webpackConfig = require('./webpack.prod.conf') 12 | 13 | var spinner = ora('building for production...') 14 | spinner.start() 15 | 16 | rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => { 17 | if (err) throw err 18 | webpack(webpackConfig, function (err, stats) { 19 | spinner.stop() 20 | if (err) throw err 21 | process.stdout.write(stats.toString({ 22 | colors: true, 23 | modules: false, 24 | children: false, 25 | chunks: false, 26 | chunkModules: false 27 | }) + '\n\n') 28 | 29 | console.log(chalk.cyan(' Build complete.\n')) 30 | console.log(chalk.yellow( 31 | ' Tip: built files are meant to be served over an HTTP server.\n' + 32 | ' Opening index.html over file:// won\'t work.\n' 33 | )) 34 | }) 35 | }) 36 | -------------------------------------------------------------------------------- /src/main/js/build/check-versions.js: -------------------------------------------------------------------------------- 1 | var chalk = require('chalk') 2 | var semver = require('semver') 3 | var packageConfig = require('../package.json') 4 | var shell = require('shelljs') 5 | function exec (cmd) { 6 | return require('child_process').execSync(cmd).toString().trim() 7 | } 8 | 9 | var versionRequirements = [ 10 | { 11 | name: 'node', 12 | currentVersion: semver.clean(process.version), 13 | versionRequirement: packageConfig.engines.node 14 | }, 15 | ] 16 | 17 | if (shell.which('npm')) { 18 | versionRequirements.push({ 19 | name: 'npm', 20 | currentVersion: exec('npm --version'), 21 | versionRequirement: packageConfig.engines.npm 22 | }) 23 | } 24 | 25 | module.exports = function () { 26 | var warnings = [] 27 | for (var i = 0; i < versionRequirements.length; i++) { 28 | var mod = versionRequirements[i] 29 | if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) { 30 | warnings.push(mod.name + ': ' + 31 | chalk.red(mod.currentVersion) + ' should be ' + 32 | chalk.green(mod.versionRequirement) 33 | ) 34 | } 35 | } 36 | 37 | if (warnings.length) { 38 | console.log('') 39 | console.log(chalk.yellow('To use this template, you must update following to modules:')) 40 | console.log() 41 | for (var i = 0; i < warnings.length; i++) { 42 | var warning = warnings[i] 43 | console.log(' ' + warning) 44 | } 45 | console.log() 46 | process.exit(1) 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/js/build/dev-client.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable */ 2 | require('eventsource-polyfill') 3 | var hotClient = require('webpack-hot-middleware/client?noInfo=true&reload=true') 4 | 5 | hotClient.subscribe(function (event) { 6 | if (event.action === 'reload') { 7 | window.location.reload() 8 | } 9 | }) 10 | -------------------------------------------------------------------------------- /src/main/js/build/dev-server.js: -------------------------------------------------------------------------------- 1 | require('./check-versions')() 2 | 3 | var config = require('../config') 4 | if (!process.env.NODE_ENV) { 5 | process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV) 6 | } 7 | 8 | var opn = require('opn') 9 | var path = require('path') 10 | var express = require('express') 11 | var webpack = require('webpack') 12 | var proxyMiddleware = require('http-proxy-middleware') 13 | var webpackConfig = process.env.NODE_ENV === 'testing' 14 | ? require('./webpack.prod.conf') 15 | : require('./webpack.dev.conf') 16 | 17 | // default port where dev server listens for incoming traffic 18 | var port = process.env.PORT || config.dev.port 19 | // automatically open browser, if not set will be false 20 | var autoOpenBrowser = !!config.dev.autoOpenBrowser 21 | // Define HTTP proxies to your custom API backend 22 | // https://github.com/chimurai/http-proxy-middleware 23 | var proxyTable = config.dev.proxyTable 24 | 25 | var app = express() 26 | var compiler = webpack(webpackConfig) 27 | 28 | var devMiddleware = require('webpack-dev-middleware')(compiler, { 29 | publicPath: webpackConfig.output.publicPath, 30 | quiet: true 31 | }) 32 | 33 | var hotMiddleware = require('webpack-hot-middleware')(compiler, { 34 | log: () => {} 35 | }) 36 | // force page reload when html-webpack-plugin template changes 37 | compiler.plugin('compilation', function (compilation) { 38 | compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) { 39 | hotMiddleware.publish({ action: 'reload' }) 40 | cb() 41 | }) 42 | }) 43 | 44 | // proxy api requests 45 | Object.keys(proxyTable).forEach(function (context) { 46 | var options = proxyTable[context] 47 | if (typeof options === 'string') { 48 | options = { target: options } 49 | } 50 | app.use(proxyMiddleware(options.filter || context, options)) 51 | }) 52 | 53 | // handle fallback for HTML5 history API 54 | app.use(require('connect-history-api-fallback')()) 55 | 56 | // serve webpack bundle output 57 | app.use(devMiddleware) 58 | 59 | // enable hot-reload and state-preserving 60 | // compilation error display 61 | app.use(hotMiddleware) 62 | 63 | // serve pure static assets 64 | var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory) 65 | app.use(staticPath, express.static('./static')) 66 | 67 | var uri = 'http://localhost:' + port 68 | 69 | var _resolve 70 | var readyPromise = new Promise(resolve => { 71 | _resolve = resolve 72 | }) 73 | 74 | console.log('> Starting dev server...') 75 | devMiddleware.waitUntilValid(() => { 76 | console.log('> Listening at ' + uri + '\n') 77 | // when env is testing, don't need open it 78 | if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') { 79 | opn(uri) 80 | } 81 | _resolve() 82 | }) 83 | 84 | var server = app.listen(port) 85 | 86 | module.exports = { 87 | ready: readyPromise, 88 | close: () => { 89 | server.close() 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/main/js/build/utils.js: -------------------------------------------------------------------------------- 1 | var path = require('path') 2 | var config = require('../config') 3 | var ExtractTextPlugin = require('extract-text-webpack-plugin') 4 | 5 | exports.assetsPath = function (_path) { 6 | var assetsSubDirectory = process.env.NODE_ENV === 'production' 7 | ? config.build.assetsSubDirectory 8 | : config.dev.assetsSubDirectory 9 | return path.posix.join(assetsSubDirectory, _path) 10 | } 11 | 12 | exports.cssLoaders = function (options) { 13 | options = options || {} 14 | 15 | var cssLoader = { 16 | loader: 'css-loader', 17 | options: { 18 | minimize: process.env.NODE_ENV === 'production', 19 | sourceMap: options.sourceMap 20 | } 21 | } 22 | 23 | // generate loader string to be used with extract text plugin 24 | function generateLoaders (loader, loaderOptions) { 25 | var loaders = [cssLoader] 26 | if (loader) { 27 | loaders.push({ 28 | loader: loader + '-loader', 29 | options: Object.assign({}, loaderOptions, { 30 | sourceMap: options.sourceMap 31 | }) 32 | }) 33 | } 34 | 35 | // Extract CSS when that option is specified 36 | // (which is the case during production build) 37 | if (options.extract) { 38 | return ExtractTextPlugin.extract({ 39 | use: loaders, 40 | fallback: 'vue-style-loader' 41 | }) 42 | } else { 43 | return ['vue-style-loader'].concat(loaders) 44 | } 45 | } 46 | 47 | // https://vue-loader.vuejs.org/en/configurations/extract-css.html 48 | return { 49 | css: generateLoaders(), 50 | postcss: generateLoaders(), 51 | less: generateLoaders('less'), 52 | sass: generateLoaders('sass', { indentedSyntax: true }), 53 | scss: generateLoaders('sass'), 54 | stylus: generateLoaders('stylus'), 55 | styl: generateLoaders('stylus') 56 | } 57 | } 58 | 59 | // Generate loaders for standalone style files (outside of .vue) 60 | exports.styleLoaders = function (options) { 61 | var output = [] 62 | var loaders = exports.cssLoaders(options) 63 | for (var extension in loaders) { 64 | var loader = loaders[extension] 65 | output.push({ 66 | test: new RegExp('\\.' + extension + '$'), 67 | use: loader 68 | }) 69 | } 70 | return output 71 | } 72 | -------------------------------------------------------------------------------- /src/main/js/build/vue-loader.conf.js: -------------------------------------------------------------------------------- 1 | var utils = require('./utils') 2 | var config = require('../config') 3 | var isProduction = process.env.NODE_ENV === 'production' 4 | 5 | module.exports = { 6 | loaders: utils.cssLoaders({ 7 | sourceMap: isProduction 8 | ? config.build.productionSourceMap 9 | : config.dev.cssSourceMap, 10 | extract: isProduction 11 | }) 12 | } 13 | -------------------------------------------------------------------------------- /src/main/js/build/webpack.base.conf.js: -------------------------------------------------------------------------------- 1 | var path = require('path') 2 | var utils = require('./utils') 3 | var config = require('../config') 4 | var vueLoaderConfig = require('./vue-loader.conf') 5 | 6 | function resolve (dir) { 7 | return path.join(__dirname, '..', dir) 8 | } 9 | 10 | module.exports = { 11 | entry: { 12 | app: './src/main.js' 13 | }, 14 | output: { 15 | path: config.build.assetsRoot, 16 | filename: '[name].js', 17 | publicPath: process.env.NODE_ENV === 'production' 18 | ? config.build.assetsPublicPath 19 | : config.dev.assetsPublicPath 20 | }, 21 | resolve: { 22 | extensions: ['.js', '.vue', '.json'], 23 | alias: { 24 | 'vue$': 'vue/dist/vue.esm.js', 25 | '@': resolve('src') 26 | } 27 | }, 28 | module: { 29 | rules: [ 30 | { 31 | test: /\.(js|vue)$/, 32 | loader: 'eslint-loader', 33 | enforce: 'pre', 34 | include: [resolve('src'), resolve('test')], 35 | options: { 36 | formatter: require('eslint-friendly-formatter') 37 | } 38 | }, 39 | { 40 | test: /\.vue$/, 41 | loader: 'vue-loader', 42 | options: vueLoaderConfig 43 | }, 44 | { 45 | test: /\.js$/, 46 | loader: 'babel-loader', 47 | include: [resolve('src'), resolve('test')] 48 | }, 49 | { 50 | test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, 51 | loader: 'url-loader', 52 | options: { 53 | limit: 10000, 54 | name: utils.assetsPath('img/[name].[hash:7].[ext]') 55 | } 56 | }, 57 | { 58 | test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, 59 | loader: 'url-loader', 60 | options: { 61 | limit: 10000, 62 | name: utils.assetsPath('fonts/[name].[hash:7].[ext]') 63 | } 64 | } 65 | ] 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/js/build/webpack.dev.conf.js: -------------------------------------------------------------------------------- 1 | var utils = require('./utils') 2 | var webpack = require('webpack') 3 | var config = require('../config') 4 | var merge = require('webpack-merge') 5 | var baseWebpackConfig = require('./webpack.base.conf') 6 | var HtmlWebpackPlugin = require('html-webpack-plugin') 7 | var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin') 8 | 9 | // add hot-reload related code to entry chunks 10 | Object.keys(baseWebpackConfig.entry).forEach(function (name) { 11 | baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name]) 12 | }) 13 | 14 | module.exports = merge(baseWebpackConfig, { 15 | module: { 16 | rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap }) 17 | }, 18 | // cheap-module-eval-source-map is faster for development 19 | devtool: '#cheap-module-eval-source-map', 20 | plugins: [ 21 | new webpack.DefinePlugin({ 22 | 'process.env': config.dev.env 23 | }), 24 | // https://github.com/glenjamin/webpack-hot-middleware#installation--usage 25 | new webpack.HotModuleReplacementPlugin(), 26 | new webpack.NoEmitOnErrorsPlugin(), 27 | // https://github.com/ampedandwired/html-webpack-plugin 28 | new HtmlWebpackPlugin({ 29 | filename: 'index.html', 30 | template: 'index.html', 31 | inject: true 32 | }), 33 | new FriendlyErrorsPlugin() 34 | ] 35 | }) 36 | -------------------------------------------------------------------------------- /src/main/js/build/webpack.prod.conf.js: -------------------------------------------------------------------------------- 1 | var path = require('path') 2 | var utils = require('./utils') 3 | var webpack = require('webpack') 4 | var config = require('../config') 5 | var merge = require('webpack-merge') 6 | var baseWebpackConfig = require('./webpack.base.conf') 7 | var CopyWebpackPlugin = require('copy-webpack-plugin') 8 | var HtmlWebpackPlugin = require('html-webpack-plugin') 9 | var ExtractTextPlugin = require('extract-text-webpack-plugin') 10 | var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin') 11 | 12 | var env = process.env.NODE_ENV === 'testing' 13 | ? require('../config/test.env') 14 | : config.build.env 15 | 16 | var webpackConfig = merge(baseWebpackConfig, { 17 | module: { 18 | rules: utils.styleLoaders({ 19 | sourceMap: config.build.productionSourceMap, 20 | extract: true 21 | }) 22 | }, 23 | devtool: config.build.productionSourceMap ? '#source-map' : false, 24 | output: { 25 | path: config.build.assetsRoot, 26 | filename: utils.assetsPath('js/[name].[chunkhash].js'), 27 | chunkFilename: utils.assetsPath('js/[id].[chunkhash].js') 28 | }, 29 | plugins: [ 30 | // http://vuejs.github.io/vue-loader/en/workflow/production.html 31 | new webpack.DefinePlugin({ 32 | 'process.env': env 33 | }), 34 | new webpack.optimize.UglifyJsPlugin({ 35 | compress: { 36 | warnings: false 37 | }, 38 | sourceMap: true 39 | }), 40 | // extract css into its own file 41 | new ExtractTextPlugin({ 42 | filename: utils.assetsPath('css/[name].[contenthash].css') 43 | }), 44 | // Compress extracted CSS. We are using this plugin so that possible 45 | // duplicated CSS from different components can be deduped. 46 | new OptimizeCSSPlugin({ 47 | cssProcessorOptions: { 48 | safe: true 49 | } 50 | }), 51 | // generate dist index.html with correct asset hash for caching. 52 | // you can customize output by editing /index.html 53 | // see https://github.com/ampedandwired/html-webpack-plugin 54 | new HtmlWebpackPlugin({ 55 | filename: process.env.NODE_ENV === 'testing' 56 | ? 'index.html' 57 | : config.build.index, 58 | template: 'index.html', 59 | inject: true, 60 | minify: { 61 | removeComments: true, 62 | collapseWhitespace: true, 63 | removeAttributeQuotes: true 64 | // more options: 65 | // https://github.com/kangax/html-minifier#options-quick-reference 66 | }, 67 | // necessary to consistently work with multiple chunks via CommonsChunkPlugin 68 | chunksSortMode: 'dependency' 69 | }), 70 | // split vendor js into its own file 71 | new webpack.optimize.CommonsChunkPlugin({ 72 | name: 'vendor', 73 | minChunks: function (module, count) { 74 | // any required modules inside node_modules are extracted to vendor 75 | return ( 76 | module.resource && 77 | /\.js$/.test(module.resource) && 78 | module.resource.indexOf( 79 | path.join(__dirname, '../node_modules') 80 | ) === 0 81 | ) 82 | } 83 | }), 84 | // extract webpack runtime and module manifest to its own file in order to 85 | // prevent vendor hash from being updated whenever app bundle is updated 86 | new webpack.optimize.CommonsChunkPlugin({ 87 | name: 'manifest', 88 | chunks: ['vendor'] 89 | }), 90 | // copy custom static assets 91 | new CopyWebpackPlugin([ 92 | { 93 | from: path.resolve(__dirname, '../static'), 94 | to: config.build.assetsSubDirectory, 95 | ignore: ['.*'] 96 | } 97 | ]) 98 | ] 99 | }) 100 | 101 | if (config.build.productionGzip) { 102 | var CompressionWebpackPlugin = require('compression-webpack-plugin') 103 | 104 | webpackConfig.plugins.push( 105 | new CompressionWebpackPlugin({ 106 | asset: '[path].gz[query]', 107 | algorithm: 'gzip', 108 | test: new RegExp( 109 | '\\.(' + 110 | config.build.productionGzipExtensions.join('|') + 111 | ')$' 112 | ), 113 | threshold: 10240, 114 | minRatio: 0.8 115 | }) 116 | ) 117 | } 118 | 119 | if (config.build.bundleAnalyzerReport) { 120 | var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin 121 | webpackConfig.plugins.push(new BundleAnalyzerPlugin()) 122 | } 123 | 124 | module.exports = webpackConfig 125 | -------------------------------------------------------------------------------- /src/main/js/build/webpack.test.conf.js: -------------------------------------------------------------------------------- 1 | // This is the webpack config used for unit tests. 2 | 3 | var utils = require('./utils') 4 | var webpack = require('webpack') 5 | var merge = require('webpack-merge') 6 | var baseConfig = require('./webpack.base.conf') 7 | 8 | var webpackConfig = merge(baseConfig, { 9 | // use inline sourcemap for karma-sourcemap-loader 10 | module: { 11 | rules: utils.styleLoaders() 12 | }, 13 | devtool: '#inline-source-map', 14 | resolveLoader: { 15 | alias: { 16 | // necessary to to make lang="scss" work in test when using vue-loader's ?inject option 17 | // see discussion at https://github.com/vuejs/vue-loader/issues/724 18 | 'scss-loader': 'sass-loader' 19 | } 20 | }, 21 | plugins: [ 22 | new webpack.DefinePlugin({ 23 | 'process.env': require('../config/test.env') 24 | }) 25 | ] 26 | }) 27 | 28 | // no need for app entry during tests 29 | delete webpackConfig.entry 30 | 31 | module.exports = webpackConfig 32 | -------------------------------------------------------------------------------- /src/main/js/config/dev.env.js: -------------------------------------------------------------------------------- 1 | var merge = require('webpack-merge') 2 | var prodEnv = require('./prod.env') 3 | 4 | module.exports = merge(prodEnv, { 5 | NODE_ENV: '"development"' 6 | }) 7 | -------------------------------------------------------------------------------- /src/main/js/config/index.js: -------------------------------------------------------------------------------- 1 | // see http://vuejs-templates.github.io/webpack for documentation. 2 | var path = require('path') 3 | 4 | module.exports = { 5 | build: { 6 | env: require('./prod.env'), 7 | index: path.resolve(__dirname, '../../../../public/index.html'), 8 | assetsRoot: path.resolve(__dirname, '../../../../public'), 9 | assetsSubDirectory: 'static', 10 | assetsPublicPath: '/', 11 | productionSourceMap: true, 12 | // Gzip off by default as many popular static hosts such as 13 | // Surge or Netlify already gzip all static assets for you. 14 | // Before setting to `true`, make sure to: 15 | // npm install --save-dev compression-webpack-plugin 16 | productionGzip: false, 17 | productionGzipExtensions: ['js', 'css'], 18 | // Run the build command with an extra argument to 19 | // View the bundle analyzer report after build finishes: 20 | // `npm run build --report` 21 | // Set to `true` or `false` to always turn it on or off 22 | bundleAnalyzerReport: process.env.npm_config_report 23 | }, 24 | dev: { 25 | env: require('./dev.env'), 26 | port: 3000, 27 | autoOpenBrowser: true, 28 | assetsSubDirectory: 'static', 29 | assetsPublicPath: '/', 30 | proxyTable: { 31 | '/login': { 32 | target: 'http://localhost:8080/', 33 | changeOrigin: true 34 | }, 35 | '/api': { 36 | target: 'http://localhost:8080/', 37 | changeOrigin: true 38 | } 39 | }, 40 | // CSS Sourcemaps off by default because relative paths are "buggy" 41 | // with this option, according to the CSS-Loader README 42 | // (https://github.com/webpack/css-loader#sourcemaps) 43 | // In our experience, they generally work as expected, 44 | // just be aware of this issue when enabling this option. 45 | cssSourceMap: false 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/js/config/prod.env.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | NODE_ENV: '"production"' 3 | } 4 | -------------------------------------------------------------------------------- /src/main/js/config/test.env.js: -------------------------------------------------------------------------------- 1 | var merge = require('webpack-merge') 2 | var devEnv = require('./dev.env') 3 | 4 | module.exports = merge(devEnv, { 5 | NODE_ENV: '"testing"' 6 | }) 7 | -------------------------------------------------------------------------------- /src/main/js/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | tripchecker 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /src/main/js/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "tripchecker", 3 | "version": "1.0.0", 4 | "description": "A Vue.js project", 5 | "author": "Adam Nagy ", 6 | "private": true, 7 | "scripts": { 8 | "dev": "node build/dev-server.js", 9 | "start": "node build/dev-server.js", 10 | "build": "node build/build.js", 11 | "unit": "cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run", 12 | "test": "npm run unit", 13 | "lint": "eslint --ext .js,.vue src test/unit/specs" 14 | }, 15 | "dependencies": { 16 | "es6-promise": "^4.1.1", 17 | "isomorphic-fetch": "^2.2.1", 18 | "vue": "^2.3.3", 19 | "vue-router": "^2.3.1", 20 | "vuex": "^2.3.1" 21 | }, 22 | "devDependencies": { 23 | "autoprefixer": "^6.7.2", 24 | "babel-core": "^6.22.1", 25 | "babel-eslint": "^7.1.1", 26 | "babel-loader": "^6.2.10", 27 | "babel-plugin-transform-runtime": "^6.22.0", 28 | "babel-preset-env": "^1.3.2", 29 | "babel-preset-stage-2": "^6.22.0", 30 | "babel-register": "^6.22.0", 31 | "chalk": "^1.1.3", 32 | "connect-history-api-fallback": "^1.3.0", 33 | "copy-webpack-plugin": "^4.0.1", 34 | "css-loader": "^0.28.0", 35 | "eslint": "^3.19.0", 36 | "eslint-friendly-formatter": "^2.0.7", 37 | "eslint-loader": "^1.7.1", 38 | "eslint-plugin-html": "^2.0.0", 39 | "eslint-config-standard": "^6.2.1", 40 | "eslint-plugin-promise": "^3.4.0", 41 | "eslint-plugin-standard": "^2.0.1", 42 | "eventsource-polyfill": "^0.9.6", 43 | "express": "^4.14.1", 44 | "extract-text-webpack-plugin": "^2.0.0", 45 | "file-loader": "^0.11.1", 46 | "friendly-errors-webpack-plugin": "^1.1.3", 47 | "html-webpack-plugin": "^2.28.0", 48 | "http-proxy-middleware": "^0.17.3", 49 | "webpack-bundle-analyzer": "^2.2.1", 50 | "cross-env": "^4.0.0", 51 | "karma": "^1.4.1", 52 | "karma-coverage": "^1.1.1", 53 | "karma-mocha": "^1.3.0", 54 | "karma-phantomjs-launcher": "^1.0.2", 55 | "karma-phantomjs-shim": "^1.4.0", 56 | "karma-sinon-chai": "^1.3.1", 57 | "karma-sourcemap-loader": "^0.3.7", 58 | "karma-spec-reporter": "0.0.30", 59 | "karma-webpack": "^2.0.2", 60 | "lolex": "^1.5.2", 61 | "mocha": "^3.2.0", 62 | "chai": "^3.5.0", 63 | "sinon": "^2.1.0", 64 | "sinon-chai": "^2.8.0", 65 | "inject-loader": "^3.0.0", 66 | "babel-plugin-istanbul": "^4.1.1", 67 | "phantomjs-prebuilt": "^2.1.14", 68 | "semver": "^5.3.0", 69 | "shelljs": "^0.7.6", 70 | "opn": "^4.0.2", 71 | "optimize-css-assets-webpack-plugin": "^1.3.0", 72 | "ora": "^1.2.0", 73 | "rimraf": "^2.6.0", 74 | "url-loader": "^0.5.8", 75 | "vue-loader": "^12.1.0", 76 | "vue-style-loader": "^3.0.1", 77 | "vue-template-compiler": "^2.3.3", 78 | "webpack": "^2.6.1", 79 | "webpack-dev-middleware": "^1.10.0", 80 | "webpack-hot-middleware": "^2.18.0", 81 | "webpack-merge": "^4.1.0" 82 | }, 83 | "engines": { 84 | "node": ">= 4.0.0", 85 | "npm": ">= 3.0.0" 86 | }, 87 | "browserslist": [ 88 | "> 1%", 89 | "last 2 versions", 90 | "not ie <= 8" 91 | ] 92 | } 93 | -------------------------------------------------------------------------------- /src/main/js/src/App.vue: -------------------------------------------------------------------------------- 1 | 6 | 7 | 12 | 13 | 18 | -------------------------------------------------------------------------------- /src/main/js/src/assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagyadam2092/jwt-spring-boot-vuejs-auth/6105cba818090aeeed3f12002a8b9503c7a646a1/src/main/js/src/assets/logo.png -------------------------------------------------------------------------------- /src/main/js/src/components/Home.vue: -------------------------------------------------------------------------------- 1 | 10 | 11 | 60 | 61 | 62 | 64 | -------------------------------------------------------------------------------- /src/main/js/src/components/Login.vue: -------------------------------------------------------------------------------- 1 | 17 | 18 | 74 | 75 | 76 | 224 | -------------------------------------------------------------------------------- /src/main/js/src/main.js: -------------------------------------------------------------------------------- 1 | // The Vue build version to load with the `import` command 2 | // (runtime-only or standalone) has been set in webpack.base.conf with an alias. 3 | import 'whatwg-fetch' 4 | import Vue from 'vue' 5 | import App from './App' 6 | import router from './router' 7 | import store from './store' 8 | 9 | Vue.config.productionTip = false 10 | /* eslint-disable no-new */ 11 | new Vue({ 12 | store, 13 | el: '#app', 14 | router, 15 | template: '', 16 | components: { App } 17 | }) 18 | -------------------------------------------------------------------------------- /src/main/js/src/router/index.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import Router from 'vue-router' 3 | import Home from '@/components/Home' 4 | import Login from '@/components/Login' 5 | import store from '../store' 6 | import * as types from '../store/mutation-types' 7 | 8 | const hasToken = (to, from, next) => { 9 | const token = localStorage.getItem('JWT') 10 | const username = localStorage.getItem('username') 11 | if (token) { 12 | store.commit(types.LOGIN_SUCCESS, { token, username }) 13 | router.push('/home') 14 | } else { 15 | next() 16 | } 17 | } 18 | 19 | const requireAuth = (to, from, next) => { 20 | if (store.getters.isLoggedIn) { 21 | next() 22 | } else { 23 | router.push('/') 24 | } 25 | } 26 | 27 | Vue.use(Router) 28 | 29 | const router = new Router({ 30 | routes: [ 31 | { 32 | path: '/', 33 | alias: '/login', 34 | name: 'Login', 35 | component: Login, 36 | beforeEnter: hasToken 37 | }, 38 | { 39 | path: '/home', 40 | name: 'Home', 41 | component: Home, 42 | beforeEnter: requireAuth 43 | } 44 | ] 45 | }) 46 | 47 | export default router 48 | -------------------------------------------------------------------------------- /src/main/js/src/store/actions.js: -------------------------------------------------------------------------------- 1 | import fetch from 'isomorphic-fetch' 2 | import * as types from './mutation-types' 3 | import router from '../router' 4 | 5 | const login = ({ commit }, creds) => { 6 | commit(types.LOGIN) // show spinner 7 | return fetch('/api/login', { 8 | method: 'POST', 9 | headers: { 10 | Accept: 'application/json' 11 | }, 12 | body: JSON.stringify(creds) 13 | }) 14 | } 15 | 16 | const logout = ({ commit }) => { 17 | commit(types.LOGOUT) 18 | localStorage.removeItem('JWT') 19 | router.push('/login') 20 | } 21 | 22 | const sendCoordinates = ({ getters }) => { 23 | const token = getters.getToken 24 | console.log(token) 25 | return fetch('/api/coordinate', { 26 | method: 'POST', 27 | headers: { 28 | Authorization: 'Bearer ' + token 29 | } 30 | }) 31 | } 32 | 33 | export default { 34 | [types.LOGIN]: login, 35 | [types.LOGOUT]: logout, 36 | [types.SEND_COORDINATES]: sendCoordinates 37 | } 38 | 39 | -------------------------------------------------------------------------------- /src/main/js/src/store/getters.js: -------------------------------------------------------------------------------- 1 | export const isLoggedIn = state => 2 | state.auth.isLoggedIn 3 | 4 | export const getToken = state => 5 | state.auth.token 6 | 7 | export const username = state => 8 | state.auth.username 9 | -------------------------------------------------------------------------------- /src/main/js/src/store/index.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import Vuex from 'vuex' 3 | import actions from './actions' 4 | import * as getters from './getters' 5 | import mutations from './mutations' 6 | 7 | Vue.use(Vuex) 8 | 9 | const state = { 10 | auth: { 11 | isLoggedIn: false, 12 | pending: false, 13 | token: null, 14 | username: null 15 | } 16 | } 17 | 18 | const options = { 19 | state, 20 | mutations, 21 | actions, 22 | getters 23 | } 24 | 25 | const store = new Vuex.Store(options) 26 | 27 | export default store 28 | -------------------------------------------------------------------------------- /src/main/js/src/store/mutation-types.js: -------------------------------------------------------------------------------- 1 | export const LOGIN = 'LOGIN' 2 | export const LOGIN_SUCCESS = 'LOGIN_SUCCESS' 3 | export const LOGIN_WRONG_CREDENTIALS = 'LOGIN_WRONG_CREDENTIALS' 4 | export const LOGIN_ERROR = 'LOGIN_ERROR' 5 | export const LOGOUT = 'LOGOUT' 6 | 7 | export const SEND_COORDINATES = 'SEND_COORDINATES' 8 | -------------------------------------------------------------------------------- /src/main/js/src/store/mutations.js: -------------------------------------------------------------------------------- 1 | import * as types from './mutation-types' 2 | 3 | const mutations = { 4 | [types.LOGIN] (state) { 5 | state.auth.pending = true 6 | }, 7 | [types.LOGIN_SUCCESS] (state, data) { 8 | const token = data.token 9 | const username = data.username 10 | console.log('data: ', data) 11 | state.auth.isLoggedIn = true 12 | state.auth.pending = false 13 | state.auth.token = token 14 | state.auth.username = username 15 | localStorage.setItem('JWT', token) 16 | localStorage.setItem('username', username) 17 | }, 18 | [types.LOGIN_WRONG_CREDENTIALS] (state) { 19 | state.pending = false 20 | state.auth.isLoggedIn = false 21 | }, 22 | [types.LOGIN_ERROR] (state) { 23 | state.pending = false 24 | state.auth.isLoggedIn = false 25 | }, 26 | [types.LOGOUT] (state) { 27 | localStorage.removeItem('JWT') 28 | localStorage.removeItem('username') 29 | state.auth.isLoggedIn = false 30 | } 31 | } 32 | 33 | export default mutations 34 | -------------------------------------------------------------------------------- /src/main/js/src/utils/check-geolocation.js: -------------------------------------------------------------------------------- 1 | export default () => !!navigator.geolocation 2 | -------------------------------------------------------------------------------- /src/main/js/static/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagyadam2092/jwt-spring-boot-vuejs-auth/6105cba818090aeeed3f12002a8b9503c7a646a1/src/main/js/static/.gitkeep -------------------------------------------------------------------------------- /src/main/js/test/unit/.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "mocha": true 4 | }, 5 | "globals": { 6 | "expect": true, 7 | "sinon": true 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/main/js/test/unit/index.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | 3 | Vue.config.productionTip = false 4 | 5 | // require all test files (files that ends with .spec.js) 6 | const testsContext = require.context('./specs', true, /\.spec$/) 7 | testsContext.keys().forEach(testsContext) 8 | 9 | // require all src files except main.js for coverage. 10 | // you can also change this to match only the subset of files that 11 | // you want coverage for. 12 | const srcContext = require.context('../../src', true, /^\.\/(?!main(\.js)?$)/) 13 | srcContext.keys().forEach(srcContext) 14 | -------------------------------------------------------------------------------- /src/main/js/test/unit/karma.conf.js: -------------------------------------------------------------------------------- 1 | // This is a karma config file. For more details see 2 | // http://karma-runner.github.io/0.13/config/configuration-file.html 3 | // we are also using it with karma-webpack 4 | // https://github.com/webpack/karma-webpack 5 | 6 | var webpackConfig = require('../../build/webpack.test.conf') 7 | 8 | module.exports = function (config) { 9 | config.set({ 10 | // to run in additional browsers: 11 | // 1. install corresponding karma launcher 12 | // http://karma-runner.github.io/0.13/config/browsers.html 13 | // 2. add it to the `browsers` array below. 14 | browsers: ['PhantomJS'], 15 | frameworks: ['mocha', 'sinon-chai', 'phantomjs-shim'], 16 | reporters: ['spec', 'coverage'], 17 | files: ['./index.js'], 18 | preprocessors: { 19 | './index.js': ['webpack', 'sourcemap'] 20 | }, 21 | webpack: webpackConfig, 22 | webpackMiddleware: { 23 | noInfo: true 24 | }, 25 | coverageReporter: { 26 | dir: './coverage', 27 | reporters: [ 28 | { type: 'lcov', subdir: '.' }, 29 | { type: 'text-summary' } 30 | ] 31 | } 32 | }) 33 | } 34 | -------------------------------------------------------------------------------- /src/main/js/test/unit/specs/Hello.spec.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import Hello from '@/components/Hello' 3 | 4 | describe('Hello.vue', () => { 5 | it('should render correct contents', () => { 6 | const Constructor = Vue.extend(Hello) 7 | const vm = new Constructor().$mount() 8 | expect(vm.$el.querySelector('.hello h1').textContent) 9 | .to.equal('Welcome to Your Vue.js App') 10 | }) 11 | }) 12 | -------------------------------------------------------------------------------- /src/main/resources/static/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagyadam2092/jwt-spring-boot-vuejs-auth/6105cba818090aeeed3f12002a8b9503c7a646a1/src/main/resources/static/logo.png --------------------------------------------------------------------------------