basic sign in, sign up and sign out.

main
bog 2024-02-07 18:09:07 +01:00
parent 690067b841
commit 9c9e3cf6f0
38 changed files with 1216 additions and 596 deletions

3
.gitignore vendored
View File

@ -1,4 +1,5 @@
*~* *~*
*\#* *\#*
__pycache__ __pycache__
db.sqlite3 db.sqlite3
staticfiles

View File

@ -3,9 +3,13 @@ FROM python
WORKDIR app WORKDIR app
COPY . . COPY . .
ENV PYTHONUNBUFFERED=1
EXPOSE 8000 EXPOSE 8000
CMD pip install -r requirements.txt && \ CMD pip install -r requirements.txt ; \
python manage.py migrate && \ python manage.py makemigrations ; \
python manage.py collectstatic --noinput && \ python manage.py migrate ; \
python manage.py shell < create_admin.py ; \
python manage.py collectstatic --noinput ; \
python manage.py runserver 0.0.0.0:8000 python manage.py runserver 0.0.0.0:8000

View File

@ -6,4 +6,4 @@ WORKDIR app
COPY . . COPY . .
EXPOSE 3000 EXPOSE 3000
CMD npm run build && serve -s build CMD npm install && npm run build && serve -s build

188
app/package-lock.json generated
View File

