Initial commit

This commit is contained in:
Damien Broqua 2023-09-23 20:54:44 +02:00
parent 9577ba4af5
commit 1bf353c150
52 changed files with 10449 additions and 0 deletions

12
.babelrc Normal file
View file

@ -0,0 +1,12 @@
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"esmodules": true
}
}
]
]
}

6
.env.example Normal file
View file

@ -0,0 +1,6 @@
NODE_ENV=development
PORT=3000
MONGODB_URI=mongodb://images-upload-db/upload
TRUST_PROXY=loopback
PAGINATION=16
SECRET=waemaeMe5ahc6ce1chaeKohKa6Io8Eik

26
.eslintrc.js Normal file
View file

@ -0,0 +1,26 @@
module.exports = {
env: {
browser: true,
es2021: true
},
extends: 'google',
overrides: [
{
env: {
node: true
},
files: [
'.eslintrc.{js,cjs}'
],
parserOptions: {
sourceType: 'script'
}
}
],
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module'
},
rules: {
}
}

2
.gitignore vendored
View file

@ -130,3 +130,5 @@ dist
.yarn/install-state.gz
.pnp.*
.DS_Store
uploads

4
.husky/pre-commit Executable file
View file

@ -0,0 +1,4 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npm run lint

40
docker-compose.yml Normal file
View file

@ -0,0 +1,40 @@
version: "2.4"
services:
images-upload-www:
container_name: images-upload-www
image: "node:18"
restart: always
user: "node"
working_dir: /home/node/app
command: >
bash -c "
npm install &&
npm run watch"
volumes:
- ./:/home/node/app
- /home/node/node_modules
ports:
- 2666:3000
depends_on:
- images-upload-db
environment:
NODE_ENV: ${NODE_ENV}
PORT: ${PORT}
MONGODB_URI: ${MONGODB_URI}
SECRET: ${SECRET}
TRUST_PROXY: ${TRUST_PROXY}
PAGINATION: ${PAGINATION}
DEBUG: "*"
networks:
- images-upload
images-upload-db:
container_name: images-upload-db
image: mongo:latest
restart: always
networks:
- images-upload
networks:
images-upload:
driver: bridge

7915
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

68
package.json Normal file
View file

@ -0,0 +1,68 @@
{
"name": "simple-images-upload",
"version": "1.0.0",
"description": "Simple application to store and share image with bbcode integration",
"main": "src/bin/www",
"scripts": {
"run:all": "npm-run-all build sass start",
"build": "npx babel ./src --out-dir dist --copy-files",
"sass": "npx sass sass/index.scss public/css/main.css -s compressed --color",
"watch": "npx nodemon -e js,scss",
"start": "node ./dist/bin/www",
"lint": "npx eslint ./src --ext .js",
"lint:fix": "npx eslint --fix ./src --ext .js",
"prepare": "husky install"
},
"repository": {
"type": "git",
"url": "git@git.darkou.fr:dbroqua/simple-images-upload.git"
},
"author": {
"name": "Damien Broqua",
"email": "contact@darkou.fr",
"url": "https://www.darkou.fr"
},
"license": "CC-BY-NC-SA-4.0",
"nodemonConfig": {
"exec": "npm run run:all",
"watch": [
"src/*",
"sass/*",
"javascripts/*"
],
"ignore": [
"**/__tests__/**",
"*.test.js",
"*.spec.js"
]
},
"devDependencies": {
"@babel/cli": "^7.22.15",
"@babel/preset-env": "^7.22.20",
"eslint": "^8.50.0",
"eslint-config-google": "^0.14.0",
"husky": "^8.0.3",
"nodemon": "^3.0.1",
"npm-run-all": "^4.1.5",
"sass": "^1.68.0"
},
"dependencies": {
"connect-ensure-login": "^0.1.1",
"connect-flash": "^0.1.1",
"connect-mongo": "^5.0.0",
"cookie-parser": "^1.4.6",
"debug": "^4.3.4",
"ejs": "^3.1.9",
"express": "^4.18.2",
"express-session": "^1.17.3",
"knacss": "^8.0.4",
"mongoose": "^7.5.2",
"mongoose-unique-validator": "^4.0.0",
"multer": "^1.4.5-lts.1",
"passport": "^0.6.0",
"passport-http": "^0.3.0",
"passport-local": "^1.0.0",
"rand-token": "^1.0.1",
"sharp": "^0.32.6"
}
}

1
public/css/main.css Normal file

File diff suppressed because one or more lines are too long

1
public/css/main.css.map Normal file

File diff suppressed because one or more lines are too long

BIN
public/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

BIN
public/img/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

97
public/js/main.js Normal file
View file

@ -0,0 +1,97 @@
let timeout = null;
/**
* Ensemble d'actions effectuées au chargement de la page
*/
document.addEventListener("DOMContentLoaded", () => {
const $navbarBurgers = Array.prototype.slice.call(
document.querySelectorAll(".navbar-burger"),
0
);
if ($navbarBurgers.length > 0) {
$navbarBurgers.forEach((el) => {
el.addEventListener("click", () => {
const { target } = el.dataset;
const $target = document.getElementById(target);
el.classList.toggle("is-active");
$target.classList.toggle("is-active");
});
});
}
});
/**
* Fonction permettant d'afficher un message dans un toastr
* @param {String} message
*/
function showToastr(message, success = false) {
const x = document.getElementById("toastr");
if (message) {
x.getElementsByTagName("SPAN")[0].innerHTML = message;
}
if (timeout) {
clearTimeout(timeout);
x.classList.remove("show");
}
x.classList.remove("success");
x.classList.remove("error");
if (success) {
x.classList.add("success");
} else {
x.classList.add("error");
}
x.classList.add("show");
timeout = setTimeout(() => {
x.classList.remove("show");
}, 3000);
}
/**
* Fonction permettant de masquer le toastr
*/
function hideToastr() {
const x = document.getElementById("toastr");
x.className = x.className.replace("show", "");
x.getElementsByTagName("SPAN")[0].innerHTML = "";
}
const copyToClipboard = (itemId, message) => {
const copyText = document.getElementById(itemId);
copyText.select();
document.execCommand('copy');
showToastr(message, true);
};
const showModale = () => {
const x = document.getElementsByClassName("modal");
x[0].classList.add('is-visible');
}
const closeModale = () => {
const x = document.getElementsByClassName("modal");
x[0].classList.remove('is-visible');
}
const displayImageDetails = (itemId) => {
const x = document.getElementById(`item-${itemId}`);
const original = x.dataset.original;
const medium = x.dataset.medium;
const small = x.dataset.small;
document.getElementById('previewImage').src = small;
document.getElementById('originalFile-0').value = original;
document.getElementById('mediumFile-0').value = medium;
document.getElementById('smallFile-0').value = small;
document.getElementById('bbcode-0').value = `[url=${original}][img]${medium}[/img][/url]`;
showModale();
}

26
sass/box.scss Normal file
View file

@ -0,0 +1,26 @@
.box {
background-color: var(--box-bg-color);
border-radius: 6px;
box-shadow: var(--box-shadow-color) 0px 3px 6px 0px;
color: var(--font-color);
display: block;
padding: 1.25rem;
width: calc(100% - 2rem);
margin: auto;
@include transition() {}
@include respond-to("small-up") {
width: 65%;
}
@include respond-to("medium-up") {
width: 35%;
}
h1 {
margin-top: 0;
}
button {
margin-top: 2rem;
}
}

