Adding login page

Adding login page
This commit is contained in:
Jason
2020-05-12 16:36:48 +09:00
parent 1d03cbd314
commit 4638ee34d1
14 changed files with 150 additions and 11 deletions

View File

@@ -59,6 +59,11 @@
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator-core</artifactId>
@@ -181,6 +186,12 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>mockwebserver</artifactId>

View File

@@ -0,0 +1,67 @@
/*
* Copyright 2020 Jason H House
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.jasonhhouse.gaps;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private static final Logger LOGGER = LoggerFactory.getLogger(WebSecurityConfig.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/images/gaps.ico",
"/css/bootstrap.min.css",
"/css/input.min.css",
"/js/jquery-3.4.1.min.js",
"/js/bootstrap.bundle.min.js",
"/js/index.min.js",
"/images/final-2.svg").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Bean
@Override
public UserDetailsService userDetailsService() {
UUID uuid = UUID.randomUUID();
LOGGER.info("Gaps Password: " + uuid.toString());
PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
UserDetails userDetails = User.withUsername("user")
.password(encoder.encode(uuid.toString()))
.roles("USER")
.build();
return new InMemoryUserDetailsManager(userDetails);
}
}

View File

@@ -116,6 +116,15 @@ public class GapsController {
return new ModelAndView("about");
}
@RequestMapping(method = RequestMethod.GET,
value = "/login",
produces = MediaType.TEXT_HTML_VALUE)
public ModelAndView getLogin() {
LOGGER.info("getLogin()");
return new ModelAndView("login");
}
@RequestMapping(method = RequestMethod.GET,
value = "/updates",
produces = MediaType.TEXT_HTML_VALUE)

View File

@@ -43,17 +43,6 @@ public class MislabeledController {
this.plexQuery = plexQuery;
this.mislabeledService = mislabeledService;
}
/*
@RequestMapping(method = RequestMethod.GET,
value = "/{machineIdentifier}/{key}")
@ResponseBody
public ResponseEntity<MediaContainer> getPlexMovies(@PathVariable("machineIdentifier") final String machineIdentifier, @PathVariable("key") final Integer key) {
LOGGER.info("getPlexMovies( " + machineIdentifier + ", " + key + " )");
String url = generatePlexUrl(machineIdentifier, key);
MediaContainer mediaContainer = plexQuery.findAllPlexVideos(url);
return ResponseEntity.ok().body(mediaContainer);
}*/
@RequestMapping(method = RequestMethod.GET,
produces = MediaType.TEXT_HTML_VALUE)

View File

View File

@@ -0,0 +1 @@
.top-margin{margin-top:16px}.all-padding{padding:16px}.gaps-hide{display:none}.thumbnail{max-width:96px;height:auto}.bottom-margin{margin-top:16px}.word-break{word-break:break-all}.center{display:block;margin-left:auto;margin-right:auto;width:50%}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
"use strict";window.addEventListener("load",function(){var forms=document.getElementsByClassName("needs-validation");Array.prototype.filter.call(forms,function(form){form.addEventListener("submit",function(event){!1===form.checkValidity()&&(event.preventDefault(),event.stopPropagation()),form.classList.add("was-validated")},!1)})},!1);

View File