@ -8,12 +8,21 @@
"name": "app", "name": "app",
"version": "0.1.0", "version": "0.1.0",
"dependencies": { "dependencies": {
"@fortawesome/fontawesome-svg-core": "^6.5.1",
"@fortawesome/free-brands-svg-icons": "^6.5.1",
"@fortawesome/free-regular-svg-icons": "^6.5.1",
"@fortawesome/free-solid-svg-icons": "^6.5.1",
"@fortawesome/react-fontawesome": "^0.2.0",
"@reduxjs/toolkit": "^2.1.0",
"@testing-library/jest-dom": "^5.17.0", "@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0", "@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0", "@testing-library/user-event": "^13.5.0",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"react-redux": "^9.1.0",
"react-scripts": "5.0.1", "react-scripts": "5.0.1",
"redux-thunk": "^3.1.0",
"sass": "^1.70.0",
"web-vitals": "^2.1.4" "web-vitals": "^2.1.4"
} }
}, },
@ -2376,6 +2385,75 @@
"node": "^12.22.0 || ^14.17.0 || >=16.0.0" "node": "^12.22.0 || ^14.17.0 || >=16.0.0"
} }
}, },
"node_modules/@fortawesome/fontawesome-common-types": {
"version": "6.5.1",
"resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-common-types/-/fontawesome-common-types-6.5.1.tgz",
"integrity": "sha512-GkWzv+L6d2bI5f/Vk6ikJ9xtl7dfXtoRu3YGE6nq0p/FFqA1ebMOAWg3XgRyb0I6LYyYkiAo+3/KrwuBp8xG7A==",
"hasInstallScript": true,
"engines": {
"node": ">=6"
}
},
"node_modules/@fortawesome/fontawesome-svg-core": {
"version": "6.5.1",
"resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-svg-core/-/fontawesome-svg-core-6.5.1.tgz",
"integrity": "sha512-MfRCYlQPXoLlpem+egxjfkEuP9UQswTrlCOsknus/NcMoblTH2g0jPrapbcIb04KGA7E2GZxbAccGZfWoYgsrQ==",
"hasInstallScript": true,
"dependencies": {
"@fortawesome/fontawesome-common-types": "6.5.1"
},
"engines": {
"node": ">=6"
}
},
"node_modules/@fortawesome/free-brands-svg-icons": {
"version": "6.5.1",
"resolved": "https://registry.npmjs.org/@fortawesome/free-brands-svg-icons/-/free-brands-svg-icons-6.5.1.tgz",
"integrity": "sha512-093l7DAkx0aEtBq66Sf19MgoZewv1zeY9/4C7vSKPO4qMwEsW/2VYTUTpBtLwfb9T2R73tXaRDPmE4UqLCYHfg==",
"hasInstallScript": true,
"dependencies": {
"@fortawesome/fontawesome-common-types": "6.5.1"
},
"engines": {
"node": ">=6"
}
},
"node_modules/@fortawesome/free-regular-svg-icons": {
"version": "6.5.1",
"resolved": "https://registry.npmjs.org/@fortawesome/free-regular-svg-icons/-/free-regular-svg-icons-6.5.1.tgz",
"integrity": "sha512-m6ShXn+wvqEU69wSP84coxLbNl7sGVZb+Ca+XZq6k30SzuP3X4TfPqtycgUh9ASwlNh5OfQCd8pDIWxl+O+LlQ==",
"hasInstallScript": true,
"dependencies": {
"@fortawesome/fontawesome-common-types": "6.5.1"
},
"engines": {
"node": ">=6"
}
},
"node_modules/@fortawesome/free-solid-svg-icons": {
"version": "6.5.1",
"resolved": "https://registry.npmjs.org/@fortawesome/free-solid-svg-icons/-/free-solid-svg-icons-6.5.1.tgz",
"integrity": "sha512-S1PPfU3mIJa59biTtXJz1oI0+KAXW6bkAb31XKhxdxtuXDiUIFsih4JR1v5BbxY7hVHsD1RKq+jRkVRaf773NQ==",
"hasInstallScript": true,
"dependencies": {
"@fortawesome/fontawesome-common-types": "6.5.1"
},
"engines": {
"node": ">=6"
}
},
"node_modules/@fortawesome/react-fontawesome": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/@fortawesome/react-fontawesome/-/react-fontawesome-0.2.0.tgz",
"integrity": "sha512-uHg75Rb/XORTtVt7OS9WoK8uM276Ufi7gCzshVWkUJbHhh3svsUUeqXerrM96Wm7fRiDzfKRwSoahhMIkGAYHw==",
"dependencies": {
"prop-types": "^15.8.1"
},
"peerDependencies": {
"@fortawesome/fontawesome-svg-core": "~1 || ~6",
"react": ">=16.3"
}
},
"node_modules/@humanwhocodes/config-array": { "node_modules/@humanwhocodes/config-array": {
"version": "0.11.14", "version": "0.11.14",
"resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.14.tgz", "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.14.tgz",
@ -3352,6 +3430,38 @@
} }
} }
}, },
"node_modules/@reduxjs/toolkit": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/@reduxjs/toolkit/-/toolkit-2.1.0.tgz",
"integrity": "sha512-nfJ/b4ZhzUevQ1ZPKjlDL6CMYxO4o7ZL7OSsvSOxzT/EN11LsBDgTqP7aedHtBrFSVoK7oTP1SbMWUwGb30NLg==",
"dependencies": {
"immer": "^10.0.3",
"redux": "^5.0.1",
"redux-thunk": "^3.1.0",
"reselect": "^5.0.1"
},
"peerDependencies": {
"react": "^16.9.0 || ^17.0.0 || ^18",
"react-redux": "^7.2.1 || ^8.1.3 || ^9.0.0"
},
"peerDependenciesMeta": {
"react": {
"optional": true
},
"react-redux": {
"optional": true
}
}
},
"node_modules/@reduxjs/toolkit/node_modules/immer": {
"version": "10.0.3",
"resolved": "https://registry.npmjs.org/immer/-/immer-10.0.3.tgz",
"integrity": "sha512-pwupu3eWfouuaowscykeckFmVTpqbzW+rXFCX8rQLkZzM9ftBmU/++Ra+o+L27mz03zJTlyV4UUr+fdKNffo4A==",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/immer"
}
},
"node_modules/@rollup/plugin-babel": { "node_modules/@rollup/plugin-babel": {
"version": "5.3.1", "version": "5.3.1",
"resolved": "https://registry.npmjs.org/@rollup/plugin-babel/-/plugin-babel-5.3.1.tgz", "resolved": "https://registry.npmjs.org/@rollup/plugin-babel/-/plugin-babel-5.3.1.tgz",
@ -4547,6 +4657,11 @@
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
"integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==" "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw=="
}, },
"node_modules/@types/use-sync-external-store": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.3.tgz",
"integrity": "sha512-EwmlvuaxPNej9+T4v5AuBPJa2x2UOJVdjCtDHgcDqitUeOtjnJKJ+apYjVcAoBEMjKW1VVFGZLUb5+qqa09XFA=="
},
"node_modules/@types/ws": { "node_modules/@types/ws": {
"version": "8.5.10", "version": "8.5.10",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.10.tgz", "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.10.tgz",
@ -9400,6 +9515,11 @@
"url": "https://opencollective.com/immer" "url": "https://opencollective.com/immer"
} }
}, },
"node_modules/immutable": {
"version": "4.3.5",
"resolved": "https://registry.npmjs.org/immutable/-/immutable-4.3.5.tgz",
"integrity": "sha512-8eabxkth9gZatlwl5TBuJnCsoTADlL6ftEr7A4qgdaTsPyreilDSnUk57SO+jfKcNtxPa22U5KK6DSeAYhpBJw=="
},
"node_modules/import-fresh": { "node_modules/import-fresh": {
"version": "3.3.0", "version": "3.3.0",
"resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz", "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz",
@ -14952,6 +15072,32 @@
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
"integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==" "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w=="
}, },
"node_modules/react-redux": {
"version": "9.1.0",
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.1.0.tgz",
"integrity": "sha512-6qoDzIO+gbrza8h3hjMA9aq4nwVFCKFtY2iLxCtVT38Swyy2C/dJCGBXHeHLtx6qlg/8qzc2MrhOeduf5K32wQ==",
"dependencies": {
"@types/use-sync-external-store": "^0.0.3",
"use-sync-external-store": "^1.0.0"
},
"peerDependencies": {
"@types/react": "^18.2.25",
"react": "^18.0",
"react-native": ">=0.69",
"redux": "^5.0.0"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"react-native": {
"optional": true
},
"redux": {
"optional": true
}
}
},
"node_modules/react-refresh": { "node_modules/react-refresh": {
"version": "0.11.0", "version": "0.11.0",
"resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.11.0.tgz", "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.11.0.tgz",
@ -15087,6 +15233,19 @@
"node": ">=8" "node": ">=8"
} }
}, },
"node_modules/redux": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz",
"integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w=="
},
"node_modules/redux-thunk": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/redux-thunk/-/redux-thunk-3.1.0.tgz",
"integrity": "sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw==",
"peerDependencies": {
"redux": "^5.0.0"
}
},
"node_modules/reflect.getprototypeof": { "node_modules/reflect.getprototypeof": {
"version": "1.0.5", "version": "1.0.5",
"resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.5.tgz", "resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.5.tgz",
@ -15233,6 +15392,11 @@
"resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz",
"integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==" "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ=="
}, },
"node_modules/reselect": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/reselect/-/reselect-5.1.0.tgz",
"integrity": "sha512-aw7jcGLDpSgNDyWBQLv2cedml85qd95/iszJjN988zX1t7AVRJi19d9kto5+W7oCfQ94gyo40dVbT6g2k4/kXg=="
},
"node_modules/resolve": { "node_modules/resolve": {
"version": "1.22.8", "version": "1.22.8",
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.8.tgz", "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.8.tgz",
@ -15521,6 +15685,22 @@
"resolved": "https://registry.npmjs.org/sanitize.css/-/sanitize.css-13.0.0.tgz", "resolved": "https://registry.npmjs.org/sanitize.css/-/sanitize.css-13.0.0.tgz",
"integrity": "sha512-ZRwKbh/eQ6w9vmTjkuG0Ioi3HBwPFce0O+v//ve+aOq1oeCy7jMV2qzzAlpsNuqpqCBjjriM1lbtZbF/Q8jVyA==" "integrity": "sha512-ZRwKbh/eQ6w9vmTjkuG0Ioi3HBwPFce0O+v//ve+aOq1oeCy7jMV2qzzAlpsNuqpqCBjjriM1lbtZbF/Q8jVyA=="
}, },
"node_modules/sass": {
"version": "1.70.0",
"resolved": "https://registry.npmjs.org/sass/-/sass-1.70.0.tgz",
"integrity": "sha512-uUxNQ3zAHeAx5nRFskBnrWzDUJrrvpCPD5FNAoRvTi0WwremlheES3tg+56PaVtCs5QDRX5CBLxxKMDJMEa1WQ==",
"dependencies": {
"chokidar": ">=3.0.0 <4.0.0",
"immutable": "^4.0.0",
"source-map-js": ">=0.6.2 <2.0.0"
},
"bin": {
"sass": "sass.js"
},
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/sass-loader": { "node_modules/sass-loader": {
"version": "12.6.0", "version": "12.6.0",
"resolved": "https://registry.npmjs.org/sass-loader/-/sass-loader-12.6.0.tgz", "resolved": "https://registry.npmjs.org/sass-loader/-/sass-loader-12.6.0.tgz",
@ -17166,6 +17346,14 @@
"requires-port": "^1.0.0" "requires-port": "^1.0.0"
} }
}, },
"node_modules/use-sync-external-store": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.2.0.tgz",
"integrity": "sha512-eEgnFxGQ1Ife9bzYs6VLi8/4X6CObHMw9Qr9tPY43iKwsPw8xE8+EFsf/2cFZ5S3esXgpWgtSCtLNS41F+sKPA==",
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0"
}
},
"node_modules/util-deprecate": { "node_modules/util-deprecate": {
"version": "1.0.2", "version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",

View File

@ -3,12 +3,21 @@
"version": "0.1.0", "version": "0.1.0",
"private": true, "private": true,
"dependencies": { "dependencies": {
"@fortawesome/fontawesome-svg-core": "^6.5.1",
"@fortawesome/free-brands-svg-icons": "^6.5.1",
"@fortawesome/free-regular-svg-icons": "^6.5.1",
"@fortawesome/free-solid-svg-icons": "^6.5.1",
"@fortawesome/react-fontawesome": "^0.2.0",
"@reduxjs/toolkit": "^2.1.0",
"@testing-library/jest-dom": "^5.17.0", "@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0", "@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0", "@testing-library/user-event": "^13.5.0",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"react-redux": "^9.1.0",
"react-scripts": "5.0.1", "react-scripts": "5.0.1",
"redux-thunk": "^3.1.0",
"sass": "^1.70.0",
"web-vitals": "^2.1.4" "web-vitals": "^2.1.4"
}, },
"scripts": { "scripts": {

View File

@ -1,6 +1,14 @@
import './Style/main.scss';
import './fontawesome.js';
import Home from './Pages/Home.jsx';
import Navbar from './Components/Navbar';
function App() { function App() {
return ( return (
<div className="App"> <div className="App">
<Navbar/>
<Home/>
</div> </div>
); );
} }

View File

@ -0,0 +1,41 @@
import {useSelector, useDispatch} from 'react-redux';
import {signout} from '../Slices/UserSlice';
export default function Navbar() {
const dispatch = useDispatch();
const isConnected = useSelector(
state => state.user.isConnected
);
const onLogout = event => {
event.preventDefault();
event.stopPropagation();
dispatch(signout());
};
return (
<div className="navbar">
<ul>
<li>
<a href="/">
<strong>BUDJETO</strong>
</a>
</li>
<div className="navbar__separator"></div>
{isConnected
? <li>
<a id="logOut" href="/" onClick={e => onLogout(e)}>
Déconnexion
</a>
</li>
: <></>
}
</ul>
</div>
);
}

254
app/src/Pages/Home.jsx Normal file
View File

@ -0,0 +1,254 @@
import {useState, useEffect} from 'react';
import {useSelector, useDispatch} from 'react-redux';
import {fetchUserByUsername} from '../Slices/UserSlice';
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
import {api_signup} from '../api';
function ConnectForm({onClick, onConnect}) {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const dispatch = useDispatch();
const status = useSelector(state => {
return state.user.status;
});
const error = useSelector(state => {
return state.user.error;
});
const onUsernameChange = event => {
setUsername(_ => event.target.value);
};
const onPasswordChange = event => {
setPassword(_ => event.target.value);
};
const onSubmit = event => {
event.preventDefault();
dispatch(fetchUserByUsername({username, password}));
};
return (
<form>
{status === 'pending'
? <>
Connexion en cours
<FontAwesomeIcon className="spinner" icon="fa-gear"/>
</>
: <></>
}
{status === 'done'
? <p className="passOk">Vous êtes connecté !</p>
: <></>
}
{status === 'error'
? <p className="error-msg passErr">Error: {error.detail}</p>
: <></>
}
<h1>Se connecter</h1>
<input type="text" placeholder="nom d'utilisateur"
value={username}
onChange={e => onUsernameChange(e)}
/>
<input type="password" placeholder="mot de passe"
value={password}
onChange={e => onPasswordChange(e)}
/>
<input type="submit"
onClick={e => onSubmit(e)}
value="Connexion"/>
<a href="/" onClick={e => onClick(e)}> je n'ai pas de compte</a>
</form>
);
}
function RegisterForm({onClick, onRegister}) {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [email, setEmail] = useState('');
const [confirmation, setConfirmation] = useState('');
const [samePassword, setSamePassword] = useState(true);
const [errors, setErrors] = useState([]);
const err_messages = {
'password': 'Mot de passe',
'username': 'Nom d\'utilisateur',
'email': 'Adresse email'
};
useEffect(function () {
setSamePassword(_ =>
password === confirmation
|| (password === '' && confirmation === '')
);
}, [password, confirmation]);
const onUsernameChanged = function (event) {
setUsername(_ => event.target.value);
};
const onPasswordChanged = function (event) {
setPassword(_ => event.target.value);
};
const onEmailChanged = function (event) {
setEmail(_ => event.target.value);
};
const onConfirmationChanged = function (event) {
setConfirmation(_ => event.target.value);
};
const onSubmit = function(event) {
event.preventDefault();
if (samePassword) {
onRegister(username, email, password)
.then(result => {
if (result === null) {
setUsername(_ => "");
setEmail(_ => "");
setPassword(_ => "");
setConfirmation(_ => "");
setErrors(_ => []);
return;
}
let errs = [];
for (let e in result) {
errs.push([err_messages[e], result[e]]);
}
setErrors(_ => errs);
});
}
};
return (
<form>
<ul id="home-signup-error"> {
errors.map((v, idx) => {
return <li className="err-msg" key={idx}>
<h1 className="err-msg__h">{v[0]}</h1>
<p>{v[1]}</p>
<br/>
</li>;
})
}
</ul>
<h1>Créer un nouveau compte</h1>
<input type="text" placeholder="nom d'utilisateur"
value={username}
onChange={e => onUsernameChanged(e)}/>
<input type="email"
placeholder="votre adresse email"
value={email}
onChange={e => onEmailChanged(e)}/>
<input type="password" placeholder="mot de passe"
value={password}
onChange={e => onPasswordChanged(e)}/>
{!samePassword
? <p className="passMsg passErr">
Attention, les mots des passe sont différents
</p>
: <></>}
<input type="password"
placeholder="confirmation du mot de passe"
value={confirmation}
onChange={e => onConfirmationChanged(e)}/>
<input type="submit"
value="Inscription"
onClick={e => onSubmit(e)}/>
<a href="/" onClick={e => onClick(e)}> j'ai déjà un compte</a>
</form>
);
}
export default function Home() {
const [showRegister, setShowRegister] = useState(false);
const isConnected = useSelector(state => state.user.isConnected);
const username = useSelector(state => state.user.username);
const onSwitchRegister = function(event) {
event.stopPropagation();
event.preventDefault();
setShowRegister(old => !old);
};
const onRegister = async function(username, password, email) {
const data = await api_signup(username, password, email);
const json = await data.json();
if (data.ok === false) {
return json;
}
return null;
};
const onConnect = async function (username, password) {
return null;
};
return (
<div id="home-page">
<header>
<h1>
Budjeto
</h1>
</header>
<div className="center">
<div className="center__desc">
{isConnected
?
<h2> Bienvenue {username} ! </h2>
:
<h2>Bienvenue !</h2>
}
<p>
<strong>Bienvenue sur Budjeto</strong>, votre partenaire incontournable pour une gestion de budget simplifiée et efficace. Dans un monde la maîtrise de ses finances personnelles est plus cruciale que jamais, Budjeto se positionne comme la solution idéale pour vous aider à reprendre le contrôle de votre argent.
</p>
<br/>
<p>
<strong>Rejoignez dès aujourd'hui la communauté Budjeto</strong> et commencez votre voyage vers une meilleure santé financière. Créez votre compte, définissez vos objectifs, et découvrez à quel point il est facile de faire de vos rêves financiers une réalité. Avec Budjeto, prenez enfin le contrôle de votre budget et construisez l'avenir financier que vous méritez.
</p>
</div>
{!isConnected
?
<div className="center__form">
{showRegister
? <ConnectForm onClick={onSwitchRegister}
onConnect={onConnect}
/>
: <RegisterForm onClick={onSwitchRegister}
onRegister={onRegister}/>
}
</div>
:
<div>
</div>
}
</div>
</div>
);
}

View File

@ -0,0 +1,72 @@
import {api_url} from '../api';
import {createSlice, createAsyncThunk} from '@reduxjs/toolkit';
export const fetchUserByUsername = createAsyncThunk(
'user/fetch_by_username',
async ({username, password}) => {
const res = await fetch(api_url('token'), {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
username,
password
})
});
const data = await res.json();
if (res.ok) {
return {username, token: data, error: ''};
} else {
return {username, token: "", error: data};
}
}
);
export const userSlice = createSlice({
name: 'user',
initialState: {
isConnected: false,
username: '',
token: '',
status: '',
error: ''
},
reducers: {
signout: (state) => {
state.isConnected = false;
state.username = '';
state.token = '';
state.status = '';
state.error = '';
}
},
extraReducers: builder => {
builder.addCase(fetchUserByUsername.pending, (state, action) => {
state.status = 'pending';
state.error = '';
});
builder.addCase(fetchUserByUsername.fulfilled, (state, action) => {
if (action.payload.error === '') {
state.isConnected = true;
state.username = action.payload.username;
state.token = {...action.payload.token};
state.status = 'done';
state.error = '';
} else {
state.status = 'error';
state.error = action.payload.error;
}
});
}
});
export const {signout} = userSlice.actions;
export default userSlice.reducer;

View File

@ -0,0 +1,16 @@
form {
display: flex;
flex-direction: column;
h1 {
text-align: center;
font-size: 1.2rem;
font-weight: normal;
}
input {
margin: 1rem;
padding: 0.5rem;
border: 1px solid black;
}
}

View File

@ -0,0 +1,65 @@
.navbar {
$item-height: 6rem;
$item-color: black;
$nav-color: #1E1A1D;
display: inline-block;
position: fixed;
top: 0;
left: 0;
height: 100%;
border-right: 2px solid black;
background-color: $nav-color;
@include for-mobile {
position: relative;
top: 0;
left: 0;
width: 100%;
}
ul {
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
@include for-mobile {
flex-direction: row;
}
li {
display: inline-block;
width: 100%;
height: $item-height;
border-bottom: 4px solid $nav-color;
list-decoration: none;
a {
display: grid;
align-content: center;
width: 100%;
height: 100%;
text-decoration: none;
color: white;
text-align: center;
background-color: $nav-color;
transition: background-color 0.5s;
&:hover {
background-color: lighten($nav-color, 10%);
}
}
}
}
&__separator {
display: inline-block;
width: 100%;
height: 100%;
}
}

View File

@ -0,0 +1,13 @@
.spinner {
@keyframes loading {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
animation: loading 1.5s linear infinite;
}

View File

@ -0,0 +1,123 @@
#home-page {
header {
padding: 5rem;
text-align: center;
width: 50%;
margin: auto;
margin-top: 1rem;
border-top: 1px solid black;
border-bottom: 1px solid black;
background-color: rgba(100, 100, 0, 0.1)
}
#home-signup-error {
$font-size: 1rem;
position: relative;
margin: 1rem;
list-style: none;
border-radius: 8px;
color: darkred;
font-size: $font-size;
top: 0;
left: 0;
h1 {
font-size: $font-size;
text-decoration: underline;
}
}
.center {
$max-center-width: 600px;
display: flex;
flex-direction: row;
margin-left: 1rem;
margin-top: 4%;
@include for-mobile {
flex-direction: column;
gap: 2rem;
}
&__form {
display: inline-block;
padding: 2rem;
width: 10%;
max-width: $max-center-width;
min-width: 300px;
margin-right: 2rem;
@include for-mobile {
width: 95%;
margin: auto;
padding: 0;
}
}
&__desc {
@include my-shadow;
display: inline-block;
width: 50%;
max-width: 900px;
margin: auto;
text-align: justify;
padding: 2em;
font-size: 1.25rem;
@include for-mobile {
width: 75%;
margin: auto;
padding: 1rem;
max-width: $max-center-width;
}
h2 {
text-align: center;
margin-bottom: 1.5rem;
}
}
}
form {
border: 1px solid black;
@include my-shadow;
a {
text-align: right;
margin: 1rem;
}
.passMsg {
padding: 0;
margin: 0;
text-align: center;
text-decoration: underline;
}
.passOk {
color: darkgreen;
}
.passErr {
color: darkred;
}
.err-msg {
&__h {
}
p {
text-align: center;
}
}
}
}

19
app/src/Style/_app.scss Normal file
View File

@ -0,0 +1,19 @@
.App {
$nav-width: 9%;
.navbar {
width: $nav-width;
@include for-mobile {
width: 100%;
}
}
#home-page {
margin-left: $nav-width;
@include for-mobile {
margin-left: 0;
}
}
}