63
sass/button.scss Normal file
View file

@ -0,0 +1,63 @@
.button {
cursor: pointer;
justify-content: center;
padding-bottom: calc(0.5em - 1px);
padding-left: 1em;
padding-right: 1em;
padding-top: calc(0.5em - 1px);
text-align: center;
white-space: nowrap;
border: 1px solid transparent;
margin-bottom: .5rem;
background-color: $nord9;
border-radius: 0.375rem;
color: $button-font-color;
@include transition() {}
&:hover {
background-color: darken($nord9, $hoverAmount);
}
&.is-danger {
background-color: $danger-color;
color: $button-alternate-color;
&:hover {
background-color: $danger-color-hl;
}
}
&.is-primary {
background-color: $primary-color;
&:hover {
background-color: $primary-color-hl;
}
}
&.is-warning {
background-color: $warning-color;
&:hover {
background-color: $warning-color-hl;
}
}
&.is-success {
background-color: $success-color;
&:hover {
background-color: $success-color-hl;
}
}
&.is-link {
background-color: transparent;
border-color: $nord9;
color: var(--button-link-text-color);
&:hover {
border-color: darken($nord9, $hoverAmount);
}
}
}

103
sass/colors.scss Normal file
View file

@ -0,0 +1,103 @@
$hoverAmount: 10%;
$white: #ffffff;
$darken-white: #F8F9FB;
/* Couleurs du thème Nord (https://www.nordtheme.com/) */
$nord0: #2e3440;
$nord1: #3b4252;
$nord2: #434c5e;
$nord3: #4C566A;
$nord4: #d8dee9;
$nord5: #e5e9f0;
$nord6: #eceff4;
$nord7: #8fbcbb;
$nord8: #88c0d0;
$nord9: #81a1c1;
$nord10: #5e81ac;
$nord11: #d08770;
$nord12: #bf616a;
$nord13: #ebcb8b;
$nord14: #a3be8c;
$nord15: #b48ead;
$primary-color: $nord8;
$danger-color: $nord11;
$error-color: $nord12;
$warning-color: $nord13;
$success-color: $nord14;
$primary-color-hl: darken($primary-color, $hoverAmount);
$danger-color-hl: darken($danger-color, $hoverAmount);
$error-color-hl: darken($error-color, $hoverAmount);
$warning-color-hl: darken($warning-color, $hoverAmount);
$success-color-hl: darken($success-color, $hoverAmount);
$button-font-color: #2C364A;
$button-alternate-color: #01103C;
$pagination-border-color: $nord3;
$pagination-hover-color: rgb(115, 151, 186);
:root {
--default-color: #{$white};
--bg-color: #{darken($white, 5%)};
--bg-alternate-color: #{darken($white, 8%)};
--font-color: #{$nord3};
--footer-color: #{$darken-white};
--link-color: #{$nord1};
--input-font-color: #{$nord3};
--input-color: #{$white};
--input-active-color: #{$nord5};
--navbar-color: #{darken($white, 5%)};
--box-bg-color: #F8F9FB;
--box-shadow-color: #{rgba($nord4, 0.35)};
--border-color: #{$nord4};
--button-link-text-color: #2C364A;
--loader-img: url('/img/loading-light.gif');
--nord0: #{$nord0};
--nord1: #{$nord1};
--nord2: #{$nord2};
--nord3: #{$nord3};
--nord4: #{$nord4};
--nord5: #{$nord5};
--nord6: #{$nord6};
--nord7: #{$nord7};
--nord8: #{$nord8};
--nord9: #{$nord9};
--nord10: #{$nord10};
--nord11: #{$nord11};
--nord12: #{$nord12};
--nord13: #{$nord13};
--nord14: #{$nord14};
--nord15: #{$nord15};
}
[data-theme="dark"] {
--default-color: #{$nord3};
--bg-color: #{lighten($nord0, 2%)};
--bg-alternate-color: #{lighten($nord3, 8%)};
--font-color: #{$nord6};
--footer-color: #{$nord1};
--link-color: #{$nord4};
--input-font-color: #{$nord6};
--input-color: #{$nord0};
--input-active-color: #{$nord3};
--navbar-color: #{$nord0};
--box-bg-color: #{$nord1};
--box-shadow-color: #{rgba($nord4, 0.2)};
--border-color: #{$nord1};
--button-link-text-color: #{$white};
--loader-img: url('/img/loading-dark.gif');
}

6
sass/error.scss Normal file
View file

@ -0,0 +1,6 @@
main {
&.error {
min-height: calc(100vh - 3.25rem - 100px);
padding-top: 4rem;
}
}

16
sass/fonts.scss Normal file

File diff suppressed because one or more lines are too long

147
sass/forms.scss Normal file
View file