@@ -0,0 +1 @@
import{getOwnedMoviesForTable}from"/js/modules/common.min.js";let libraryTitle,noMovieContainer,movieContainer,movieSearchingContainer,plexServers,plexServer,moviesTable,libraryKey;function switchPlexLibrary(machineIdentifier,key){libraryKey=key;const plexLibrary=(plexServer=plexServers[machineIdentifier]).plexLibraries.find(plexServer=>plexServer.key===parseInt(key));libraryTitle.text(`${plexServer.friendlyName} - ${plexLibrary.title}`),moviesTable.data().clear(),moviesTable.rows().invalidate().draw(),getOwnedMoviesForTable(`/libraries/${machineIdentifier}/${libraryKey}`,movieContainer,noMovieContainer,moviesTable)}function searchForMovies(){movieSearchingContainer.show(),noMovieContainer.css({display:"none"}),moviesTable.data().clear(),$.ajax({type:"GET",url:`/plex/movies/${plexServer.machineIdentifier}/${libraryKey}`,contentType:"application/json",success:function(data){movieSearchingContainer.css({display:"none"}),moviesTable.rows.add(data).draw(),movieContainer.show(100)}})}jQuery(function($){Handlebars.registerHelper("json",function(context){return JSON.stringify(context)}),libraryTitle=$("#libraryTitle"),noMovieContainer=$("#noMovieContainer"),movieContainer=$("#movieContainer"),movieSearchingContainer=$("#movieSearchingContainer"),plexServers=JSON.parse($("#plexServers").val()),plexServer=JSON.parse($("#plexServer").val()),libraryKey=$("#libraryKey").val(),moviesTable=$("#movies").DataTable({deferRender:!0,ordering:!1,columns:[{data:"imdbId"},{data:"name"},{data:"year"},{data:"language"},{data:"overview"}],columnDefs:[{targets:[0],type:"html",searchable:!1,render:function(data,type,row){if("display"===type){row.address=plexServer.address,row.port=plexServer.port,row.plexToken=plexServer.plexToken;const plexServerCard=$("#movieCard").html();return Handlebars.compile(plexServerCard)(row)}return""}},{targets:[1,2,3,4],visible:!1}]}),getOwnedMoviesForTable(`/libraries/${plexServer.machineIdentifier}/${libraryKey}`,movieContainer,noMovieContainer,moviesTable),window.searchForMovies=searchForMovies,window.switchPlexLibrary=switchPlexLibrary});

View File

@@ -0,0 +1 @@
jQuery(function($){$("#mislabeled").DataTable({ajax:{url:"mislabeled/c51c432ae94e316d52570550f915ecbcd71bede8/1/.75",dataSrc:""},columns:[{data:"plexTitle"},{data:"filename"},{data:"percentageMatch"}],columnDefs:[{type:"string",targets:[0,1]},{targets:[2],type:"num-fmt",render:function(data,type,row){return"display"===type?Math.floor(100*row.percentageMatch)+"%":""}}]})});

View File

@@ -0,0 +1 @@
export function getOwnedMoviesForTable(url,movieContainer,noMovieContainer,moviesTable){$.ajax({type:"GET",url:url,contentType:"application/json; charset=utf-8",dataType:"json",success:function(result){40===result.code?(movieContainer.show(100),noMovieContainer.css({display:"none"}),moviesTable.rows.add(result.extras).draw()):(movieContainer.css({display:"none"}),noMovieContainer.show(100))},error:function(){movieContainer.css({display:"none"}),noMovieContainer.show(100)}})};export function getRecommendedMoviesForTable(url,movieContainer,noMovieContainer,notSearchedYetContainer,moviesTable){$.ajax({type:"GET",url:url,contentType:"application/json; charset=utf-8",dataType:"json",success:function(result){50===result.code?(movieContainer.show(100),noMovieContainer.css({display:"none"}),notSearchedYetContainer.css({display:"none"}),moviesTable.rows.add(result.extras).draw()):41===result.code?(movieContainer.css({display:"none"}),notSearchedYetContainer.css({display:"none"}),noMovieContainer.show(100)):(movieContainer.css({display:"none"}),noMovieContainer.css({display:"none"}),notSearchedYetContainer.show(100))},error:function(){movieContainer.css({display:"none"}),notSearchedYetContainer.css({display:"none"}),noMovieContainer.show(100)}})};

View File