View File

@ -0,0 +1,5 @@
* {
margin: 0;
padding: 0;
font-family: monospace;
}

11
app/src/Style/_utils.scss Normal file
View File

@ -0,0 +1,11 @@
@mixin my-shadow() {
border: 2px solid black;
box-shadow: 6px 6px rgb(200, 200, 200);
}
@mixin for-mobile() {
@media screen and (max-width: 1024px) {
@content
}
}

9
app/src/Style/main.scss Normal file
View File

@ -0,0 +1,9 @@
@import 'reset';
@import 'utils';
@import 'app';
@import 'Components/form';
@import 'Components/spinner';
@import 'Components/navbar';
@import 'Pages/home';

35
app/src/api.js Normal file
View File

@ -0,0 +1,35 @@
export function api_url() {
let url = process.env.REACT_APP_API;
if (process.env.REACT_APP_API === undefined) {
url = 'http://localhost:8000';
}
let params = [url, 'v0'];
for (let val of arguments) {
params.push(val);
}
return params.join('/') + '/';
}
export async function api_post(request, body) {
const data = await fetch(request, {
method: 'POST',
headers: {
"Content-Type": 'application/json'
},
body: JSON.stringify(body)
});
return data;
}
export async function api_signup(username, email, password) {
return api_post(api_url('signup'), {
"username": username,
"email": email,
"password": password
});
}