@ -0,0 +1,147 @@
.field {
padding-top: .6rem;
display: flex;
flex-direction: column;
&.inline {
flex-direction: row;
}
&.has-addons {
display: flex;
justify-content: flex-start;
flex-direction: row;
.button {
margin-bottom: 0;
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
input {
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
}
input,
textarea,
select {
border-radius: 4px;
max-width: 100%;
width: 100%;
background-color: var(--input-color);
border: 1px solid var(--input-active-color) !important;
color: var(--input-font-color);
@include transition() {}
&:focus-visible {
outline: unset;
}
}
input[type="radio"] {
border-radius: 50%;
appearance: none;
width: 1.2rem;
height: 1.2rem;
vertical-align: text-bottom;
outline: 0;
box-shadow: inset 0 0 0 1px var(--input-active-color);
background-color: #fff;
transition: background-size .15s;
cursor: pointer;
&:checked {
box-shadow: inset 0 0 0 4px var(--input-active-color);
}
}
input[type="radio"] + label,
label + input[type="radio"] {
margin-left: 12px;
}
select {
appearance: none;
background-image: url("data:image/svg+xml,%3C%3Fxml%20version%3D%221.0%22%20standalone%3D%22no%22%3F%3E%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20xmlns%3Axlink%3D%22http%3A//www.w3.org/1999/xlink%22%20style%3D%22isolation%3Aisolate%22%20viewBox%3D%220%200%2020%2020%22%20width%3D%2220%22%20height%3D%2220%22%3E%3Cpath%20d%3D%22%20M%209.96%2011.966%20L%203.523%205.589%20C%202.464%204.627%200.495%206.842%201.505%207.771%20L%201.505%207.771%20L%208.494%2014.763%20C%209.138%2015.35%2010.655%2015.369%2011.29%2014.763%20L%2011.29%2014.763%20L%2018.49%207.771%20C%2019.557%206.752%2017.364%204.68%2016.262%205.725%20L%2016.262%205.725%20L%209.96%2011.966%20Z%20%22%20fill%3D%22inherit%22/%3E%3C/svg%3E");
background-position: right 0.8rem center;
background-repeat: no-repeat;
background-size: 1.2rem;
padding-right: 2.4rem;
}
}
.theme-switch-wrapper {
display: flex;
align-items: center;
em {
margin-left: 10px;
font-size: 1rem;
}
}
.theme-switch {
display: inline-block;
height: 34px;
position: relative;
width: 60px;
}
.theme-switch input {
display:none;
}
.slider {
background-color: #ccc;
bottom: 0;
cursor: pointer;
left: 0;
position: absolute;
right: 0;
top: 0;
transition: .4s;
@include transition() {}
}
.slider:before {
background-color: #fff;
bottom: 4px;
content: '\f185';
height: 26px;
left: 4px;
position: absolute;
transition: .4s;
width: 26px;
padding: 0;
font-family: "icon";
font-style: normal;
font-weight: normal;
display: inline-block;
text-decoration: inherit;
text-align: center;
font-variant: normal;
text-transform: none;
}
input:checked + .slider {
background-color: $primary-color;
@include transition() {}
}
input:checked + .slider:before {
transform: translateX(26px);
content: '\f186';
background-color: var(--input-active-color);
@include transition() {}
}
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}

88
sass/global.scss Normal file
View file

@ -0,0 +1,88 @@
html {
min-height: 100vh;
scroll-behavior: smooth;
body {
background-color: var(--bg-color);
display: flex;
flex-direction: column;
padding-top: 3.5rem;
font-family: 'lucioleregular';
min-height: 100vh;
color: var(--font-color);
@include transition();
footer.footer {
margin-top: auto;
padding: 2rem 0.7rem 1.5rem;
background-color: var(--footer-color);
@include transition() {}
}
a {
color: var(--link-color);
cursor: pointer;
@include transition() {}
&:hover {
color: var(--font-color);
}
}
h1,
h2,
h3,
h4,
h5,
h6 {
color: var(--font-color);
}
h1 {
margin-top: 2rem;
}
pre {
font-family: 'fira_codelight';
margin: 0.75rem 0;
padding: 0.75rem;
border-left: 2px solid $nord10;
background: var(--box-bg-color);
color: var(--font-color);
}
.image-preview {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
}
}
}
.layout-maxed {
@include respond-to("small") {
padding: 0 0.7rem;
}
}
.is-hidden {
display: none;
}
.ml-4 {
margin-left: 1rem;
}
.sm-hidden {
display: none;
@include respond-to("small-up") {
display: initial;
}
}
.is-danger {
color: $nord12;
}

34
sass/index.scss Normal file
View file

@ -0,0 +1,34 @@
// @use '../node_modules/knacss/sass/knacss.scss';
// NOYAU
@import "../node_modules/knacss/sass/abstracts/variables-sass";
@import "../node_modules/knacss/sass/abstracts/mixins-sass";
@import "../node_modules/knacss/sass/base/reset-base";
@import "../node_modules/knacss/sass/base/reset-accessibility";
@import "../node_modules/knacss/sass/base/reset-forms";
@import "../node_modules/knacss/sass/base/reset-print";
@import "../node_modules/knacss/sass/base/layout";
// UTILITAIRES
@import "../node_modules/knacss/sass/utils/utils-global";
@import "../node_modules/knacss/sass/utils/utils-font-sizes";
@import "../node_modules/knacss/sass/utils/utils-spacers";
@import "../node_modules/knacss/sass/utils/grillade";
// SPÉCIFIQUE AU SITE
@import './fonts';
@import './colors';
@import './mixin';
@import './global';
@import './navbar';
@import './forms';
@import './button';
@import './modal';
@import './toast';
@import './pagination';
@import './box';
@import './list';
@import './error';
@import './messages';

32
sass/list.scss Normal file
View file

@ -0,0 +1,32 @@
.list {
margin: 2rem 0;
.item{
padding: 0.5rem 0.75rem;
border: 2px solid var(--border-color);
background-color: var(--bg-alternate-color);
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
@include transition() {}
&:nth-child(2n) {
background-color: var(--default-color);
}
&.link {
cursor: pointer;
}
img {
border: 2px solid var(--font-color);
}
}
&.hover {
.item:hover {
background-color: var(--border-color);
}
}
}

9
sass/messages.scss Normal file
View file

@ -0,0 +1,9 @@
.message {
margin: 8px 0;
padding: 0;
font-size: 0.8rem;
&.error {
color: $error-color-hl;
}
}

4
sass/mixin.scss Normal file
View file

@ -0,0 +1,4 @@
@mixin transition() {
transition: background-color 200ms ease-in 0s, border-color 200ms ease-in 0s, box-shadow 200ms ease-in 0s, color 200ms ease-in 0s;
@content;
}

125
sass/modal.scss Normal file
View file

@ -0,0 +1,125 @@
.modal {
bottom: 0;
left: 0;
right: 0;
top: 0;
align-items: center;
display: none;
flex-direction: column;
justify-content: center;
overflow: hidden;
position: fixed;
z-index: 40;
&.is-visible {
display: flex;
}
.modal-background {
background-color: rgba(10,10,10,.86);
bottom: 0;
left: 0;
position: absolute;
right: 0;
top: 0;
}
button.close {
user-select: none;
background-color: rgba(10,10,10,.2);
border: none;
border-radius: 9999px;
cursor: pointer;
pointer-events: auto;
display: inline-block;
flex-grow: 0;
flex-shrink: 0;
font-size: 0;
height: 20px;
max-height: 20px;
max-width: 20px;
min-height: 20px;
min-width: 20px;
outline: none;
position: relative;
width: 20px;
&::before,
&::after {
background-color: var(--default-color);
content: "";
display: block;
left: 50%;
position: absolute;
top: 50%;
transform: translateX(-50%) translateY(-50%) rotate(45deg);
transform-origin: center center;
}
&::before {
height: 2px;
width: 50%;
}
&::after {
height: 50%;
width: 2px;
}
}
.modal-card {
position: relative;
width: 300px;
margin: 0 auto;
display: flex;
flex-direction: column;
max-height: calc(100vh - 40px);
overflow: hidden;
@include respond-to("small-up") {
width: 560px;
}
@include respond-to("medium-up") {
width: 980px;
}
@include respond-to("large-up") {
width: 1200;
}
header,
footer {
align-items: center;
background-color: var(--navbar-color);
display: flex;
flex-shrink: 0;
justify-content: flex-start;
padding: 0.75rem;
position: relative;
@include transition() {}
}
header {
border-bottom: 1px solid var(--border-color);
border-top-left-radius: 6px;
border-top-right-radius: 6px;
justify-content: space-between;
font-size: 1.5rem;
@include transition() {}
}
section {
background-color: var(--default-color);
flex-grow: 1;
flex-shrink: 1;
overflow: auto;
padding: 20px;
@include transition() {}
}
footer {
border-bottom-left-radius: 6px;
border-bottom-right-radius: 6px;
border-top: 1px solid var(--border-color);
.button:not(:last-child) {
margin-right: .5em;
}
}
}
}

321
sass/navbar.scss Normal file
View file

@ -0,0 +1,321 @@
.navbar {
min-height: 3.25rem;
background-color: var(--navbar-color);
box-shadow: rgba(216, 222, 233, 0.15) 0px 5px 10px 0px;
color: rgba(0,0,0,.7);
position: fixed;
z-index: 30;
top: 0;
right: 0;
left: 0;
@include transition() {}
@include respond-to("medium-up") {
min-height: 3.25rem;
align-items: stretch;
display: flex;
}
.navbar-brand {
align-items: stretch;
display: flex;
min-height: 3.25rem;
.navbar-item {
align-items: center;
display: flex;
img {
max-height: 32px;
}
span {
word-break: break-word;
color: var(--font-color);
font-size: 2rem;
line-height: 1.125;
margin-left: .5rem !important;
@include transition() {}
}
}
}
.navbar-burger {
padding: 0;
margin: 0;
font-size: 1em;
appearance: none;
background: none;
border: none;
cursor: pointer;
display: block;
height: 3.25rem;
position: relative;
width: 3.25rem;
margin-left: auto;
color: var(--font-color);
@include respond-to("medium-up") {
display: none;
}
span {
background-color: currentColor;
display: block;
height: 1px;
left: calc(50% - 8px);
position: absolute;
transform-origin: center;
transition-duration: 86ms;
transition-property: background-color,opacity,transform;
transition-timing-function: ease-out;
width: 16px;
&:nth-child(1) {
top: calc(50% - 6px);
}
&:nth-child(2) {
top: calc(50% - 1px);
}
&:nth-child(3) {
top: calc(50% + 4px);
}
}
&.is-active {
span {
&:nth-child(1) {
transform: translateY(5px) rotate(45deg);
}
&:nth-child(2) {
opacity: 0;
}
&:nth-child(3) {
transform: translateY(-5px) rotate(-45deg);
}
}
}
}
.navbar-item {
line-height: 1.5;
padding: .5rem .75rem;
position: relative;
flex-grow: 0;
flex-shrink: 0;
color: var(--font-color);
display: block;
@include transition() {}
&.has-dropdown {
padding: 0;
@include respond-to("medium-up") {
display: flex;
align-items: stretch;
color: rgba(0,0,0,.7);
.navbar-dropdown {
background-color: var(--default-color);
border-bottom-left-radius: 6px;
border-bottom-right-radius: 6px;
border-top: 2px solid var(--default-hl-color);
box-shadow: 0 8px 8px rgba(10,10,10,.1);
display: none;
font-size: .875rem;
left: 0;
min-width: 100%;
position: absolute;
top: 100%;
z-index: 20;
}
&:hover {
background-color: var(--default-color);
.navbar-link {
background-color: var(--default-hl-color);
color: rgba(0,0,0,.7);
}
.navbar-dropdown {
display: block;
}
}
}
}
@include respond-to("medium-up") {
align-items: center;
display: flex;
}
}
.navbar-link {
color: var(--font-color);
display: block;
line-height: 1.5;
padding: .5rem .75rem;
position: relative;
cursor: pointer;
padding-right: 2.5em;
@include transition() {}
@include respond-to("medium-up") {
display: flex;
align-items: center;
}
.icon {
align-items: center;
display: inline-flex;
justify-content: center;
height: 1.5rem;
width: 1.5rem;
}
&::after {
border: 3px solid transparent;
border-radius: 2px;
border-right: 0;
border-top: 0;
content: " ";
display: block;
height: .625em;
pointer-events: none;
position: absolute;
top: 50%;
transform: rotate(-45deg);
transform-origin: center;
width: .625em;
border-color: var(--secondary-color);
margin-top: -0.375em;
right: 1.125em;
@include respond-to("medium-up") {
border-color: rgba(0,0,0,.7);
}
}
}
.navbar-menu {
display: none;
background-color: var(--default-color);
box-shadow: 0 8px 16px rgba(10,10,10,.1);
padding: .5rem 0;
@include transition() {}
@include respond-to("medium") {
max-height: calc(100vh - 3.25rem);
overflow: auto;
}
@include respond-to("medium-up") {
flex-grow: 1;
flex-shrink: 0;
align-items: stretch;
display: flex;
background-color: initial;
box-shadow: none;
padding: 0;
}
&.is-active {
display: block;
}
@include respond-to("medium-up") {
.navbar-start {
justify-content: flex-start;
margin-right: auto;
align-items: stretch;
display: flex;
.navbar-item {
color: rgba(0,0,0,.7);
align-items: center;
display: flex;
}
}
.navbar-end {
justify-content: flex-end;
margin-left: auto;
align-items: stretch;
display: flex;
}
}
}
.navbar-dropdown {
font-size: .875rem;
padding-bottom: .5rem;
padding-top: .5rem;
hr {
background-color: var(--font-color);
border: none;
height: 2px;
margin: .5rem 0;
}
.navbar-item {
cursor: pointer;
padding-left: 1.5rem;
padding-right: 1.5rem;
}
@include respond-to("medium-up") {
background-color: var(--default-color);
border-bottom-left-radius: 6px;
border-bottom-right-radius: 6px;
border-top: 2px solid var(--default-hl-color);
box-shadow: 0 8px 8px rgba(10,10,10,.1);
display: none;
font-size: .875rem;
left: 0;
min-width: 100%;
position: absolute;
top: 100%;
z-index: 20;
.navbar-item {
white-space: nowrap;
padding: .375rem 1rem;
padding-right: 3rem;
}
}
}
img {
height: auto;
max-width: 100%;
}
a {
text-decoration: none;
}
.buttons {
align-items: center;
display: flex;
flex-wrap: wrap;
justify-content: flex-start;
.button {
margin-right: 0.75rem;
}
&:last-child {
margin-bottom: -0.5rem;
}
}
}
[data-theme="dark"] {
.navbar {
box-shadow: none;
}
}

69
sass/pagination.scss Normal file
View file

@ -0,0 +1,69 @@
.pagination {
font-size: 1rem;
align-items: center;
display: flex;
text-align: center;
justify-content: space-between;
margin: 0.75rem 0;
.pagination-list {
align-items: center;
display: flex;
text-align: center;
flex-wrap: wrap;
flex-grow: 1;
flex-shrink: 1;
justify-content: flex-end;
@include respond-to("small") {
justify-content: center;
}
.pagination-link {
align-items: center;
border: 1px solid transparent;
border-radius: .375em;
box-shadow: none;
display: inline-flex;
font-size: 1rem;
height: 2.5em;
justify-content: flex-start;
line-height: 1.5;
padding: calc(.5em - 1px) calc(.75em - 1px);
position: relative;
vertical-align: top;
text-decoration: none;
user-select: none;
text-align: center;
font-size: 1em;
justify-content: center;
margin: .25rem;
border-color: $pagination-border-color;
color: var(--font-color);
min-width: 2.5em;
white-space: nowrap;
@include transition() {}
&:hover {
border-color: $pagination-hover-color;
color: $pagination-hover-color;
}
&.is-disabled {
background-color: var(--default-hl-color);
border-color: var(--default-hl-color);
box-shadow: none;
color: var(--disabled-color);
opacity: .5;
}
&.is-current {
background-color: $primary-color;
border-color: $primary-color;
color: $button-font-color;
}
}
}
}

95
sass/toast.scss Normal file
View file

@ -0,0 +1,95 @@
#toastr {
visibility: hidden;
min-width: 250px;
max-width: 360px;
position: fixed;
z-index: 66;
right: 30px;
top: 30px;
font-size: 17px;
padding: 1.25rem 2.5rem 1.25rem 1.5rem;
border-radius: 6px;
&.error {
background-color: $danger-color;
color: $button-alternate-color;
}
&.success {
background-color: $success-color;
color: $button-font-color;
}
&.show {
visibility: visible;
animation: toastrFadein 0.5s, toastrFadeout 0.5s 2.5s;
}
button {
width: 20px;
font-size: 0;
height: 20px;
max-height: 20px;
max-width: 20px;
min-height: 20px;
min-width: 20px;
outline: 0;
border: none;
border-radius: 9999px;
cursor: pointer;
pointer-events: auto;
display: inline-block;
user-select: none;
right: .5rem;
position: absolute;
top: .5rem;
background-color: rgba(10, 10, 10, 0.2);
&:hover {
background-color: rgba(10,10,10,.3);
}
&::before,
&::after {
background-color: var(--default-color);
content: "";
display: block;
left: 50%;
position: absolute;
top: 50%;
transform: translateX(-50%) translateY(-50%) rotate(45deg);
transform-origin: center center;
}
&::before {
height: 2px;
width: 50%;
}
&::after {
height: 50%;
width: 2px;
}
}
}
@keyframes toastrFadein {
from {
top: 0;
opacity: 0;
}
to {
top: 30px;
opacity: 1;
}
}
@keyframes toastrFadeout {
from {
top: 30px;
opacity: 1;
}
to {
top: 0;
opacity: 0;
}
}