@@ -0,0 +1 @@
export const Payload=Object.freeze({UNKNOWN_ERROR:-1,SEARCH_SUCCESSFUL:0,SEARCH_CANCELLED:1,SEARCH_FAILED:2,OWNED_MOVIES_CANNOT_BE_EMPTY:3,PLEX_CONNECTION_SUCCEEDED:10,PLEX_CONNECTION_FAILED:11,PARSING_PLEX_FAILED:12,PLEX_URL_ERROR:13,PLEX_LIBRARIES_FOUND:13,DUPLICATE_PLEX_LIBRARY:14,TMDB_KEY_VALID:20,TMDB_KEY_INVALID:21,TMDB_CONNECTION_ERROR:22,TMDB_KEY_SAVE_SUCCESSFUL:23,TMDB_KEY_SAVE_UNSUCCESSFUL:24,NUKE_SUCCESSFUL:30,NUKE_UNSUCCESSFUL:31,PLEX_LIBRARY_MOVIE_FOUND:40,PLEX_LIBRARY_MOVIE_NOT_FOUND:41,RECOMMENDED_MOVIES_FOUND:50,RECOMMENDED_MOVIES_NOT_FOUND:51});

View File

@@ -0,0 +1 @@
import{getRecommendedMoviesForTable}from"/js/modules/common.js";import{Payload}from"/js/modules/payload.js";let libraryTitle,notSearchedYetContainer,movieContainer,searchContainer,noMovieContainer,movieSearchingContainer,plexServers,plexServer,moviesTable,libraryKey,stompClient,backButton,searchResults,searchTitle,searchDescription,movieCounter;function switchPlexLibrary(machineIdentifier,key){libraryKey=key;const plexLibrary=(plexServer=plexServers[machineIdentifier]).plexLibraries.find(plexServer=>plexServer.key===parseInt(key));libraryTitle.text(`${plexServer.friendlyName} - ${plexLibrary.title}`),notSearchedYetContainer.css({display:"none"}),moviesTable.data().clear(),moviesTable.rows().invalidate().draw(),getRecommendedMoviesForTable(`/recommended/${machineIdentifier}/${libraryKey}`,movieContainer,noMovieContainer,notSearchedYetContainer,moviesTable)}function cancel(){stompClient.send(`/recommended/cancel/${plexServer.machineIdentifier}/${libraryKey}`),location.assign("/")}function setCopyToClipboardEnabled(bool){bool?$("#copyToClipboard").removeClass("disabled"):$("#copyToClipboard").addClass("disabled")}function searchForMovies(){movieContainer.show(100),searchContainer.show(100),notSearchedYetContainer.css({display:"none"}),noMovieContainer.css({display:"none"}),moviesTable.data().clear(),moviesTable.rows().invalidate().draw(),movieCounter=0,searchTitle.text("Searching for Movies"),searchDescription.text("Gaps is looking through your Plex libraries. This could take a while so just sit tight, and we'll find all the missing movies for you."),$.ajax({type:"PUT",url:`/recommended/find/${plexServer.machineIdentifier}/${libraryKey}`,contentType:"application/json"}),showSearchStatus()}function disconnect(){null!==stompClient&&stompClient.disconnect(),console.log("Disconnected")}function showSearchStatus(obj){if(obj){obj.percentage=Math.trunc(obj.searchedMovieCount/obj.totalMovieCount*100);const plexServerCard=$("#updateSearchDescription").html(),theTemplate=Handlebars.compile(plexServerCard);searchDescription.html(theTemplate(obj))}else searchDescription.html("")}function copy(arr){const stringified=arr.join("\r\n");$("<input>").val(stringified).appendTo("body").select(),document.execCommand("copy")}function copyToClipboard(){copy(searchResults),$("#copiedToClipboard").show()}jQuery(function($){Handlebars.registerHelper("json",function(context){return JSON.stringify(context)}),libraryTitle=$("#libraryTitle"),notSearchedYetContainer=$("#notSearchedYetContainer"),movieContainer=$("#movieContainer"),noMovieContainer=$("#noMovieContainer"),movieSearchingContainer=$("#movieSearchingContainer"),plexServers=JSON.parse($("#plexServers").val()),plexServer=JSON.parse($("#plexServer").val()),libraryKey=$("#libraryKey").val(),backButton=$("#cancel"),searchResults=[],searchContainer=$("#searchContainer"),searchTitle=$("#searchTitle"),searchDescription=$("#searchDescription"),moviesTable=$("#movies").DataTable({deferRender:!0,ordering:!1,columns:[{data:"imdbId"},{data:"name"},{data:"year"},{data:"language"},{data:"overview"}],columnDefs:[{targets:[0],type:"html",searchable:!1,render:function(data,type,row){if("display"===type){row.address=plexServer.address,row.port=plexServer.port,row.plexToken=plexServer.plexToken;const plexServerCard=$("#movieCard").html();return Handlebars.compile(plexServerCard)(row)}return""}},{targets:[1,2,3,4],visible:!1}]}),getRecommendedMoviesForTable(`/recommended/${plexServer.machineIdentifier}/${libraryKey}`,movieContainer,noMovieContainer,notSearchedYetContainer,moviesTable);const socket=new SockJS("/gs-guide-websocket");(stompClient=Stomp.over(socket)).connect({},function(){stompClient.subscribe("/finishedSearching",function(message){searchContainer.css({display:"none"});const payload=JSON.parse(message.body);backButton.text("Restart"),payload&&payload.code===Payload.SEARCH_SUCCESSFUL?(searchTitle.text("Search Complete"),searchDescription.text(`${movieCounter} movies to add to complete your collections. Below is everything Gaps found that is missing from your movie collections.`),setCopyToClipboardEnabled(!0)):(searchTitle.text("Search Failed"),searchDescription.text(payload.reason),setCopyToClipboardEnabled(!1),movieContainer.css({display:"none"}),notSearchedYetContainer.css({display:"none"}),noMovieContainer.show(100))}),stompClient.subscribe("/newMovieFound",function(status){const obj=JSON.parse(status.body);showSearchStatus(obj),obj.nextMovie&&(movieCounter++,moviesTable.row.add(obj.nextMovie).draw(),searchResults.push(`${obj.nextMovie.name} (${obj.nextMovie.year}) in collection '${obj.nextMovie.collection}'`))})}),window.searchForMovies=searchForMovies,window.cancel=cancel,window.switchPlexLibrary=switchPlexLibrary,window.copyToClipboard=copyToClipboard}),window.onbeforeunload=function(){disconnect()};