15
app/src/fontawesome.js Normal file
View File

@ -0,0 +1,15 @@
import {library} from '@fortawesome/fontawesome-svg-core';
import {
faSackDollar,
faSpinner,
faGear,
faRightFromBracket
} from '@fortawesome/free-solid-svg-icons';
library.add(
faSackDollar,
faSpinner,
faGear,
faRightFromBracket
);

View File

@ -2,11 +2,15 @@ import React from 'react';
import ReactDOM from 'react-dom/client'; import ReactDOM from 'react-dom/client';
import App from './App'; import App from './App';
import reportWebVitals from './reportWebVitals'; import reportWebVitals from './reportWebVitals';
import store from './store';
import {Provider} from 'react-redux';
const root = ReactDOM.createRoot(document.getElementById('root')); const root = ReactDOM.createRoot(document.getElementById('root'));
root.render( root.render(
<React.StrictMode> <React.StrictMode>
<App /> <Provider store={store}>
<App />
</Provider>
</React.StrictMode> </React.StrictMode>
); );

38
app/src/store.js Normal file
View File

@ -0,0 +1,38 @@
import {configureStore} from '@reduxjs/toolkit';
import userReducer from './Slices/UserSlice.js';
function loadState() {
const val = localStorage.getItem('state');
if (!val) {
localStorage.setItem('state', JSON.stringify({}));
}
try {
return JSON.parse(val);
} catch (_) {
return {};
}
}
export function saveState(state) {
try {
localStorage.setItem('state', JSON.stringify(state));
} catch (_) {
}
}
const preloaded = loadState();
const store = configureStore({
reducer: {
user: userReducer,
},
preloadedState: preloaded
});
store.subscribe(_ => {
saveState(store.getState());
});
export default store;