125
src/app.js Normal file
View file

@ -0,0 +1,125 @@
import path from 'path';
import express from 'express';
import cookieParser from 'cookie-parser';
import passport from 'passport';
import mongoose from 'mongoose';
import flash from 'connect-flash';
import session from 'express-session';
import MongoStore from 'connect-mongo';
import passportConfig from './libs/passport';
// Import des routes
import globalRoutes from './routes';
import authRoutes from './routes/auth';
import {trustProxy, env, mongoDbUri, secret} from './config';
import {isXhr, getBaseUrl} from './helpers';
// import indexmkactRouterApiV1 from "./routes/api/v1/contact";
passportConfig(passport);
mongoose.set('strictQuery', false);
mongoose
.connect(mongoDbUri, {useNewUrlParser: true, useUnifiedTopology: true})
.catch(() => {
process.exit();
});
const sess = {
cookie: {
maxAge: 86400000,
},
secret,
saveUninitialized: false,
resave: false,
store: MongoStore.create({
mongoUrl: mongoDbUri,
mongoOptions: {useNewUrlParser: true, useUnifiedTopology: true},
}),
};
const app = express();
app.set('trust proxy', trustProxy);
app.use(cookieParser());
app.use(flash());
app.use(express.json({limit: '50mb'}));
app.use(express.urlencoded({extended: false, limit: '50mb'}));
app.use(session(sess));
if (['production'].indexOf(env) !== -1) {
sess.cookie.secure = true;
/* eslint-disable func-names */
app.use((req, res, next) => {
if (req.secure) {
next();
} else {
res.redirect(`https://${req.headers.host}${req.url}`);
}
});
}
app.use(passport.initialize());
app.use(passport.session());
app.set('views', path.join(__dirname, '../views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, '../public')));
app.use('/uploads', express.static(path.join(__dirname, '../uploads')));
// Init des routes
app.use('/', globalRoutes);
app.use('/', authRoutes);
// Handle 404
app.use((req, res) => {
if (isXhr(req)) {
res.status(404).send({message: '404: Not found'});
} else {
res.status(404);
res.render('index', {
pagename: '404',
viewname: 'error',
page: {
title: '404: Cette page n\'existe pas.',
},
baseUrl: getBaseUrl(req),
params: {},
query: {},
user: req.user,
error: 'La page demandée n\'existe pas sur le server',
});
}
});
// Handle 500
app.use((error, req, res, next) => {
if (isXhr(req)) {
const {message, errorCode, date} = error;
res.status(error.errorCode || 500).send({message, errorCode, date});
} else {
console.log('ERR:', error);
res.status(error.errorCode || 500);
res.render('index', {
pagename: '500',
viewname: 'error',
page: {
title: '500: Oups… le serveur a crashé !',
},
baseUrl: getBaseUrl(req),
params: {},
query: {},
user: req.user,
error,
});
}
});
console.log('Server ready!');
export default app;

52
src/bin/www.js Normal file
View file

@ -0,0 +1,52 @@
#!/usr/bin/env node
/**
* Module dependencies.
*/
import debugLib from 'debug';
import http from 'http';
import app from '../app';
import {port} from '../config';
const debug = debugLib('simple-images-upload:server');
const server = http.createServer(app);
/**
* Event listener for HTTP server "error" event.
* @param {*} error
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
const bind = typeof port === 'string' ? `Pipe ${port}` : `Port ${port}`;
switch (error.code) {
case 'EACCES':
console.error(`${bind} requires elevated privileges`);
process.exit(1);
break;
case 'EADDRINUSE':
console.error(`${bind} is already in use`);
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
const addr = server.address();
const bind =
typeof addr === 'string' ? `pipe ${addr}` : `port ${addr.port}`;
debug(`Listening on ${bind}`);
}
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

8
src/config/index.js Normal file
View file

@ -0,0 +1,8 @@
module.exports = {
nodeEnv: process.env.NODE_ENV || 'development',
port: parseInt(process.env.PORT || '3001', 10),
trustProxy: process.env.TRUST_PROXY || 'loopback',
mongoDbUri: process.env.MONGODB_URI || 'mongodb://images-upload-db/upload',
secret: process.env.SECRET || 'waemaeMe5ahc6ce1chaeKohKa6Io8Eik',
pagination: Number(process.env.PAGINATION || 16),
};

14
src/helpers/index.js Normal file
View file

@ -0,0 +1,14 @@
export const getBaseUrl = (req) => `${req.protocol}://${req.get('host')}`;
export const isXhr = (req) => {
const is = req.xhr;
if (!is) {
for (let i = 0; i < req.rawHeaders.length; i += 1) {
if (req.rawHeaders[i].indexOf('application/json') !== -1) {
return true;
}
}
}
return is;
};

24
src/libs/Render.js Normal file
View file

@ -0,0 +1,24 @@
export default (req, res, error, page, redirectTo) => {
if (error) {
res.status(500);
return res.render('index', {
pagename: '500',
viewname: '500',
page: {
title: '500: Oups… le serveur a crashé !',
error,
},
baseUrl: '',
params: {},
query: {},
user: req.user || null,
error,
});
}
if (redirectTo) {
return res.redirect(redirectTo);
}
return res.render('index', page.render());
};

23
src/libs/error.js Normal file
View file

@ -0,0 +1,23 @@
/**
* Classe permettant la gestion des erreurs personilisées
*/
class ErrorEvent extends Error {
/**
* @param {Number} errorCode
* @param {String} title
* @param {Mixed} ...params
*/
constructor(errorCode, title, ...params) {
super(...params);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, ErrorEvent);
}
this.errorCode = parseInt(errorCode, 10);
this.title = title;
this.date = new Date();
}
}
export default ErrorEvent;

