Browse Source

started working on templates and api

drop_old_mail
Stephan Richter 3 years ago
parent
commit
546d3c10f3
  1. 1
      .gitignore
  2. 2
      src/main/java/de/srsoftware/widerhall/Application.java
  3. 17
      src/main/java/de/srsoftware/widerhall/Constants.java
  4. 22
      src/main/java/de/srsoftware/widerhall/Util.java
  5. 59
      src/main/java/de/srsoftware/widerhall/data/User.java
  6. 41
      src/main/java/de/srsoftware/widerhall/web/Rest.java
  7. 94
      src/main/java/de/srsoftware/widerhall/web/Web.java
  8. 7
      static/templates/css.st
  9. 8
      static/templates/index.st
  10. 24
      static/templates/js.st
  11. 10
      static/templates/listlist.st
  12. 5
      static/templates/login.st
  13. 6
      static/templates/messages.st
  14. 36
      static/templates/register.st
  15. 7
      static/templates/userinfo.st
  16. 14
      static/templates/userlist.st

1
.gitignore vendored

@ -2,3 +2,4 @@
target target
config/config.json config/config.json
*.sqlite3 *.sqlite3
jquery-3.6.0.min.js

2
src/main/java/de/srsoftware/widerhall/Application.java

@ -35,7 +35,7 @@ public class Application {
SessionHandler sh = new SessionHandler(); SessionHandler sh = new SessionHandler();
server.setConnectors(new Connector[]{connector}); server.setConnectors(new Connector[]{connector});
ServletContextHandler context = new ServletContextHandler(server, "/",sh,null,null,null); ServletContextHandler context = new ServletContextHandler(server, "/",sh,null,null,null);
context.addServlet(Rest.class,"/api"); context.addServlet(Rest.class,"/api/*");
context.addServlet(Web.class,"/web/*"); context.addServlet(Web.class,"/web/*");
server.start(); server.start();

17
src/main/java/de/srsoftware/widerhall/Constants.java

@ -1,18 +1,21 @@
package de.srsoftware.widerhall; package de.srsoftware.widerhall;
public class Constants { public class Constants {
public static final String ADMIN = "Admin";
public static final String EMAIL = "email";
public static final String ERROR = "error";
public static final String HOST = "host";
public static final String IMAPS = "imaps"; public static final String IMAPS = "imaps";
public static final String INBOX = "inbox";
public static final String INDEX = "index";
public static final String NAME = "name";
public static final String NOTES = "notes";
public static final String PASSWORD = "password";
public static final String PROTOCOL = "mail.store.protocol"; public static final String PROTOCOL = "mail.store.protocol";
public static final String HOST = "host";
public static final String USER = "user"; public static final String USER = "user";
public static final String PASSWORD = "password";
public static final String INBOX = "inbox";
public static final Object PORT = "port"; public static final Object PORT = "port";
public static final String TOKEN_URL = "token_url";
public static final String LOGIN_URL = "login_url";
public static final String BASE_URL = "base_url"; public static final String BASE_URL = "base_url";
public static final String CLIENT_ID = "client_id";
public static final String CLIENT_SECRET = "client_secret";
public static final String DB = "database"; public static final String DB = "database";
public static final String BASE = "base"; public static final String BASE = "base";
public static final String CONFIG = "configuration"; public static final String CONFIG = "configuration";

22
src/main/java/de/srsoftware/widerhall/Util.java

@ -62,4 +62,26 @@ public class Util {
public static boolean isEmail(String email) { public static boolean isEmail(String email) {
return email.matches(EMAIL_PATTERN); return email.matches(EMAIL_PATTERN);
} }
public static boolean simplePassword(String pass) {
if (pass.length() < 6) return true;
if (pass.length() < 8){
for (int i=0; i<pass.length();i++){
if (!Character.isLetterOrDigit(pass.charAt(i))) return false; // password contains special character
}
}
if (pass.length() < 10){
var digit = false;
var letter = false;
for (int i=0; i<pass.length();i++){
char c = pass.charAt(i);
if (!Character.isLetterOrDigit(c)) return false; // password contains special character
digit |= Character.isDigit(c);
letter |= Character.isLetter(c);
if (letter && digit) return false; // password contains letters and digits
}
return true;
}
return false;
}
} }

59
src/main/java/de/srsoftware/widerhall/data/User.java

@ -1,16 +1,23 @@
package de.srsoftware.widerhall.data; package de.srsoftware.widerhall.data;
import de.srsoftware.widerhall.Util; import de.srsoftware.widerhall.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
import java.security.InvalidKeyException; import java.security.InvalidKeyException;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; import java.util.Map;
import static de.srsoftware.widerhall.Util.t;
import static de.srsoftware.widerhall.data.Database.*; import static de.srsoftware.widerhall.data.Database.*;
public class User { public class User {
private static final Logger LOG = LoggerFactory.getLogger(User.class);
private static Database database = Database.open(); private static Database database = Database.open();
private String email, salt, hashedPass, name; private String email, salt, hashedPass, name;
@ -51,7 +58,50 @@ public class User {
throw new InvalidKeyException(); throw new InvalidKeyException();
} }
private static boolean noUsers() throws SQLException { public String email() {
return email;
}
public String hashedPassword() {
return hashedPass;
}
public boolean is(String test){
if (test == null) return false;
return test.equals(name) || test.equals(email);
}
public static List<User> list() {
var userList = new ArrayList<User>();
try {
var rs = database.query("SELECT * FROM Users").exec();
while (rs.next()){
var email = rs.getString(EMAIL);
var name = rs.getString(NAME);
var salt = rs.getString(SALT);
var hashedPassword = rs.getString(HASHED_PASS);
userList.add(new User(email,name,salt,hashedPassword));
}
} catch (SQLException e) {
LOG.warn("Error loading user list!",e);
}
return userList;
}
public Map<String,String> map() {
return Map.of(EMAIL,email,NAME,name);
}
private boolean matching(String password) {
return hashedPass.equals(Util.sha256(password+salt));
}
public String name() {
return name;
}
public static boolean noUsers() throws SQLException {
var rs = database.query("SELECT count(*) FROM users").exec(); var rs = database.query("SELECT count(*) FROM users").exec();
try { try {
if (rs.next()) { if (rs.next()) {
@ -63,10 +113,6 @@ public class User {
return false; return false;
} }
private boolean matching(String password) {
return hashedPass.equals(Util.sha256(password+salt));
}
private User save() throws SQLException { private User save() throws SQLException {
database.insertInto("Users") database.insertInto("Users")
.values(Map.of(EMAIL,email,NAME,name,SALT,salt,HASHED_PASS,hashedPass)) .values(Map.of(EMAIL,email,NAME,name,SALT,salt,HASHED_PASS,hashedPass))
@ -74,7 +120,4 @@ public class User {
return this; return this;
} }
public Map<String,String> map() {
return Map.of(EMAIL,email,NAME,name);
}
} }

41
src/main/java/de/srsoftware/widerhall/web/Rest.java

@ -1,5 +1,7 @@
package de.srsoftware.widerhall.web; package de.srsoftware.widerhall.web;
import de.srsoftware.widerhall.data.User;
import org.json.simple.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -8,14 +10,47 @@ import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
public class Rest extends HttpServlet { import static de.srsoftware.widerhall.Constants.*;
import static de.srsoftware.widerhall.Util.t;
public class Rest extends HttpServlet {
private static final Logger LOG = LoggerFactory.getLogger(Rest.class); private static final Logger LOG = LoggerFactory.getLogger(Rest.class);
private static final String USER_LIST = "user/list";
@Override @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getMethod(); String error = handleGet(req, resp);
LOG.debug("GET {}"+method); if (error != null) resp.sendError(400,error);
}
public String handleGet(HttpServletRequest req, HttpServletResponse resp){
Object o = req.getSession().getAttribute(USER);
JSONObject json = new JSONObject();
if (o instanceof User user){
var path = req.getPathInfo();
json.put(USER,safeMapUser(user));
path = path == null ? INDEX : path.substring(1);
switch (path) {
case USER_LIST:
json.put("users", (user.is(ADMIN) ? User.list() : List.of(user)).stream().map(Rest::safeMapUser).toList());
break;
}
} else {
json.put(ERROR,"Not logged in!");
}
try {
resp.getWriter().println(json.toJSONString());
return null;
} catch (IOException e) {
return t("Failed to handle request: {}",e.getMessage());
}
}
private static Map<String,String> safeMapUser(User user){
return Map.of(NAME,user.name(),EMAIL,user.email(),PASSWORD,user.hashedPassword() == null ? "no" : "yes");
} }
} }

94
src/main/java/de/srsoftware/widerhall/web/Web.java

@ -15,23 +15,27 @@ import javax.servlet.http.HttpServletResponse;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import static de.srsoftware.widerhall.Constants.*;
import static de.srsoftware.widerhall.Util.t; import static de.srsoftware.widerhall.Util.t;
public class Web extends HttpServlet { public class Web extends HttpServlet {
private static final Logger LOG = LoggerFactory.getLogger(Web.class); private static final Logger LOG = LoggerFactory.getLogger(Web.class);
private static final String LOGIN = "login"; private static final String LOGIN = "login";
private static final String LOGOUT = "logout";
private static final String REGISTER = "register";
private final String baseDir; private final String baseDir;
private final STGroup templates; private STGroup templates;
private static final String WEB_ROOT = "/web"; private static final String WEB_ROOT = "/web";
public Web(){ public Web(){
var config = Configuration.instance(); var config = Configuration.instance();
baseDir = config.baseDir(); baseDir = config.baseDir();
var templateDir = String.join(File.separator,baseDir,"static","templates"); loadTemplates();
templates = new STRawGroupDir(templateDir,'«','»');
} }
@Override @Override
@ -42,22 +46,44 @@ public class Web extends HttpServlet {
private String handleGet(HttpServletRequest req, HttpServletResponse resp) { private String handleGet(HttpServletRequest req, HttpServletResponse resp) {
var path = req.getPathInfo(); var path = req.getPathInfo();
path = path == null ? "index" : path.substring(1); path = path == null ? INDEX : path.substring(1);
String notes = null;
switch (path){ switch (path){
case "reload":
loadTemplates();
path = INDEX;
notes = t("Templates have been reloaded");
break;
case "css": case "css":
case "js": case "js":
case "login":
return loadTemplate(path,null,resp); return loadTemplate(path,null,resp);
case LOGIN:
try {
if (User.noUsers()) return loadTemplate(REGISTER, Map.of(NOTES,t("User database is empty. Create admin user first:")), resp);
return loadTemplate(path,null,resp);
} catch (SQLException throwables) {
return "Error reading user database!";
}
case LOGOUT:
req.getSession().invalidate();
return redirectTo(INDEX,resp);
case "jquery": case "jquery":
return loadFile("jquery-3.6.0.min.js",resp); return loadFile("jquery-3.6.0.min.js",resp);
} }
var u = req.getSession().getAttribute("user"); var o = req.getSession().getAttribute("user");
if (u instanceof User user){ if (o instanceof User user){
Map<String,Object> data = Map.of("user",user.map()); var data = new HashMap<String,Object>();
data.put(USER,user.map());
data.put(NOTES,notes);
return loadTemplate(path,data,resp); return loadTemplate(path,data,resp);
} }
return loginRedirect(resp); return redirectTo(LOGIN,resp);
}
private void loadTemplates() {
var templateDir = String.join(File.separator,baseDir,"static","templates");
templates = new STRawGroupDir(templateDir,'«','»');
} }
private String loadTemplate(String path, Map<String, ? extends Object> data, HttpServletResponse resp) { private String loadTemplate(String path, Map<String, ? extends Object> data, HttpServletResponse resp) {
@ -75,17 +101,17 @@ public class Web extends HttpServlet {
} }
private String loginRedirect(HttpServletResponse resp) { private String redirectTo(String page, HttpServletResponse resp) {
try { try {
resp.sendRedirect(String.join("/",WEB_ROOT,LOGIN)); resp.sendRedirect(String.join("/",WEB_ROOT,page));
return null; return null;
} catch (IOException e) { } catch (IOException e) {
return t("Was not able to redirect to login page: {}", e.getMessage()); return t("Was not able to redirect to {} page: {}", page, e.getMessage());
} }
} }
private String loadFile(String filename, HttpServletResponse resp) { private String loadFile(String filename, HttpServletResponse resp) {
var path = String.join(File.separator,baseDir,filename); var path = String.join(File.separator,baseDir,"static",filename);
LOG.debug("loading {}",path); LOG.debug("loading {}",path);
var file = new File(path); var file = new File(path);
if (!file.exists()) return t("File {} does not exist!",filename); if (!file.exists()) return t("File {} does not exist!",filename);
@ -106,19 +132,55 @@ public class Web extends HttpServlet {
private String handlePost(HttpServletRequest req, HttpServletResponse resp) { private String handlePost(HttpServletRequest req, HttpServletResponse resp) {
var path = req.getPathInfo(); var path = req.getPathInfo();
if (path == null) path = "/"; path = path == null ? INDEX : path.substring(1);
switch (path){ switch (path){
case "/login": case LOGIN:
return handleLogin(req,resp); return handleLogin(req,resp);
case REGISTER:
return registerUser(req,resp);
} }
return t("No handler for path {}!",path); return t("No handler for path {}!",path);
} }
private String registerUser(HttpServletRequest req, HttpServletResponse resp) {
var email = req.getParameter("email");
var pass = req.getParameter("pass");
var pass_repeat = req.getParameter("pass_repeat");
var name = req.getParameter("name");
if (email == null || email.isBlank() ||
name == null || name.isBlank() ||
pass == null || pass.isBlank() ||
pass_repeat == null || pass_repeat.isBlank()) return loadTemplate(REGISTER,Map.of(ERROR,"Fill all fields, please!",NAME,name,EMAIL,email),resp);
if (!pass.equals(pass_repeat)) return loadTemplate(REGISTER,Map.of(ERROR,"Passwords do not match!",NAME,name,EMAIL,email),resp);
if (Util.simplePassword(pass)) return loadTemplate(REGISTER,Map.of(ERROR,"Password to short or to simple!",NAME,name,EMAIL,email),resp);
try {
if (User.noUsers()) { // we are registering the first user, which is forced to be „Admin“
name = ADMIN;
} else {
if (ADMIN.equals(name)) return loadTemplate(REGISTER,Map.of(ERROR,t("Name must not be „{}“",ADMIN),NAME,name,EMAIL,email),resp);
}
} catch (SQLException e) {
return t("Failed to access user database: {}",e.getMessage());
}
try {
var user = User.create(email, name, pass);
req.getSession().setAttribute("user",user);
return redirectTo(INDEX,resp);
} catch (SQLException e) {
return t("Failed to create new user: {}",e.getMessage());
}
}
private String handleLogin(HttpServletRequest req, HttpServletResponse resp) { private String handleLogin(HttpServletRequest req, HttpServletResponse resp) {
var email = req.getParameter("email"); var email = req.getParameter("email");
var pass = req.getParameter("pass"); var pass = req.getParameter("pass");
if (email == null || pass == null) return loginRedirect(resp); if (email == null || pass == null) return loadTemplate("login", Map.of("error",t("Missing username or password!")), resp);
if (!Util.isEmail(email)) return loadTemplate("login", Map.of("error",t("'{}' is not a valid email address!",email)), resp); if (!Util.isEmail(email)) return loadTemplate("login", Map.of("error",t("'{}' is not a valid email address!",email)), resp);
try { try {
var user = User.load(email,pass); var user = User.load(email,pass);

7
static/templates/css.st

@ -18,6 +18,13 @@ h1 {
background: orange; background: orange;
} }
.notes{
display: block;
text-align: center;
background: yellow;
}
.user{ .user{
background: lime; background: lime;
float: right;
} }

8
static/templates/index.st

@ -1,3 +1,4 @@
<!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
@ -6,8 +7,9 @@
<link rel="stylesheet" href="css" /> <link rel="stylesheet" href="css" />
</head> </head>
<body> <body>
<span class="user">Logged in as <em>«data.user.name»</em></span> «userinfo()»
<h2>Users</h2> «messages()»
<h2>Lists</h2> «userlist()»
«listlist()»
</body> </body>
</html> </html>

24
static/templates/js.st

@ -1 +1,25 @@
function loadUserList(){
$.getJSON("/api/user/list", showUserList);
}
function showUserList(data){
for (let i in data.users){
let user = data.users[i];
let row = $('<tr/>');
$('<td/>').text(user.name).appendTo(row);
$('<td/>').text(user.email).appendTo(row);
$('<td/>').text(user.password).appendTo(row);
row.appendTo('#userlist');
}
if (data.user.name == 'Admin'){
$('a[href=register]').show();
} else {
$('a[href=register]').hide();
}
}
function start(){
console.log("application started");
}
$(start); // document.on ready $(start); // document.on ready

10
static/templates/listlist.st

@ -0,0 +1,10 @@
<fieldset>
<legend>List of mailinglists</legend>
<table id="listlist">
<tr>
<th>List name</th>
<th>List email</th>
<th>Details</th>
</tr>
</table>
</fieldset>

5
static/templates/login.st

@ -1,3 +1,4 @@
<!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
@ -7,9 +8,7 @@
</head> </head>
<body id="login"> <body id="login">
<h1>Widerhall login</h1> <h1>Widerhall login</h1>
«if(data.error)» «messages()»
<span class="error">«data.error»</span>
«endif»
<form method="POST"> <form method="POST">
<fieldset> <fieldset>
<legend>Login-Daten</legend> <legend>Login-Daten</legend>

6
static/templates/messages.st

@ -0,0 +1,6 @@
«if(data.error)»
<span class="error">«data.error»</span>
«endif»
«if(data.notes)»
<span class="notes">«data.notes»</span>
«endif»

36
static/templates/register.st

@ -0,0 +1,36 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="jquery"></script>
<script src="js"></script>
<link rel="stylesheet" href="css" />
</head>
<body id="login">
«userinfo()»
<h1>Widerhall user registration</h1>
«messages()»
<form method="POST" action="register">
<fieldset>
<legend>User credentials</legend>
<label>
<input type="text" name="name" value="«data.name»" id="name" />
Your name
</label>
<label>
<input type="text" name="email" value="«data.email»" id="email" />
E-Mail Address
</label>
<label>
<input type="password" name="pass" value="" id="password" />
Password
</label>
<label>
<input type="password" name="pass_repeat" value="" id="password_repeated" />
Password (repeat)
</label>
<button type="submit">Save new user</button>
</fieldset>
</form>
</body>
</html>

7
static/templates/userinfo.st

@ -0,0 +1,7 @@
«if(data.user)»
<div class="user">
Logged in as <em>«data.user.name»</em>
<a class="button" href="reload" />Reload templates</a>
<a class="button" href="logout" />Logout</a>
</div>
«endif»

14
static/templates/userlist.st

@ -0,0 +1,14 @@
<fieldset>
<legend>User list</legend>
<table id="userlist">
<tr>
<th>User name</th>
<th>Email</th>
<th>Password</th>
</tr>
</table>
<a href="register">Register new user</a>
<script type="text/javascript">
loadUserList();
</script>
</fieldset>
Loading…
Cancel
Save