View File

@ -1,3 +1,5 @@
from django.contrib import admin from django.contrib import admin
from authentication import models
# Register your models here. # Register your models here.
admin.site.register(models.User)

View File

@ -0,0 +1,44 @@
# Generated by Django 5.0.1 on 2024-02-06 11:32
import django.contrib.auth.models
import django.contrib.auth.validators
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')),
('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.permission', verbose_name='user permissions')),
],
options={
'verbose_name': 'user',
'verbose_name_plural': 'users',
'abstract': False,
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
]

View File

@ -1,3 +1,5 @@
from django.db import models from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here. class User(AbstractUser):
email = models.EmailField(blank=False, null=False)

View File

@ -0,0 +1,15 @@
from authentication.models import User
from rest_framework.serializers import ModelSerializer, ValidationError
class UserSerializer(ModelSerializer):
class Meta:
model = User
fields = '__all__'
def validate(self, data):
req = User.objects.filter(email=data['email'])
if req.count() != 0:
raise ValidationError("Cette adresse email est déjà utilisée.")
return super().validate(data)

View File

@ -1,3 +0,0 @@
from django.test import TestCase
# Create your tests here.

View File

@ -0,0 +1,20 @@
import pytest
from django.urls import reverse_lazy
from django.contrib.auth import get_user_model
from rest_framework.test import APIRequestFactory, APIClient
from rest_framework import status
@pytest.mark.parametrize('ret_status, username', [
(status.HTTP_200_OK, 'alice'),
(status.HTTP_401_UNAUTHORIZED, 'bob')
])
def test_get_token(client, mkadmin, ret_status, username):
mkadmin()
res = client.post(reverse_lazy('auth:token_obtain'), {
'username': username,
'password': 'alicepassword',
'email': 'alice@email.com'
})
assert res.status_code == ret_status

View File

@ -0,0 +1,106 @@
from django.urls import reverse_lazy
from rest_framework import status
def test_signup__ok(client, User):
assert 0 == User.objects.count()
resp = client.post(reverse_lazy('auth:signup'), {
'username': 'dan',
'password': 'danpassword',
'email': 'dan@email.com'
})
assert resp.status_code == status.HTTP_201_CREATED
assert 1 == User.objects.count()
assert 'dan' == User.objects.first().username
assert 'dan@email.com' == User.objects.first().email
def test_signup__err_username_already_taken(client, User, mkuser):
mkuser('dan')
assert 1 == User.objects.count()
resp = client.post(reverse_lazy('auth:signup'), {
'username': 'dan',
'password': 'danpassword',
'email': 'dan@email.com'
})
assert resp.status_code != status.HTTP_201_CREATED
assert 1 == User.objects.count()
def test_signup__err_email_already_taken(client, User, mkuser):
mkuser('sam', 'dan@email.com')
assert 1 == User.objects.count()
resp = client.post(reverse_lazy('auth:signup'), {
'username': 'dan',
'password': 'danpassword',
'email': 'dan@email.com'
})
assert resp.status_code != status.HTTP_201_CREATED
assert 1 == User.objects.count()
def test_signup__err_blank_username(client, User):
resp = client.post(reverse_lazy('auth:signup'), {
'username': '',
'password': 'danpassword',
'email': 'dan@email.com'
})
assert resp.status_code == status.HTTP_400_BAD_REQUEST
assert 0 == User.objects.count()
def test_signup__err_no_username(client, User):
resp = client.post(reverse_lazy('auth:signup'), {
'password': 'danpassword',
'email': 'dan@email.com'
})
assert resp.status_code == status.HTTP_400_BAD_REQUEST
assert 0 == User.objects.count()
def test_signup__err_blank_password(client, User):
resp = client.post(reverse_lazy('auth:signup'), {
'username': 'dan',
'password': '',
'email': 'dan@email.com'
})
assert resp.status_code == status.HTTP_400_BAD_REQUEST
assert 0 == User.objects.count()
def test_signup__err_no_password(client, User):
resp = client.post(reverse_lazy('auth:signup'), {
'username': 'dan',
'email': 'dan@email.com'
})
assert resp.status_code == status.HTTP_400_BAD_REQUEST
assert 0 == User.objects.count()
def test_signup__err_blank_email(client, User):
resp = client.post(reverse_lazy('auth:signup'), {
'username': 'dan',
'password': 'danpassword',
'email': ''
})
assert resp.status_code == status.HTTP_400_BAD_REQUEST
assert 0 == User.objects.count()
def test_signup__err_no_email(client, User):
resp = client.post(reverse_lazy('auth:signup'), {
'username': 'dan',
'password': 'danpassword',
})
assert resp.status_code == status.HTTP_400_BAD_REQUEST
assert 0 == User.objects.count()

View File

@ -1,4 +1,5 @@
from django.urls import path, include from django.urls import path, include
from authentication import views
from rest_framework_simplejwt.views import ( from rest_framework_simplejwt.views import (
TokenObtainPairView, TokenObtainPairView,
@ -8,6 +9,7 @@ from rest_framework_simplejwt.views import (
app_name = 'auth' app_name = 'auth'
urlpatterns = [ urlpatterns = [
path('signup/', views.SignUpView.as_view(), name='signup'),
path('token/', TokenObtainPairView.as_view(), name='token_obtain'), path('token/', TokenObtainPairView.as_view(), name='token_obtain'),
path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh') path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh')
] ]

View File

@ -1 +1,19 @@
from django.shortcuts import render from django.shortcuts import render
from django.contrib.auth import get_user_model
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from authentication import serializers
class SignUpView(APIView):
def post(self, request):
user = serializers.UserSerializer(data=request.data)
if user.is_valid():
u = user.save()
u.set_password(request.data['password'])
u.save()
return Response(user.data, status=status.HTTP_201_CREATED)
return Response(user.errors, status=status.HTTP_400_BAD_REQUEST)

View File

@ -6,7 +6,8 @@ BUDJETO_PRODUCTION = os.getenv('BUDJETO_PRODUCTION') == 'ON'
if BUDJETO_PRODUCTION: if BUDJETO_PRODUCTION:
DEBUG = False DEBUG = False
ALLOWED_HOSTS = ['localhost'] ALLOWED_HOSTS = ['127.0.0.1', 'localhost']
SECRET_KEY = os.getenv('BUDJETO_SECRET') SECRET_KEY = os.getenv('BUDJETO_SECRET')
DATABASES = { DATABASES = {
@ -31,6 +32,11 @@ else:
} }
} }
CORS_ALLOWED_ORIGINS = [
'http://localhost:32145',
'http://localhost:3000',
]
INSTALLED_APPS = [ INSTALLED_APPS = [
'django.contrib.admin', 'django.contrib.admin',
'django.contrib.auth', 'django.contrib.auth',
@ -38,12 +44,14 @@ INSTALLED_APPS = [
'django.contrib.sessions', 'django.contrib.sessions',
'django.contrib.messages', 'django.contrib.messages',
'django.contrib.staticfiles', 'django.contrib.staticfiles',
'corsheaders',
'rest_framework', 'rest_framework',
'rest_framework_simplejwt', 'rest_framework_simplejwt',
'authentication' 'authentication'
] ]
MIDDLEWARE = [ MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware', 'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware', 'django.middleware.common.CommonMiddleware',
@ -108,7 +116,7 @@ USE_TZ = True
# Static files (CSS, JavaScript, Images) # Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/ # https://docs.djangoproject.com/en/5.0/howto/static-files/
STATIC_URL = 'static/' STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
# Default primary key field type # Default primary key field type
@ -121,3 +129,5 @@ REST_FRAMEWORK = {
'rest_framework_simplejwt.authentication.JWTAuthentication' 'rest_framework_simplejwt.authentication.JWTAuthentication'
] ]
} }
AUTH_USER_MODEL = 'authentication.User'