39
src/libs/format.js Normal file
View file

@ -0,0 +1,39 @@
/**
* Fonction permettant de formater une réponse basée sur la méthode utilisée
* @param {Object} req
* @param {Object} res
* @param {Object} data
*
* @return {Object}
*/
export const sendResponse = (req, res, data) => {
let status = 200;
const path = req.route.path.split('/');
switch (req.method) {
case 'GET':
// INFO: On regarde de quel type de get il s'agit (liste ou item)
if (path[path.length - 1].indexOf(':') === 0) {
// INFO: Cas d'un item
status = !data ? 404 : 200;
} else {
// INFO: Cas d'une liste
status =
data.rows === undefined || data.rows.length > 0 ? 200 : 204;
}
return res.status(status).json(data).end();
case 'PATCH':
return res.status(200).json(data).end();
case 'DELETE':
return res.status(200).json(data).end();
case 'POST':
return res.status(201).json(data).end();
default:
return res.status(500).json({message: 'Not implemented'});
}
};
export default (res, page) => {
res.status(200).render('index', page.render());
};

58
src/libs/passport.js Normal file
View file

@ -0,0 +1,58 @@
/* eslint-disable func-names */
import {Strategy as LocalStrategy} from 'passport-local';
import {BasicStrategy} from 'passport-http';
import Users from '../models/Users';
export default (passport) => {
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((user, done) => {
done(null, user);
});
passport.use(
'user',
new LocalStrategy(
{
usernameField: 'email',
passwordField: 'password',
},
(email, password, done) => {
Users.findOne({email})
.then((user) => {
if (!user || !user.validPassword(password)) {
return done(
null,
false,
{message: 'Oops! Identifiants incorrects'},
);
}
return done(null, user);
})
.catch(done);
},
),
);
passport.use(
'basic',
new BasicStrategy((email, password, done) => {
Users.findOne({email})
.then((user) => {
if (!user || !user.validPassword(password)) {
return done(
null,
false,
{message: 'Oops! Identifiants incorrects'},
);
}
return done(null, user);
})
.catch(done);
}),
);
};

