From 8629bba07fdd0b396a9bdef6a0bd536d986d211e Mon Sep 17 00:00:00 2001 From: tuxmain Date: Sun, 8 Jan 2023 01:26:33 +0100 Subject: [PATCH] started implementing API --- Cargo.lock | 1 + Cargo.toml | 1 + README.md | 12 +- client/basic.html | 13 + client/js/jquery.js | 2 + client/js/webcomment.js | 50 ++ src/config.rs | 6 + src/helpers.rs | 4 +- src/main.rs | 6 +- src/server.rs | 727 +---------------------------- src/server/api.rs | 92 ++++ src/server/page.rs | 726 ++++++++++++++++++++++++++++ src/{ => server/page}/queries.rs | 0 src/{ => server/page}/templates.rs | 7 +- 14 files changed, 928 insertions(+), 719 deletions(-) create mode 100644 client/basic.html create mode 100644 client/js/jquery.js create mode 100644 client/js/webcomment.js create mode 100644 src/server/api.rs create mode 100644 src/server/page.rs rename src/{ => server/page}/queries.rs (100%) rename src/{ => server/page}/templates.rs (90%) diff --git a/Cargo.lock b/Cargo.lock index f639d11..31a3273 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3370,6 +3370,7 @@ dependencies = [ "rand_core 0.6.4", "rpassword", "serde", + "serde_json", "sha2 0.10.6", "sled", "tera", diff --git a/Cargo.toml b/Cargo.toml index db7ae3d..fae2e12 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,6 +24,7 @@ rand = "0.8.5" rand_core = { version = "0.6.4", features = ["std"] } rpassword = "7.2.0" serde = { version = "1.0.152", features = ["derive", "rc"] } +serde_json = "1.0.91" sha2 = "0.10.6" sled = "0.34.7" tera = { version = "1.17.1", features = ["builtins", "date-locale"] } diff --git a/README.md b/README.md index 3e5092b..b685d9a 100644 --- a/README.md +++ b/README.md @@ -47,9 +47,19 @@ Uses no cookie, no unique user identifier. At each mutation (i.e. new comment or However, keep in mind that if a reverse proxy (or any other intermediate tool) is used, IP addresses and other metadata may be logged somewhere. +## API + +/api/post_comment +/api/comments_by_topic +/api/edit_comment +/api/remove_comment +/api/get_comment +/api/admin/approve_comment +/api/admin/remove_comment + ## License -CopyLeft 2022 Pascal Engélibert [(why copyleft?)](https://txmn.tk/blog/why-copyleft/) +CopyLeft 2022-2023 Pascal Engélibert [(why copyleft?)](https://txmn.tk/blog/why-copyleft/) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3 of the License. diff --git a/client/basic.html b/client/basic.html new file mode 100644 index 0000000..849953a --- /dev/null +++ b/client/basic.html @@ -0,0 +1,13 @@ + + + + + Webcomment + + + + +
+ + + diff --git a/client/js/jquery.js b/client/js/jquery.js new file mode 100644 index 0000000..b061403 --- /dev/null +++ b/client/js/jquery.js @@ -0,0 +1,2 @@ +/*! jQuery v3.5.1 | (c) JS Foundation and other contributors | jquery.org/license */ +!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(C,e){"use strict";var t=[],r=Object.getPrototypeOf,s=t.slice,g=t.flat?function(e){return t.flat.call(e)}:function(e){return t.concat.apply([],e)},u=t.push,i=t.indexOf,n={},o=n.toString,v=n.hasOwnProperty,a=v.toString,l=a.call(Object),y={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType},x=function(e){return null!=e&&e===e.window},E=C.document,c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.5.1",S=function(e,t){return new S.fn.init(e,t)};function p(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp(F),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\[\\da-fA-F]{1,6}"+M+"?|\\\\([^\\r\\n\\f])","g"),ne=function(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(p.childNodes),p.childNodes),t[p.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&(T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!N[t+" "]&&(!v||!v.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&(U.test(t)||z.test(t))){(f=ee.test(t)&&ye(e.parentNode)||e)===e&&d.scope||((s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=S)),o=(l=h(t)).length;while(o--)l[o]=(s?"#"+s:":scope")+" "+xe(l[o]);c=l.join(",")}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){N(t,!0)}finally{s===S&&e.removeAttribute("id")}}}return g(t.replace($,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[S]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ve(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e.namespaceURI,n=(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:p;return r!=C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),p!=C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.scope=ce(function(e){return a.appendChild(e).appendChild(C.createElement("div")),"undefined"!=typeof e.querySelectorAll&&!e.querySelectorAll(":scope fieldset div").length}),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=S,!C.getElementsByName||!C.getElementsByName(S).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){var t;a.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+S+"-]").length||v.push("~="),(t=C.createElement("input")).setAttribute("name",""),e.appendChild(t),e.querySelectorAll("[name='']").length||v.push("\\["+M+"*name"+M+"*="+M+"*(?:''|\"\")"),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+S+"+*").length||v.push(".#.+[+~]"),e.querySelectorAll("\\\f"),v.push("[\\r\\n\\f]")}),ce(function(e){e.innerHTML="";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",F)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),y=t||K.test(a.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},D=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)==(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e==C||e.ownerDocument==p&&y(p,e)?-1:t==C||t.ownerDocument==p&&y(p,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e==C?-1:t==C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?pe(a[r],s[r]):a[r]==p?-1:s[r]==p?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if(T(e),d.matchesSelector&&E&&!N[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){N(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=m[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&m(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function D(e,n,r){return m(n)?S.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?S.grep(e,function(e){return e===n!==r}):"string"!=typeof n?S.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(S.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||j,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:q.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof S?t[0]:t,S.merge(this,S.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),N.test(r[1])&&S.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(S):S.makeArray(e,this)}).prototype=S.fn,j=S(E);var L=/^(?:parents|prev(?:Until|All))/,H={children:!0,contents:!0,next:!0,prev:!0};function O(e,t){while((e=e[t])&&1!==e.nodeType);return e}S.fn.extend({has:function(e){var t=S(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i;ce=E.createDocumentFragment().appendChild(E.createElement("div")),(fe=E.createElement("input")).setAttribute("type","radio"),fe.setAttribute("checked","checked"),fe.setAttribute("name","t"),ce.appendChild(fe),y.checkClone=ce.cloneNode(!0).cloneNode(!0).lastChild.checked,ce.innerHTML="",y.noCloneChecked=!!ce.cloneNode(!0).lastChild.defaultValue,ce.innerHTML="",y.option=!!ce.lastChild;var ge={thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};function ve(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&A(e,t)?S.merge([e],n):n}function ye(e,t){for(var n=0,r=e.length;n",""]);var me=/<|&#?\w+;/;function xe(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),p=[],d=0,h=e.length;d\s*$/g;function qe(e,t){return A(e,"table")&&A(11!==t.nodeType?t:t.firstChild,"tr")&&S(e).children("tbody")[0]||e}function Le(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function He(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Oe(e,t){var n,r,i,o,a,s;if(1===t.nodeType){if(Y.hasData(e)&&(s=Y.get(e).events))for(i in Y.remove(t,"handle events"),s)for(n=0,r=s[i].length;n").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var Ut,Xt=[],Vt=/(=)\?(?=&|$)|\?\?/;S.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Xt.pop()||S.expando+"_"+Ct.guid++;return this[e]=!0,e}}),S.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Vt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Vt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Vt,"$1"+r):!1!==e.jsonp&&(e.url+=(Et.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||S.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?S(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,Xt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((Ut=E.implementation.createHTMLDocument("").body).innerHTML="
",2===Ut.childNodes.length),S.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=N.exec(e))?[t.createElement(i[1])]:(i=xe([e],t,o),o&&o.length&&S(o).remove(),S.merge([],i.childNodes)));var r,i,o},S.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(S.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},S.expr.pseudos.animated=function(t){return S.grep(S.timers,function(e){return t===e.elem}).length},S.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=S.css(e,"position"),c=S(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=S.css(e,"top"),u=S.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,S.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):("number"==typeof f.top&&(f.top+="px"),"number"==typeof f.left&&(f.left+="px"),c.css(f))}},S.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){S.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===S.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===S.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=S(e).offset()).top+=S.css(e,"borderTopWidth",!0),i.left+=S.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-S.css(r,"marginTop",!0),left:t.left-i.left-S.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===S.css(e,"position"))e=e.offsetParent;return e||re})}}),S.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;S.fn[t]=function(e){return $(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),S.each(["top","left"],function(e,n){S.cssHooks[n]=$e(y.pixelPosition,function(e,t){if(t)return t=Be(e,n),Me.test(t)?S(e).position()[n]+"px":t})}),S.each({Height:"height",Width:"width"},function(a,s){S.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){S.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return $(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?S.css(e,t,i):S.style(e,t,n,i)},s,n?e:void 0,n)}})}),S.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){S.fn[t]=function(e){return this.on(t,e)}}),S.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),S.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){S.fn[n]=function(e,t){return 0 https://txmn.tk/blog/why-copyleft/) +This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3 of the License. +This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. +You should have received a copy of the GNU Affero General Public License along with this program. If not, see https://www.gnu.org/licenses/. +*/ + +var webcomments = {}; + +const MODE_TOPIC = 1;// param: {topic:str} + +class Webcomment { + constructor(root, api, mode, mode_param) { + this.root = root; + this.api = api; + this.mode = mode; + this.mode_param = mode_param; + + console.log("constr"); + + switch(mode) { + case MODE_TOPIC: + this.query_comments_by_topic(mode_param.topic); + break; + default: + console.log("Webcomment: invalid mode"); + } + } + + query_comments_by_topic(topic) { + console.log("query"); + $.ajax({ + method: "POST", + url: this.api+"/api/comments_by_topic", + data: JSON.stringify({ + mutation_token: "", + topic: topic, + }), + success: function(resp) { + console.log(resp); + }, + dataType: "json", + contentType: "application/json; charset=utf-8", + }); + } +} + +function webcomment_topic(root_id, api, topic) { + webcomments[root_id] = (new Webcomment(document.getElementById(root_id), api, MODE_TOPIC, {topic: topic})); +} diff --git a/src/config.rs b/src/config.rs index 061579e..91d59b3 100644 --- a/src/config.rs +++ b/src/config.rs @@ -36,6 +36,8 @@ pub struct Config { pub cookies_https_only: bool, #[serde(default = "Config::default_cookies_domain")] pub cookies_domain: Option, + #[serde(default = "Config::default_cors_allow_origin")] + pub cors_allow_origin: String, /// Format: "language_REGION" #[serde(default = "Config::default_default_lang")] pub default_lang: String, @@ -110,6 +112,9 @@ impl Config { fn default_cookies_domain() -> Option { None } + fn default_cors_allow_origin() -> String { + "*".into() + } fn default_default_lang() -> String { "en_US".into() } @@ -163,6 +168,7 @@ impl Default for Config { comment_text_max_len: Self::default_comment_text_max_len(), cookies_https_only: Self::default_cookies_https_only(), cookies_domain: Self::default_cookies_domain(), + cors_allow_origin: Self::default_cors_allow_origin(), default_lang: Self::default_default_lang(), listen: Self::default_listen(), matrix_notify: Self::default_matrix_notify(), diff --git a/src/helpers.rs b/src/helpers.rs index ee3c369..a32d494 100644 --- a/src/helpers.rs +++ b/src/helpers.rs @@ -1,4 +1,4 @@ -use crate::{config::Config, db::*, locales::Locales, queries::*}; +use crate::{config::Config, db::*, locales::Locales}; use fluent_bundle::FluentArgs; use log::error; @@ -313,7 +313,7 @@ pub fn check_comment( config: &Config, locales: &Locales, langs: &[LanguageIdentifier], - comment: &CommentForm, + comment: &crate::server::page::queries::CommentForm, errors: &mut Vec, ) { if comment.author.len() > config.comment_author_max_len { diff --git a/src/main.rs b/src/main.rs index 5e5bdef..98d0ce3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,9 +5,7 @@ mod db; mod helpers; mod locales; mod notify; -mod queries; mod server; -mod templates; use argon2::{ password_hash::{rand_core::OsRng, PasswordHasher, SaltString}, @@ -85,11 +83,11 @@ async fn main() { fn init_all( opt: cli::MainCommonOpt, subopt: cli::StartOpt, -) -> (config::Config, db::Dbs, templates::Templates) { +) -> (config::Config, db::Dbs, server::page::templates::Templates) { std::fs::create_dir_all(&opt.dir.0).expect("Cannot create dir"); let config = config::read_config(&opt.dir.0); let dbs = db::load_dbs((!subopt.tmp).then_some(&opt.dir.0)); - let templates = templates::Templates::new(&opt.dir.0, &config); + let templates = server::page::templates::Templates::new(&opt.dir.0, &config); (config, dbs, templates) } diff --git a/src/server.rs b/src/server.rs index 06a19fe..2ac5cf3 100644 --- a/src/server.rs +++ b/src/server.rs @@ -1,20 +1,16 @@ #![allow(clippy::too_many_arguments)] -use crate::{ - config::*, db::*, helpers, locales::*, notify::Notification, queries::*, templates::*, -}; +pub mod api; +pub mod page; + +use crate::{config::*, db::*, locales::*}; use argon2::{Argon2, PasswordHash, PasswordVerifier}; -use crossbeam_channel::Sender; -use fluent_bundle::FluentArgs; -use log::{error, warn}; -use tera::Context; -use unic_langid::LanguageIdentifier; pub async fn run_server( config: &'static Config, dbs: Dbs, - templates: &'static Templates, + templates: &'static page::templates::Templates, locales: &'static Locales, ) { tide::log::start(); @@ -23,711 +19,22 @@ pub async fn run_server( tokio::spawn(crate::notify::run_notifier(config, notify_recv)); let mut app = tide::new(); - app.at(&format!("{}t/:topic", config.root_url)).get({ - let dbs = dbs.clone(); - move |req: tide::Request<()>| { - let client_langs = get_client_langs(&req); - serve_comments( - req, - config, - templates, - dbs.clone(), - client_langs, - Context::new(), - 200, - ) - } - }); - app.at(&format!("{}t/:topic", config.root_url)).post({ - let dbs = dbs.clone(); - let notify_send = notify_send.clone(); - move |req: tide::Request<()>| { - handle_post_comments( - req, - config, - templates, - dbs.clone(), - locales, - notify_send.clone(), - ) - } - }); - app.at(&format!( - "{}t/:topic/edit/:comment_id/:mutation_token", - config.root_url - )) - .get({ - let dbs = dbs.clone(); - move |req: tide::Request<()>| { - let client_langs = get_client_langs(&req); - serve_edit_comment( - req, - config, - templates, - dbs.clone(), - client_langs, - Context::new(), - 200, - ) - } - }); - app.at(&format!( - "{}t/:topic/edit/:comment_id/:mutation_token", - config.root_url - )) - .post({ - let dbs = dbs.clone(); - move |req: tide::Request<()>| { - handle_post_comments( - req, - config, - templates, - dbs.clone(), - locales, - notify_send.clone(), - ) - } - }); - app.at(&format!("{}admin", config.root_url)) - .get(move |req: tide::Request<()>| { - let client_langs = get_client_langs(&req); - serve_admin_login(req, config, templates, client_langs) + + // CORS sucks + app.at(&format!("{}*", config.root_url)) + .options(|_req: tide::Request<()>| async { + Ok(tide::Response::builder(200) + .header("Access-Control-Allow-Origin", &config.cors_allow_origin) + .header("Access-Control-Allow-Headers", "*") + .build()) }); - app.at(&format!("{}admin", config.root_url)).post({ - let dbs = dbs.clone(); - move |req: tide::Request<()>| handle_post_admin(req, config, templates, dbs.clone()) - }); + + api::init_routes(&mut app, config, dbs.clone()).await; + page::init_routes(&mut app, config, dbs, templates, locales, notify_send).await; + app.listen(config.listen).await.unwrap(); } -async fn serve_edit_comment<'a>( - req: tide::Request<()>, - config: &Config, - templates: &Templates, - dbs: Dbs, - client_langs: Vec, - mut context: Context, - status_code: u16, -) -> tide::Result { - let (Ok(comment_id_str), Ok(mutation_token_str)) = (req.param("comment_id"), req.param("mutation_token")) else { - context.insert("log", &["no comment id or no token"]); - return serve_comments(req, config, templates, dbs, client_langs, context, 400).await; - }; - - let (Ok(comment_id), Ok(mutation_token)) = (CommentId::from_base64(comment_id_str), MutationToken::from_base64(mutation_token_str)) else { - context.insert("log", &["badly encoded comment id or token"]); - return serve_comments(req, config, templates, dbs, client_langs, context, 400).await; - }; - - let Some((comment, _edited_comment)) = dbs.comment.get(&comment_id).unwrap() else { - context.insert("log", &["not found comment"]); - return serve_comments(req, config, templates, dbs, client_langs, context, 404).await; - }; - - if let Err(e) = helpers::check_can_edit_comment(config, &comment, &mutation_token) { - context.insert("log", &[e]); - return serve_comments(req, config, templates, dbs, client_langs, context, 403).await; - } - - context.insert("edit_comment", &comment_id.to_base64()); - context.insert("edit_comment_mutation_token", &mutation_token.to_base64()); - context.insert("edit_comment_author", &comment.author); - context.insert("edit_comment_email", &comment.email); - context.insert("edit_comment_text", &comment.text); - - serve_comments( - req, - config, - templates, - dbs, - client_langs, - context, - status_code, - ) - .await -} - -async fn serve_comments<'a>( - req: tide::Request<()>, - config: &Config, - templates: &Templates, - dbs: Dbs, - client_langs: Vec, - mut context: Context, - status_code: u16, -) -> tide::Result { - let Ok(topic) = req.param("topic") else { - return Err(tide::Error::from_str(404, "No topic")) - }; - - let admin = req.cookie("admin").map_or(false, |psw| { - check_admin_password_hash(config, &String::from(psw.value())) - }); - - let topic_hash = TopicHash::from_topic(topic); - - context.insert("config", &config); - context.insert("admin", &admin); - let time_lang = get_time_lang(&client_langs); - context.insert( - "time_lang", - time_lang.as_ref().unwrap_or(&config.default_lang), - ); - context.insert( - "l", - &client_langs - .iter() - .map(|lang| lang.language.as_str()) - .collect::>(), - ); - - if admin { - if let Ok(query) = req.query::() { - if let Ok(comment_id) = CommentId::from_base64(&query.approve) { - helpers::approve_comment(comment_id, &dbs) - .map_err(|e| error!("Approving comment: {:?}", e)) - .ok(); - } - } - if let Ok(query) = req.query::() { - if let Ok(comment_id) = CommentId::from_base64(&query.approve_edit) { - helpers::approve_edit(comment_id, &dbs) - .map_err(|e| error!("Approving edit: {:?}", e)) - .ok(); - } - } - if let Ok(query) = req.query::() { - if let Ok(comment_id) = CommentId::from_base64(&query.remove) { - helpers::remove_comment(comment_id, &dbs) - .map_err(|e| error!("Removing comment: {:?}", e)) - .ok(); - } - } - if let Ok(query) = req.query::() { - if let Ok(comment_id) = CommentId::from_base64(&query.remove_edit) { - helpers::remove_edit(comment_id, &dbs) - .map_err(|e| error!("Removing edit: {:?}", e)) - .ok(); - } - } - if let Ok(query) = req.query::() { - if let Ok(comment_id) = CommentId::from_base64(&query.edit) { - if let Some((comment, _comment_status)) = dbs.comment.get(&comment_id).unwrap() { - context.insert("edit_comment", &comment_id.to_base64()); - context.insert("edit_comment_author", &comment.author); - context.insert("edit_comment_email", &comment.email); - context.insert("edit_comment_text", &comment.text); - } - } - } - - context.insert( - "comments_pending", - &helpers::iter_pending_comments_by_topic(topic_hash.clone(), &dbs) - .map(|(comment_id, comment, addr, comment_status)| { - if let CommentStatus::ApprovedEdited(edited_comment) = comment_status { - CommentWithId { - addr: addr.map(|addr| addr.to_string()), - author: edited_comment.author, - editable: true, - id: comment_id.to_base64(), - last_edit_time: edited_comment.last_edit_time, - needs_approval: true, - original: Some(OriginalComment { - author: comment.author, - editable: true, - last_edit_time: comment.last_edit_time, - post_time: comment.post_time, - text: comment.text, - }), - post_time: edited_comment.post_time, - text: edited_comment.text, - } - } else { - CommentWithId { - addr: addr.map(|addr| addr.to_string()), - author: comment.author, - editable: true, - id: comment_id.to_base64(), - last_edit_time: comment.last_edit_time, - needs_approval: true, - original: None, - post_time: comment.post_time, - text: comment.text, - } - } - }) - .collect::>(), - ); - } - - context.insert( - "comments", - &helpers::iter_approved_comments_by_topic(topic_hash, &dbs) - .map(|(comment_id, comment, _comment_status)| CommentWithId { - addr: None, - author: comment.author, - editable: admin, - id: comment_id.to_base64(), - last_edit_time: comment.last_edit_time, - needs_approval: false, - original: None, - post_time: comment.post_time, - text: comment.text, - }) - .collect::>(), - ); - - Ok(tide::Response::builder(status_code) - .content_type(tide::http::mime::HTML) - .body(templates.tera.render("comments.html", &context)?) - .build()) -} - -async fn serve_admin<'a>( - _req: tide::Request<()>, - config: &Config, - templates: &Templates, - dbs: Dbs, - client_langs: &[LanguageIdentifier], -) -> tide::Result { - let mut context = Context::new(); - context.insert("config", &config); - context.insert("admin", &true); - let time_lang = get_time_lang(client_langs); - context.insert( - "time_lang", - time_lang.as_ref().unwrap_or(&config.default_lang), - ); - context.insert( - "l", - &client_langs - .iter() - .map(|lang| lang.language.as_str()) - .collect::>(), - ); - - context.insert( - "comments", - &dbs.comment_pending - .iter() - .filter_map(|entry| { - let ((_topic_hash, _time, comment_id), (addr, _is_edit)) = entry - .map_err(|e| error!("Reading comment_pending: {:?}", e)) - .ok()?; - let (comment, comment_status) = dbs - .comment - .get(&comment_id) - .map_err(|e| error!("Reading comment: {:?}", e)) - .ok()? - .or_else(|| { - error!("Comment not found"); - None - })?; - if let CommentStatus::ApprovedEdited(edited_comment) = comment_status { - Some(CommentWithId { - addr: addr.map(|addr| addr.to_string()), - author: edited_comment.author, - editable: true, - id: comment_id.to_base64(), - last_edit_time: edited_comment.last_edit_time, - needs_approval: true, - original: Some(OriginalComment { - author: comment.author, - editable: true, - last_edit_time: comment.last_edit_time, - post_time: comment.post_time, - text: comment.text, - }), - post_time: edited_comment.post_time, - text: edited_comment.text, - }) - } else { - Some(CommentWithId { - addr: addr.map(|addr| addr.to_string()), - author: comment.author, - editable: true, - id: comment_id.to_base64(), - last_edit_time: comment.last_edit_time, - needs_approval: true, - original: None, - post_time: comment.post_time, - text: comment.text, - }) - } - }) - .collect::>(), - ); - - Ok(tide::Response::builder(200) - .content_type(tide::http::mime::HTML) - .body(templates.tera.render("comments.html", &context)?) - .build()) -} - -async fn serve_admin_login( - _req: tide::Request<()>, - config: &Config, - templates: &Templates, - client_langs: Vec, -) -> tide::Result { - let mut context = Context::new(); - context.insert("config", &config); - let time_lang = get_time_lang(&client_langs); - context.insert( - "time_lang", - time_lang.as_ref().unwrap_or(&config.default_lang), - ); - context.insert( - "l", - &client_langs - .iter() - .map(|lang| lang.language.as_str()) - .collect::>(), - ); - - Ok(tide::Response::builder(200) - .content_type(tide::http::mime::HTML) - .body(templates.tera.render("admin_login.html", &context)?) - .build()) -} - -async fn handle_post_comments( - mut req: tide::Request<()>, - config: &Config, - templates: &Templates, - dbs: Dbs, - locales: &Locales, - notify_send: Sender, -) -> tide::Result { - let admin = req.cookie("admin").map_or(false, |psw| { - check_admin_password_hash(config, &String::from(psw.value())) - }); - - let client_langs = get_client_langs(&req); - - let client_addr = match helpers::get_client_addr(config, &req) { - Some(Ok(addr)) => Some(addr), - Some(Err(e)) => { - warn!("Unable to parse client addr: {}", e); - None - } - None => { - warn!("No client addr"); - None - } - }; - let antispam_enabled = !admin - && config.antispam_enable - && client_addr - .as_ref() - .map_or(false, |addr| !config.antispam_whitelist.contains(addr)); - - let mut errors = Vec::new(); - let mut context = Context::new(); - - match req.body_form::().await? { - CommentQuery::NewComment(query) => { - let Ok(topic) = req.param("topic") else { - return Err(tide::Error::from_str(404, "No topic")) - }; - - helpers::check_comment(config, locales, &client_langs, &query.comment, &mut errors); - - if let Some(client_addr) = &client_addr { - if antispam_enabled { - if let Some(antispam_timeout) = - helpers::antispam_check_client_mutation(client_addr, &dbs, config).unwrap() - { - errors.push( - locales - .tr( - &client_langs, - "error-antispam", - Some(&FluentArgs::from_iter([( - "antispam_timeout", - antispam_timeout, - )])), - ) - .unwrap() - .into_owned(), - ); - } - } - } - - if errors.is_empty() { - if let Some(client_addr) = &client_addr { - if antispam_enabled { - helpers::antispam_update_client_mutation(client_addr, &dbs).unwrap(); - } - } - - let topic_hash = TopicHash::from_topic(topic); - - let time = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_secs(); - - let comment = Comment { - topic_hash, - author: if query.comment.author.is_empty() { - petname::Petnames::large().generate_one(2, " ") - } else { - query.comment.author - }, - email: if query.comment.email.is_empty() { - None - } else { - Some(query.comment.email) - }, - last_edit_time: None, - mutation_token: MutationToken::new(), - post_time: time, - text: query.comment.text, - }; - match helpers::new_pending_comment(&comment, client_addr, &dbs) { - Ok(comment_id) => { - notify_send - .send(Notification { - topic: topic.to_string(), - }) - .ok(); - context.insert( - "log", - &[locales - .tr( - &client_langs, - if config.comment_approve { - "new_comment-success_pending" - } else { - "new_comment-success" - }, - Some(&FluentArgs::from_iter([( - "edit_link", - format!( - "{}t/{}/edit/{}/{}", - &config.root_url, - topic, - comment_id.to_base64(), - comment.mutation_token.to_base64(), - ), - )])), - ) - .unwrap()], - ); - } - // TODO add message to client log and change http code - Err(e) => error!("Adding pending comment: {:?}", e), - } - } else { - context.insert("new_comment_author", &query.comment.author); - context.insert("new_comment_email", &query.comment.email); - context.insert("new_comment_text", &query.comment.text); - } - context.insert("new_comment_errors", &errors); - } - CommentQuery::EditComment(query) => { - let Ok(topic) = req.param("topic") else { - return Err(tide::Error::from_str(404, "No topic")) - }; - - let Ok(comment_id) = CommentId::from_base64(&query.id) else { - return Err(tide::Error::from_str(400, "Invalid comment id")); - }; - - let Some((old_comment, old_edited_comment)) = dbs.comment.get(&comment_id).unwrap() else { - return Err(tide::Error::from_str(404, "Not found")); - }; - - helpers::check_comment(config, locales, &client_langs, &query.comment, &mut errors); - - let mutation_token = if admin { - None - } else { - 'mutation_token: { - let Ok(mutation_token_str) = req.param("mutation_token") else { - errors.push("no mutation token".into()); - break 'mutation_token None; - }; - - let Ok(mutation_token) = MutationToken::from_base64(mutation_token_str) else { - errors.push("badly encoded token".into()); - break 'mutation_token None; - }; - - if let Err(e) = - helpers::check_can_edit_comment(config, &old_comment, &mutation_token) - { - errors.push(e.to_string()); - } - - Some(mutation_token) - } - }; - - if !admin { - if let Some(client_addr) = &client_addr { - if let Some(antispam_timeout) = - helpers::antispam_check_client_mutation(client_addr, &dbs, config).unwrap() - { - let client_langs = get_client_langs(&req); - errors.push( - locales - .tr( - &client_langs, - "error-antispam", - Some(&FluentArgs::from_iter([( - "antispam_timeout", - antispam_timeout, - )])), - ) - .unwrap() - .into_owned(), - ); - } - } - } - - if errors.is_empty() { - if !admin { - if let Some(client_addr) = &client_addr { - helpers::antispam_update_client_mutation(client_addr, &dbs).unwrap(); - } - } - - let time = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_secs(); - - let mut comment = old_comment.clone(); - - comment.author = if query.comment.author.is_empty() { - petname::Petnames::large().generate_one(2, " ") - } else { - query.comment.author - }; - comment.email = if query.comment.email.is_empty() { - None - } else { - Some(query.comment.email) - }; - comment.text = query.comment.text; - comment.last_edit_time = Some(time); - - match helpers::edit_comment( - comment_id.clone(), - old_comment, - old_edited_comment, - comment.clone(), - client_addr, - &dbs, - ) { - Ok(()) => { - context.insert( - "log", - &[locales - .tr( - &client_langs, - if config.comment_approve { - "edit_comment-success_pending" - } else { - "edit_comment-success" - }, - Some(&FluentArgs::from_iter([( - "edit_link", - format!( - "{}t/{}/edit/{}/{}", - &config.root_url, - topic, - comment_id.to_base64(), - comment.mutation_token.to_base64(), - ), - )])), - ) - .unwrap()], - ); - } - // TODO add message to client log and change http code - Err(e) => error!("Editing comment: {:?}", e), - } - } else { - context.insert("edit_comment", &comment_id.to_base64()); - if let Some(mutation_token) = &mutation_token { - context.insert("edit_comment_mutation_token", &mutation_token.to_base64()); - } - context.insert("edit_comment_author", &query.comment.author); - context.insert("edit_comment_email", &query.comment.email); - context.insert("edit_comment_text", &query.comment.text); - context.insert("edit_comment_errors", &errors); - - return serve_edit_comment(req, config, templates, dbs, client_langs, context, 400) - .await; - } - context.insert("edit_comment_errors", &errors); - } - } - serve_comments( - req, - config, - templates, - dbs, - client_langs, - context, - if errors.is_empty() { 200 } else { 400 }, - ) - .await -} - -async fn handle_post_admin( - mut req: tide::Request<()>, - config: &Config, - templates: &Templates, - dbs: Dbs, -) -> tide::Result { - if let Some(psw) = req.cookie("admin") { - if check_admin_password(config, &String::from(psw.value())).is_some() { - #[allow(clippy::match_single_binding)] - match req.body_form::().await? { - _ => { - let client_langs = get_client_langs(&req); - serve_admin(req, config, templates, dbs, &client_langs).await - } - } - } else { - let client_langs = get_client_langs(&req); - serve_admin_login(req, config, templates, client_langs).await - } - } else if let AdminQuery::Login(query) = req.body_form::().await? { - if let Some(password_hash) = check_admin_password(config, &query.psw) { - let client_langs = get_client_langs(&req); - serve_admin(req, config, templates, dbs, &client_langs) - .await - .map(|mut r| { - let mut cookie = tide::http::Cookie::new("admin", password_hash); - cookie.set_http_only(Some(true)); - cookie.set_path(config.root_url.clone()); - if let Some(domain) = &config.cookies_domain { - cookie.set_domain(domain.clone()); - } - if config.cookies_https_only { - cookie.set_secure(Some(true)); - } - r.insert_cookie(cookie); - r - }) - } else { - let client_langs = get_client_langs(&req); - serve_admin_login(req, config, templates, client_langs).await - } - } else { - let client_langs = get_client_langs(&req); - serve_admin_login(req, config, templates, client_langs).await - } -} - fn check_admin_password(config: &Config, password: &str) -> Option { let argon2 = Argon2::default(); config diff --git a/src/server/api.rs b/src/server/api.rs new file mode 100644 index 0000000..b2db1c5 --- /dev/null +++ b/src/server/api.rs @@ -0,0 +1,92 @@ +#![allow(clippy::too_many_arguments)] + +use crate::{config::*, db::*, helpers, notify::Notification}; + +use crossbeam_channel::Sender; +use log::{error, warn}; +use serde::{Deserialize, Serialize}; + +enum ApiError { + InvalidAdminPassword, +} + +pub async fn init_routes(app: &mut tide::Server<()>, config: &'static Config, dbs: Dbs) { + // TODO pagination + app.at(&format!("{}api/comments_by_topic", config.root_url)) + .post({ + let dbs = dbs.clone(); + move |req: tide::Request<()>| query_comments_by_topic(req, config, dbs.clone()) + }); +} + +#[derive(Serialize)] +struct CommentWithId { + pub addr: Option, + pub author: String, + pub editable: bool, + pub id: String, + pub last_edit_time: Option