39
conftest.py Normal file
View File

@ -0,0 +1,39 @@
import pytest
from django.contrib.auth import get_user_model
from rest_framework.test import APIRequestFactory, APIClient
@pytest.fixture()
def User(db):
return get_user_model()
@pytest.fixture()
def mkadmin(db):
def inner(username='alice',
email='alice@email.com',
password='alicepassword'):
User = get_user_model()
user = User.objects.create_superuser(username=username,
email=email,
password=password)
return user
return inner
@pytest.fixture()
def mkuser(db):
def inner(username='alice',
email='alice@email.com',
password='alicepassword'):
User = get_user_model()
user = User.objects.create(username=username,
email=email,
password=password)
return user
return inner
@pytest.fixture()
def client():
return APIClient()
@pytest.fixture()
def factory():
return APIRequestFactory()

7
create_admin.py Normal file
View File

@ -0,0 +1,7 @@
from django.contrib.auth import get_user_model
User = get_user_model()
if User.objects.filter(is_superuser=True).count() == 0:
print('/!\\ new admin created: CHANGE THE PASSWORD NOW')
User.objects.create_superuser(username='admin', password='admin')

View File

@ -1,18 +1,12 @@
version: "3" version: "3"
services: services:
server:
build: server/.
container_name: budjeto_server
restart: always
volumes:
- backend_staticfiles:/backend/statics
ports:
- 32294:80
frontend: frontend:
build: app/. build: app/.
container_name: budjeto_fontend container_name: budjeto_frontend
restart: always restart: always
environment:
- 'REACT_APP_API=http://localhost:12764'
ports: ports:
- 32145:3000 - 32145:3000
backend: backend:
@ -20,7 +14,7 @@ services:
container_name: budjeto_backend container_name: budjeto_backend
restart: always restart: always
volumes: volumes:
- backend_staticfiles:/app/staticfiles - ./staticfiles:/app/staticfiles
environment: environment:
- 'BUDJETO_PRODUCTION=ON' - 'BUDJETO_PRODUCTION=ON'
- 'BUDJETO_SECRET=my secret' - 'BUDJETO_SECRET=my secret'
@ -42,4 +36,3 @@ services:
volumes: volumes:
db_data: db_data:
backend_staticfiles:

2
pytest.ini Normal file
View File

@ -0,0 +1,2 @@
[pytest]
DJANGO_SETTINGS_MODULE = budjeto.settings

View File

@ -1,13 +1,18 @@
asgiref==3.7.2 asgiref==3.7.2
Django==5.0.1 Django==5.0.1
django-cors-headers==4.3.1
djangorestframework==3.14.0 djangorestframework==3.14.0
djangorestframework-simplejwt==5.3.1 djangorestframework-simplejwt==5.3.1
docstring-to-markdown==0.13 docstring-to-markdown==0.13
iniconfig==2.0.0
jedi==0.19.1 jedi==0.19.1
packaging==23.2
parso==0.8.3 parso==0.8.3
pluggy==1.4.0 pluggy==1.4.0
psycopg==3.1.18 psycopg==3.1.18
PyJWT==2.8.0 PyJWT==2.8.0
pytest==8.0.0
pytest-django==4.8.0
python-lsp-jsonrpc==1.1.2 python-lsp-jsonrpc==1.1.2
python-lsp-server==1.10.0 python-lsp-server==1.10.0
pytz==2024.1 pytz==2024.1

View File

@ -1,3 +0,0 @@
FROM httpd
COPY httpd.conf /usr/local/apache2/conf/httpd.conf

View File