39
src/middleware/Auth.js Normal file
View file

@ -0,0 +1,39 @@
import Pages from './Pages';
import Users from '../models/Users';
/**
* Classe permettant de gérer les utilisateurs
*/
class Auth extends Pages {
/**
* Méthode permettant de créer un nouvel utilisateur
* @param {Req} req
* @param {Function} callback
*
* @return {Function}
*/
async register(req) {
const {username, email, password} = req.body;
const user = new Users({
username,
email,
salt: password,
});
// user.hash = user.setPassword(password);
await user.save();
await new Promise((resolve, reject) => {
req.login(user, (errLogin) => {
if (errLogin) {
return reject(errLogin);
}
return resolve(null);
});
});
}
}
module.exports = Auth;

60
src/middleware/Pages.js Normal file
View file

@ -0,0 +1,60 @@
// import moment from 'moment';
import config from '../config';
import {getBaseUrl} from '../helpers';
/**
* Classe permettant de gérer les page du back office
*/
class Pages {
/**
* @param {Object} req
* @param {String} viewname
*/
constructor(req, viewname) {
this.req = req;
this.pageContent = {
page: {
title: null,
user: req.user || {},
header: 'partials/header',
},
viewname: `pages/${viewname}`,
baseUrl: getBaseUrl(req),
currentPage: req.originalUrl.split('?')[0],
// moment,
};
this.user = null;
this.pagename = viewname;
if (req.session && req.session.passport && req.session.passport.user) {
this.user = req.session.passport.user;
}
if (!req.query.page) {
req.query.page = 1;
}
if (!req.query.limit) {
req.query.limit = config.pagination;
}
}
/**
* Rendu de la page
* @return {Object}
*/
render() {
this.pageContent.session = this.req.session;
this.pageContent.query = this.req.query;
this.pageContent.params = this.req.params;
this.pageContent.user = this.user;
this.pageContent.pagename = this.pagename;
this.pageContent.messages = this.req.session.messages;
this.req.session.messages = [];
return this.pageContent;
}
}
module.exports = Pages;

175
src/middleware/Uploads.js Normal file
View file

@ -0,0 +1,175 @@
import fs, {copyFileSync, mkdirSync, statSync} from 'fs';
import {join, extname} from 'path';
import multer from 'multer';
import sharp from 'sharp';
import {uid} from 'rand-token';
import Pages from './Pages';
import {getBaseUrl} from '../helpers';
import {pagination} from '../config';
const checkAndCreateDirectory = async (directory) => {
try {
return statSync(directory);
} catch (err) {
if (err.errno === -2) {
mkdirSync(directory);
} else {
throw err;
}
}
return true;
};
const resizeImage = async (sourceImage, destImage, w, h) => {
return sharp(sourceImage)
.resize(w, h, {
fit: 'inside',
})
.toFile(destImage);
};
/**
* Classe permettant la gestion des images
*/
class Uploads extends Pages {
/**
* @param {Object} req
* @param {String} viewname
*/
constructor(req, viewname) {
super(req, viewname);
this.upload = multer({
storage: multer.diskStorage({}),
fileFilter(multerReq, file, cb) {
const filetypes = /jpeg|jpg|png/;
const mimetype = filetypes.test(file.mimetype);
const filExtname = filetypes.test(
extname(file.originalname).toLowerCase(),
);
if (mimetype && filExtname) {
return cb(null, true);
}
const error = 'Seuls les fichiers de type jpg et png sont acceptés';
req.session.messages.push(error);
return cb(new Error(error));
},
}).single('image');
const baseUrl = getBaseUrl(req);
this.baseUploadDir = `${__dirname}/../../uploads/`;
this.userUploadDir = join(this.baseUploadDir, req.user._id);
this.userUri = `${baseUrl}/uploads/${req.user._id}`;
}
/**
*
* @param {*} req
* @param {*} callback
*/
async postOne(req) {
await new Promise((resolve, reject) => {
this.upload(req, req.body, (err, data) => {
if (err) {
return reject(err);
}
resolve(data);
});
});
checkAndCreateDirectory(this.baseUploadDir);
checkAndCreateDirectory(this.userUploadDir);
let ext = req.file.originalname.split('.');
ext = ext[ext.length - 1];
// eslint-disable-next-line max-len
const uploadname = `${uid(4)}_${Buffer.from(req.file.originalname).toString('base64')}.${ext}`;
const originalFileName = uploadname;
const mediumFileName = `medium_${uploadname}`;
const smallFileName = `small_${uploadname}`;
copyFileSync(req.file.path, join(this.userUploadDir, originalFileName));
await resizeImage(
req.file.path,
path.join(
this.userUploadDir,
mediumFileName,
),
800,
600,
);
await resizeImage(
req.file.path,
path.join(
this.userUploadDir,
smallFileName,
),
300,
200,
);
this.pageContent.page.upload = {
originalFile: `${this.userUri}/${originalFileName}`,
mediumFile: `${this.userUri}/${mediumFileName}`,
smallFile: `${this.userUri}/${smallFileName}`,
};
return true;
}
/**
* Méthode permettant d'afficher la liste des images d'un utilisateur
* @param {Object} req
*/
async getAll(req) {
const currentPage = Number(req.query.page || 1);
const startAt = (currentPage - 1) * pagination;
const endAt = startAt + pagination;
const listOfFiles = [];
let total = 0;
checkAndCreateDirectory(this.baseUploadDir);
checkAndCreateDirectory(this.userUploadDir);
const files = fs.readdirSync(this.userUploadDir)
.map((v) => {
// eslint-disable-next-line max-len
return {name: v, time: statSync(join(this.userUploadDir, v)).mtime.getTime()};
})
.sort(function(a, b) {
return b.time - a.time;
})
.map(function(v) {
return v.name;
});
for (let i = 0; i < files.length; i += 1) {
const file = files[i];
if (file.indexOf('medium_') === 0) {
total += 1;
if (listOfFiles.length < endAt) {
listOfFiles.push({
originalFile: `${this.userUri}/${file.replace('medium_', '')}`,
mediumFile: `${this.userUri}/${file}`,
smallFile: `${this.userUri}/${file.replace('medium_', 'small_')}`,
});
}
}
}
this.pageContent.page.images = listOfFiles.slice(startAt);
this.pageContent.page.currentPage = currentPage;
// eslint-disable-next-line max-len
this.pageContent.page.totalPages = Math.floor(total / pagination) + (total % pagination > 0 ? 1 : 0);
}
}
module.exports = Uploads;