View File

@@ -0,0 +1,55 @@
<!--
- Copyright 2020 Jason H House
-
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-->
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Gaps</title>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
<link href="/images/gaps.ico" rel="shortcut icon"/>
<link href="/css/bootstrap.min.css" rel="stylesheet"/>
<link href="/css/input.min.css" rel="stylesheet">
<!--Let browser know website is optimized for mobile-->
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<a class="navbar-brand" href="/">Gaps</a>
</nav>
<div class="container bottom-margin">
<img src="/images/final-2.svg" alt="Gaps Logo" style="width:50%;height:50%;" class="center">
<div th:if="${param.error}">
Invalid username and password.
</div>
<div th:if="${param.logout}">
You have been logged out.
</div>
<form th:action="@{/login}" method="post">
<div class="form-group">
<label for="username">Username</label>
<input id="username" type="text" class="form-control" name="username"/>
</div>
<div class="form-group">
<label for="password">Password</label>
<input id="password" type="password" class="form-control" name="password"/>
</div>
<button type="submit" class="btn btn-primary">Log In</button>
</form>
</div>
<script src="/js/jquery-3.4.1.min.js" type="text/javascript"></script>
<script src="/js/bootstrap.bundle.min.js" type="text/javascript"></script>
<script src="/js/index.min.js" type="text/javascript"></script>
</body>
</html>