@ -1,569 +0,0 @@
#
# This is the main Apache HTTP server configuration file. It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do. They're here only as hints or reminders. If you are unsure
# consult the online docs. You have been warned.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path. If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so "logs/access_log"
# with ServerRoot set to "/usr/local/apache2" will be interpreted by the
# server as "/usr/local/apache2/logs/access_log", whereas "/logs/access_log"
# will be interpreted as '/logs/access_log'.
#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path. If you point
# ServerRoot at a non-local disk, be sure to specify a local disk on the
# Mutex directive, if file-based mutexes are used. If you wish to share the
# same ServerRoot for multiple httpd daemons, you will need to change at
# least PidFile.
#
ServerRoot "/usr/local/apache2"
#
# Mutex: Allows you to set the mutex mechanism and mutex file directory
# for individual mutexes, or change the global defaults
#
# Uncomment and change the directory if mutexes are file-based and the default
# mutex file directory is not on a local disk or is not appropriate for some
# other reason.
#
# Mutex default:logs
#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 80
#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
LoadModule mpm_event_module modules/mod_mpm_event.so
#LoadModule mpm_prefork_module modules/mod_mpm_prefork.so
#LoadModule mpm_worker_module modules/mod_mpm_worker.so
LoadModule authn_file_module modules/mod_authn_file.so
#LoadModule authn_dbm_module modules/mod_authn_dbm.so
#LoadModule authn_anon_module modules/mod_authn_anon.so
#LoadModule authn_dbd_module modules/mod_authn_dbd.so
#LoadModule authn_socache_module modules/mod_authn_socache.so
LoadModule authn_core_module modules/mod_authn_core.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_user_module modules/mod_authz_user.so
#LoadModule authz_dbm_module modules/mod_authz_dbm.so
#LoadModule authz_owner_module modules/mod_authz_owner.so
#LoadModule authz_dbd_module modules/mod_authz_dbd.so
LoadModule authz_core_module modules/mod_authz_core.so
#LoadModule authnz_ldap_module modules/mod_authnz_ldap.so
#LoadModule authnz_fcgi_module modules/mod_authnz_fcgi.so
LoadModule access_compat_module modules/mod_access_compat.so
LoadModule auth_basic_module modules/mod_auth_basic.so
#LoadModule auth_form_module modules/mod_auth_form.so
#LoadModule auth_digest_module modules/mod_auth_digest.so
#LoadModule allowmethods_module modules/mod_allowmethods.so
#LoadModule isapi_module modules/mod_isapi.so
#LoadModule file_cache_module modules/mod_file_cache.so
#LoadModule cache_module modules/mod_cache.so
#LoadModule cache_disk_module modules/mod_cache_disk.so
#LoadModule cache_socache_module modules/mod_cache_socache.so
#LoadModule socache_shmcb_module modules/mod_socache_shmcb.so
#LoadModule socache_dbm_module modules/mod_socache_dbm.so
#LoadModule socache_memcache_module modules/mod_socache_memcache.so
#LoadModule socache_redis_module modules/mod_socache_redis.so
#LoadModule watchdog_module modules/mod_watchdog.so
#LoadModule macro_module modules/mod_macro.so
#LoadModule dbd_module modules/mod_dbd.so
#LoadModule bucketeer_module modules/mod_bucketeer.so
#LoadModule dumpio_module modules/mod_dumpio.so
#LoadModule echo_module modules/mod_echo.so
#LoadModule example_hooks_module modules/mod_example_hooks.so
#LoadModule case_filter_module modules/mod_case_filter.so
#LoadModule case_filter_in_module modules/mod_case_filter_in.so
#LoadModule example_ipc_module modules/mod_example_ipc.so
#LoadModule buffer_module modules/mod_buffer.so
#LoadModule data_module modules/mod_data.so
#LoadModule ratelimit_module modules/mod_ratelimit.so
LoadModule reqtimeout_module modules/mod_reqtimeout.so
#LoadModule ext_filter_module modules/mod_ext_filter.so
#LoadModule request_module modules/mod_request.so
#LoadModule include_module modules/mod_include.so
LoadModule filter_module modules/mod_filter.so
#LoadModule reflector_module modules/mod_reflector.so
#LoadModule substitute_module modules/mod_substitute.so
#LoadModule sed_module modules/mod_sed.so
#LoadModule charset_lite_module modules/mod_charset_lite.so
#LoadModule deflate_module modules/mod_deflate.so
#LoadModule xml2enc_module modules/mod_xml2enc.so
#LoadModule proxy_html_module modules/mod_proxy_html.so
#LoadModule brotli_module modules/mod_brotli.so
LoadModule mime_module modules/mod_mime.so
#LoadModule ldap_module modules/mod_ldap.so
LoadModule log_config_module modules/mod_log_config.so
#LoadModule log_debug_module modules/mod_log_debug.so
#LoadModule log_forensic_module modules/mod_log_forensic.so
#LoadModule logio_module modules/mod_logio.so
#LoadModule lua_module modules/mod_lua.so
LoadModule env_module modules/mod_env.so
#LoadModule mime_magic_module modules/mod_mime_magic.so
#LoadModule cern_meta_module modules/mod_cern_meta.so
#LoadModule expires_module modules/mod_expires.so
LoadModule headers_module modules/mod_headers.so
#LoadModule ident_module modules/mod_ident.so
#LoadModule usertrack_module modules/mod_usertrack.so
#LoadModule unique_id_module modules/mod_unique_id.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule version_module modules/mod_version.so
#LoadModule remoteip_module modules/mod_remoteip.so
#LoadModule proxy_module modules/mod_proxy.so
#LoadModule proxy_connect_module modules/mod_proxy_connect.so
#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
#LoadModule proxy_http_module modules/mod_proxy_http.so
#LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so
#LoadModule proxy_scgi_module modules/mod_proxy_scgi.so
#LoadModule proxy_uwsgi_module modules/mod_proxy_uwsgi.so
#LoadModule proxy_fdpass_module modules/mod_proxy_fdpass.so
#LoadModule proxy_wstunnel_module modules/mod_proxy_wstunnel.so
#LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
#LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
#LoadModule proxy_express_module modules/mod_proxy_express.so
#LoadModule proxy_hcheck_module modules/mod_proxy_hcheck.so
#LoadModule session_module modules/mod_session.so
#LoadModule session_cookie_module modules/mod_session_cookie.so
#LoadModule session_crypto_module modules/mod_session_crypto.so
#LoadModule session_dbd_module modules/mod_session_dbd.so
#LoadModule slotmem_shm_module modules/mod_slotmem_shm.so
#LoadModule slotmem_plain_module modules/mod_slotmem_plain.so
#LoadModule ssl_module modules/mod_ssl.so
#LoadModule optional_hook_export_module modules/mod_optional_hook_export.so
#LoadModule optional_hook_import_module modules/mod_optional_hook_import.so
#LoadModule optional_fn_import_module modules/mod_optional_fn_import.so
#LoadModule optional_fn_export_module modules/mod_optional_fn_export.so
#LoadModule dialup_module modules/mod_dialup.so
#LoadModule http2_module modules/mod_http2.so
#LoadModule proxy_http2_module modules/mod_proxy_http2.so
#LoadModule md_module modules/mod_md.so
#LoadModule lbmethod_byrequests_module modules/mod_lbmethod_byrequests.so
#LoadModule lbmethod_bytraffic_module modules/mod_lbmethod_bytraffic.so
#LoadModule lbmethod_bybusyness_module modules/mod_lbmethod_bybusyness.so
#LoadModule lbmethod_heartbeat_module modules/mod_lbmethod_heartbeat.so
LoadModule unixd_module modules/mod_unixd.so
#LoadModule heartbeat_module modules/mod_heartbeat.so
#LoadModule heartmonitor_module modules/mod_heartmonitor.so
#LoadModule dav_module modules/mod_dav.so
LoadModule status_module modules/mod_status.so
LoadModule autoindex_module modules/mod_autoindex.so
#LoadModule asis_module modules/mod_asis.so
#LoadModule info_module modules/mod_info.so
#LoadModule suexec_module modules/mod_suexec.so
<IfModule !mpm_prefork_module>
#LoadModule cgid_module modules/mod_cgid.so
</IfModule>
<IfModule mpm_prefork_module>
#LoadModule cgi_module modules/mod_cgi.so
</IfModule>
#LoadModule dav_fs_module modules/mod_dav_fs.so
#LoadModule dav_lock_module modules/mod_dav_lock.so
#LoadModule vhost_alias_module modules/mod_vhost_alias.so
#LoadModule negotiation_module modules/mod_negotiation.so
LoadModule dir_module modules/mod_dir.so
#LoadModule imagemap_module modules/mod_imagemap.so
#LoadModule actions_module modules/mod_actions.so
#LoadModule speling_module modules/mod_speling.so
#LoadModule userdir_module modules/mod_userdir.so
LoadModule alias_module modules/mod_alias.so
#LoadModule rewrite_module modules/mod_rewrite.so
<IfModule unixd_module>
#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User www-data
Group www-data
</IfModule>
# 'Main' server configuration
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition. These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#
#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed. This address appears on some server-generated pages, such
# as error documents. e.g. admin@your-domain.com
#
ServerAdmin you@example.com
#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
#ServerName www.example.com:80
#
# Deny access to the entirety of your server's filesystem. You must
# explicitly permit access to web content directories in other
# <Directory> blocks below.
#
<Directory />
AllowOverride none
Require all denied
</Directory>
#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#
#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "/usr/local/apache2/htdocs"
<Directory "/usr/local/apache2/htdocs">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.4/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# AllowOverride FileInfo AuthConfig Limit
#
AllowOverride None
#
# Controls who can get stuff from this server.
#
Require all granted
</Directory>
#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
DirectoryIndex index.html
</IfModule>
#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ".ht*">
Require all denied
</Files>
#
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here. If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog /proc/self/fd/2
#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn
<IfModule log_config_module>
#
# The following directives define some format nicknames for use with
# a CustomLog directive (see below).
#
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
<IfModule logio_module>
# You need to enable mod_logio.c to use %I and %O
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
</IfModule>
#
# The location and format of the access logfile (Common Logfile Format).
# If you do not define any access logfiles within a <VirtualHost>
# container, they will be logged here. Contrariwise, if you *do*
# define per-<VirtualHost> access logfiles, transactions will be
# logged therein and *not* in this file.
#
CustomLog /proc/self/fd/1 common
#
# If you prefer a logfile with access, agent, and referer information
# (Combined Logfile Format) you can use the following directive.
#
#CustomLog "logs/access_log" combined
</IfModule>
<IfModule alias_module>
#
# Redirect: Allows you to tell clients about documents that used to
# exist in your server's namespace, but do not anymore. The client
# will make a new request for the document at its new location.
# Example:
# Redirect permanent /foo http://www.example.com/bar
#
# Alias: Maps web paths into filesystem paths and is used to
# access content that does not live under the DocumentRoot.
# Example:
# Alias /webpath /full/filesystem/path
#
# If you include a trailing / on /webpath then the server will
# require it to be present in the URL. You will also likely
# need to provide a <Directory> section to allow access to
# the filesystem path.
#
# ScriptAlias: This controls which directories contain server scripts.
# ScriptAliases are essentially the same as Aliases, except that
# documents in the target directory are treated as applications and
# run by the server when requested rather than as documents sent to the
# client. The same rules about trailing "/" apply to ScriptAlias
# directives as to Alias.
#
ScriptAlias /cgi-bin/ "/usr/local/apache2/cgi-bin/"
</IfModule>
<IfModule cgid_module>
#
# ScriptSock: On threaded servers, designate the path to the UNIX
# socket used to communicate with the CGI daemon of mod_cgid.
#
#Scriptsock cgisock
</IfModule>
#
# "/usr/local/apache2/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/usr/local/apache2/cgi-bin">
AllowOverride None
Options None
Require all granted
</Directory>
<IfModule headers_module>
#
# Avoid passing HTTP_PROXY environment to CGI's on this or any proxied
# backend servers which have lingering "httpoxy" defects.
# 'Proxy' request header is undefined by the IETF, not listed by IANA
#
RequestHeader unset Proxy early
</IfModule>
<IfModule mime_module>
#
# TypesConfig points to the file containing the list of mappings from
# filename extension to MIME-type.
#
TypesConfig conf/mime.types
#
# AddType allows you to add to or override the MIME configuration
# file specified in TypesConfig for specific file types.
#
#AddType application/x-gzip .tgz
#
# AddEncoding allows you to have certain browsers uncompress
# information on the fly. Note: Not all browsers support this.
#
#AddEncoding x-compress .Z
#AddEncoding x-gzip .gz .tgz
#
# If the AddEncoding directives above are commented-out, then you
# probably should define those extensions to indicate media types:
#
AddType application/x-compress .Z
AddType application/x-gzip .gz .tgz
#
# AddHandler allows you to map certain file extensions to "handlers":
# actions unrelated to filetype. These can be either built into the server
# or added with the Action directive (see below)
#
# To use CGI scripts outside of ScriptAliased directories:
# (You will also need to add "ExecCGI" to the "Options" directive.)
#
#AddHandler cgi-script .cgi
# For type maps (negotiated resources):
#AddHandler type-map var
#
# Filters allow you to process content before it is sent to the client.
#
# To parse .shtml files for server-side includes (SSI):
# (You will also need to add "Includes" to the "Options" directive.)
#
#AddType text/html .shtml
#AddOutputFilter INCLUDES .shtml
</IfModule>
#
# The mod_mime_magic module allows the server to use various hints from the
# contents of the file itself to determine its type. The MIMEMagicFile
# directive tells the module where the hint definitions are located.
#
#MIMEMagicFile conf/magic
#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#
#
# MaxRanges: Maximum number of Ranges in a request before
# returning the entire resource, or one of the special
# values 'default', 'none' or 'unlimited'.
# Default setting is to accept 200 Ranges.
#MaxRanges unlimited
#
# EnableMMAP and EnableSendfile: On systems that support it,
# memory-mapping or the sendfile syscall may be used to deliver
# files. This usually improves server performance, but must
# be turned off when serving from networked-mounted
# filesystems or if support for these functions is otherwise
# broken on your system.
# Defaults: EnableMMAP On, EnableSendfile Off
#
#EnableMMAP off
#EnableSendfile on
# Supplemental configuration
#
# The configuration files in the conf/extra/ directory can be
# included to add extra features or to modify the default configuration of
# the server, or you may simply copy their contents here and change as
# necessary.
# Server-pool management (MPM specific)
#Include conf/extra/httpd-mpm.conf
# Multi-language error messages
#Include conf/extra/httpd-multilang-errordoc.conf
# Fancy directory listings
#Include conf/extra/httpd-autoindex.conf
# Language settings
#Include conf/extra/httpd-languages.conf
# User home directories
#Include conf/extra/httpd-userdir.conf
# Real-time info on requests and configuration
#Include conf/extra/httpd-info.conf
# Virtual hosts
#Include conf/extra/httpd-vhosts.conf
# Local access to the Apache HTTP Server Manual
#Include conf/extra/httpd-manual.conf
# Distributed authoring and versioning (WebDAV)
#Include conf/extra/httpd-dav.conf
# Various default settings
#Include conf/extra/httpd-default.conf
# Configure mod_proxy_html to understand HTML4/XHTML1
<IfModule proxy_html_module>
Include conf/extra/proxy-html.conf
</IfModule>
# Secure (SSL/TLS) connections
#Include conf/extra/httpd-ssl.conf
#
# Note: The following must must be present to support
# starting without SSL on platforms with no /dev/random equivalent
# but a statically compiled-in mod_ssl.
#
<IfModule ssl_module>
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin
</IfModule>
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
<VirtualHost *:80>
ServerName server
RewriteEngine On
RewriteRule ^/static/(.*)$ /backend/statics/$1 [L]
<Directory /backend/statics>
Require all granted
</Directory>
ProxyPreserveHost On
ProxyPass / http://backend:8000/
ProxyPassReverse / http://backend:8000/
</VirtualHost>