58
src/models/Users.js Normal file
View file

@ -0,0 +1,58 @@
/* eslint-disable no-invalid-this */
/* eslint-disable func-names */
import mongoose from 'mongoose';
import uniqueValidator from 'mongoose-unique-validator';
import crypto from 'crypto';
const UserSchema = new mongoose.Schema(
{
username: {
type: String,
unique: true,
required: [true, 'username-required'],
match: [/^[a-zA-Z0-9]+$/, 'username-match'],
index: true,
},
email: {
type: String,
lowercase: true,
unique: true,
required: [true, 'email-required'],
match: [/\S+@\S+\.\S+/, 'email-match'],
index: true,
},
hash: String,
salt: String,
},
{timestamps: true},
);
UserSchema.plugin(uniqueValidator, {message: 'email-dup'});
UserSchema.methods.validPassword = function(password) {
const [salt, key] = this.hash.split(':');
return key === crypto.scryptSync(password, salt, 64).toString('hex');
};
UserSchema.pre('save', function(next) {
const user = this;
if (!user.isModified('salt')) {
return next();
}
const salt = crypto.randomBytes(16).toString('hex');
return crypto.scrypt(user.salt, salt, 64, (err, derivedKey) => {
if (err) {
next(err);
}
this.salt = salt;
this.hash = `${salt}:${derivedKey.toString('hex')}`;
next();
});
});
export default mongoose.model('Users', UserSchema);

75
src/routes/auth.js Normal file
View file

@ -0,0 +1,75 @@
/* eslint-disable func-names */
import express from 'express';
import passport from 'passport';
import Pages from '../middleware/Pages';
import Auth from '../middleware/Auth';
import render from '../libs/Render';
// eslint-disable-next-line new-cap
const router = express.Router();
router
.route('/connexion')
.get((req, res) => {
const page = new Pages(req, 'connexion');
return render(req, res, null, page);
})
.post(
passport.authenticate('user', {
failureRedirect: '/connexion',
failureMessage: true,
}),
(req, res) => {
const {next, query} = req.body;
let url = `/${next}`;
if (next) {
if (query) {
const params = JSON.parse(query);
Object.keys(params).forEach((key) => {
url += `${url.indexOf('?') === -1 ? '?' : '&'}${key}=${
params[key]
}`;
});
}
return res.redirect(url);
}
return res.redirect('/');
},
);
router
.route('/inscription')
.get((req, res) => {
const page = new Pages(req, 'inscription');
return render(req, res, null, page);
})
.post(async (req, res) => {
try {
const page = new Auth(req);
await page.register(req);
return res.redirect('/');
} catch (err) {
if (err.errors) {
Object.keys(err.errors).forEach((key) => {
req.session.messages.push(err.errors[key].toString());
});
} else {
req.session.messages.push(err);
}
return res.redirect('/inscription');
}
});
router.route('/se-deconnecter').get((req, res) => {
req.session.destroy(() => {
req.logout(() =>
res.redirect('/'),
);
});
});
export default router;

44
src/routes/index.js Normal file
View file

@ -0,0 +1,44 @@
import express from 'express';
import {ensureLoggedIn} from 'connect-ensure-login';
import Uploads from '../middleware/Uploads';
import render from '../libs/Render';
// eslint-disable-next-line new-cap
const router = express.Router();
router.route('/').get(ensureLoggedIn('/connexion'), (req, res) => {
return res.redirect('/upload');
});
router
.route('/upload')
.get(ensureLoggedIn('/connexion'), (req, res) => {
const page = new Uploads(req, 'upload');
return render(req, res, null, page);
})
.post(ensureLoggedIn('/connexion'), async (req, res, next) => {
try {
const page = new Uploads(req, 'upload');
await page.postOne(req);
render(req, res, null, page);
} catch (err) {
next(err);
}
});
router.route('/gallery')
.get(ensureLoggedIn('/connexion'), async (req, res, next) => {
try {
const page = new Uploads(req, 'gallery');
await page.getAll(req);
render(req, res, null, page);
} catch (err) {
next(err);
}
});
export default router;

10
views/error.ejs Normal file
View file

@ -0,0 +1,10 @@
<main class="layout-maxed error">
<div>
<h1><%= page.title %></h1>
<% if ( process.env.NODE_ENV !== 'production' ) { %>
<div>
<pre><%= error %></pre>
</div>
<% } %>
</div>
</main>

12
views/index.ejs Normal file
View file

@ -0,0 +1,12 @@
<!doctype html>
<html lang="fr">
<%- include('partials/head', {page: page, user: user, baseUrl: baseUrl}); %>
<body class="<%= pagename %>">
<% if ( user ) { %>
<%- include('partials/header', {page: page, user: user, baseUrl: baseUrl}); %>
<% } %>
<%- include(viewname, {page: page, params: params, query: query, user: user}) %>
<%- include('partials/footer', {page: page, query: query, user: user}); %>
</body>
</html>

29
views/pages/connexion.ejs Normal file
View file

@ -0,0 +1,29 @@
<div class="box">
<form method="POST">
<h1>
Connexion
</h1>
<div class="field">
<label for="email">Adresse e-mail</label>
<input type="email" name="email" id="email" placeholder="ex : damien@darkou.fr">
</div>
<div class="field">
<label for="password">Mot de passe</label>
<input type="password" name="password" id="password" placeholder="********">
</div>
<% if ( messages ) {%>
<% for (let i = 0 ; i < messages.length ; i += 1 ) { %>
<div class="message error" role="alert">
<%= messages[i] %>
</div>
<% } %>
<% } %>
<div class="text-right mt-10">
<p>Pas encore inscrit ? <a href="/inscription">Inscrivez-vous</a></p>
</div>
<button type="submit" class="button is-primary">Connexion</button>
</form>
</div>

89
views/pages/gallery.ejs Normal file
View file

@ -0,0 +1,89 @@
<main class="layout-maxed collection" id="gallery">
<div class="grid gap-5 grid-cols-1 md:grid-cols-4 list hover">
<%
for ( let i = 0 ; i < page.images.length ; i += 1 ) {
const image = page.images[i];
%>
<div
class="item link imagesPreview"
data-toggle="modal"
id="item-<%= i %>"
data-original="<%= image.originalFile %>"
data-medium="<%= image.mediumFile %>"
data-small="<%= image.smallFile %>"
onclick="displayImageDetails('<%= i %>')"
>
<img src="<%= image.smallFile %>" alt="Image <%= i %>">
</div>
<%
}
%>
</div>
<nav class="pagination" role="navigation" aria-label="Pagination">
<ul class="pagination-list">
<% if ( page.currentPage > 1 ) { %>
<li>
<a class="pagination-link" href="?page=1" aria-label="Aller à la première page">
&laquo;
</a>
</li>
<li>
<a class="pagination-link" href="?page=<%= page.currentPage - 1 %>" aria-label="Aller à la page précédente">
&lsaquo;
</a>
</li>
<% } %>
<% for ( let i = 1 ; i <= page.totalPages ; i += 1 ) { %>
<% if (i < 2 || i > (page.totalPages - 1) || (Number(page.currentPage) - 1) <= i && Number(page.currentPage) + 1 >= i) { %>
<li>
<a class="pagination-link <%= i === page.currentPage ? 'is-current' : '' %>" href="?page=<%= i %>">
<%= i %>
</a>
</li>
<% } %>
<% if ((Number(page.currentPage) - 3 === i && Number(page.currentPage) - 2 > 1) || (Number(page.currentPage) + 2 === i && Number(page.currentPage) + 2 < page.totalPages - 1)) { %>
<li>
<a class="pagination-link is-disabled">…</a>
</li>
<% } %>
<% } %>
<% if ( page.currentPage < page.totalPages ) { %>
<li>
<a class="pagination-link" href="?page=<%= page.currentPage + 1 %>" aria-label="Aller à la page suivante">
&rsaquo;
</a>
</li>
<li>
<a class="pagination-link" href="?page=<%= page.totalPages %>" aria-label="Aller à la dernière page">
&raquo;
</a>
</li>
<% } %>
</ul>
</nav>
</main>
<div class="modal">
<div class="modal-background" onclick="closeModale()"></div>
<div class="modal-card">
<header>
<div>Détails d'une image</div>
<button aria-label="Fermer" class="close" onclick="closeModale()"></button>
</header>
<section>
<div class="grid grid-cols-1 md:grid-cols-2 gap-16">
<div class="image-preview">
<img src="" id="previewImage" alt="Image">
</div>
<div>
<%- include('../partials/file-links', {file: {}, index: 0}) %></div>
<div>
</div>
</section>
<footer>
<button class="button is-primary" onclick="closeModale()">Fermer</button>
</footer>
</div>
</div>

View file

@ -0,0 +1,54 @@
<%
const errors = {
'username-required': 'Le pseudo est requis',
'username-match': 'Ce pseudo n\'est pas autorisé',
'email-required': 'L\'email est requis',
'email-match': 'L\'email n\'est pas valide',
'email-dup': 'Cet email est déjà présent en base'
};
%>
<div class="box">
<form method="POST">
<h1>
Inscription
</h1>
<div class="field">
<label for="username">Nom d'utilisateur</label>
<input type="text" required name="username" id="username" placeholder="ex : DarKou">
<% if ( messages ) {%>
<% for (let i = 0 ; i < messages.length ; i += 1 ) { %>
<% if ( messages[i].includes('username') ) { %>
<div class="message error" role="alert">
<%= errors[messages[i]] %>
</div>
<% } %>
<% } %>
<% } %>
</div>
<div class="field">
<label for="email">Adresse e-mail</label>
<input type="email" required name="email" id="email" placeholder="ex : damien@darkou.fr">
<% if ( messages ) {%>
<% for (let i = 0 ; i < messages.length ; i += 1 ) { %>
<% if ( messages[i].includes('email') ) { %>
<div class="message error" role="alert">
<%= errors[messages[i]] %>
</div>
<% } %>
<% } %>
<% } %>
</div>
<div class="field">
<label for="password">Mot de passe</label>
<input type="password" required name="password" id="password" placeholder="********">
</div>
<div class="text-right mt-10">
Déjà inscrit ?
<a href="/connexion">Connectez-vous</a>
</div>
<button type="submit" class="button is-primary">Connexion</button>
</form>
</div>

31
views/pages/upload.ejs Normal file
View file

@ -0,0 +1,31 @@
<div class="box">
<form method="POST" enctype="multipart/form-data">
<h1>
Upload
</h1>
<div class="field">
<label for="image">Choisir une image</label>
<input
type="file"
accept="image/*"
class="custom-file-input"
id="image"
name="image"
aria-describedby="file"
/>
</div>
<button type="submit" class="button is-primary">Uploader</button>
<% if ( page.upload ) { %>
<div class="grid gap-5 grid-cols-1 md:grid-cols-2">
<div class="image-preview">
<img src="<%= page.upload.smallFile %>" alt="Miniature" />
</div>
<div>
<%- include('../partials/file-links', {file: page.upload, index: 0}) %>
</div>
</div>
<% } %>
</form>
</div>

View file

@ -0,0 +1,39 @@
<div class="field">
<label for="originalFile-<%= index %>">Taille originale</label>
<input
type="text"
name="originalFile-<%= index %>"
id="originalFile-<%= index %>"
value="<%= file.originalFile %>"
onclick="copyToClipboard('originalFile-<%= index %>', 'Lien copié')"
>
</div>
<div class="field">
<label for="mediumFile-<%= index %>">Taille moyenne (800x600)</label>
<input
type="text"
name="mediumFile-<%= index %>"
id="mediumFile-<%= index %>"
value="<%= file.mediumFile %>"
onclick="copyToClipboard('mediumFile-<%= index %>', 'Lien copié')"
>
</div>
<div class="field">
<label for="smallFile-<%= index %>">Miniature (300x200)</label>
<input
type="text"
name="smallFile-<%= index %>"
id="smallFile-<%= index %>"
value="<%= file.smallFile %>"
onclick="copyToClipboard('smallFile-<%= index %>', 'Lien copié')"
>
</div>
<div class="field">
<label for="bbcode-<%= index %>"BB Code</label>
<textarea
name="bbcode-<%= index %>"
id="bbcode-<%= index %>"
onclick="copyToClipboard('bbcode-<%= index %>', 'BB Code copié')"
rows="4"
>[url=<%= file.originalFile %>][img]<%= file.mediumFile %>[/img][/url]</textarea>
</div>

View file

@ -0,0 +1 @@
<script type="text/javascript" src="/js/main.js"></script>

10
views/partials/head.ejs Normal file
View file

@ -0,0 +1,10 @@
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><% if (page.title) { %><%= page.title %> <% } else { %> DarKou - Simple Gallery <% } %></title>
<link rel="icon" type="image/png" href="favicon.png" />
<link rel="stylesheet" href="/css/main.css" />
</head>

70
views/partials/header.ejs Normal file
View file

@ -0,0 +1,70 @@
<nav class="navbar" aria-label="Navigation principale">
<div class="navbar-brand">
<a class="navbar-item" href="/">
<img src="/img/logo.png" alt="Logo Simple Gallery">
<span>Simple Gallery</span>
</a>
<a role="button" class="navbar-burger" aria-label="Afficher le menu" aria-expanded="false" data-target="navbar">
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
</a>
</div>
<div id="navbar" class="navbar-menu">
<% if ( user ) { %>
<div class="navbar-start">
<div class="navbar-item">
<div class="buttons">
<a class="button is-primary" href="/upload">
<span>
Ajouter une image
</span>
</a>
</div>
</div>
</div>
<% } %>
<div class="navbar-end">
<% if ( user ) { %>
<div class="navbar-item has-dropdown">
<a class="navbar-link">
<span>
<%= user.username %>
</span>
</a>
<div class="navbar-dropdown">
<a class="navbar-item" href="/mon-compte">
Mon compte
</a>
<hr />
<a class="navbar-item" href="/gallery">
Mes images
</a>
</div>
</div>
<% } %>
<div class="navbar-item">
<div class="buttons">
<% if ( !user ) { %>
<a class="button is-primary" href="/connexion">
<strong>Connexion</strong>
</a>
<% } else { %>
<a class="button is-danger" href="/se-deconnecter">
Déconnexion
</a>
<% } %>
</div>
</div>
</div>
</div>
</nav>
<div id="toastr">
<button class="delete" onclick="hideToastr()" aria-label="Masquer la notification"></button>
<span></span>
</div>