Skip to content

Commit

Permalink
feat: launch everything from the same docker compose (#2)
Browse files Browse the repository at this point in the history
* feat: group docker compose together

* feat: move docker compose to root

* fix: rename secret example file

the name it had before made esphome think it was an esp32 config file

* refactor: rename login_login to login

login_login is a pleonasme, it's useless to say login twice

* feat: Launch php login backend with the docker

* refactor: move sql file to root

it's the only required file for the database, therefore it doesn't need to be in another directory

* refactor: rewrite Readme.md

* feat: launch react build with the web server

* feat: isolate the sub domain from the domain
before if you were making a request to anything.domain.com, the domain would be domain.com. Now the domain will be anything.domain.com
it means that now everything starting with login.memoires-info.com will be run as php code instead of being ignored
the reason it worked before was because the uri contained "login."

* feat: access everythign from the same web server

* feat: update readme

* feat: change web server port to be the default one
User now don't need to specify the port when accessing the web server

* refactor: move sql script to it's own directory
now postgres data won't apear in root

* refactor: rename assets folder to be hidden

* refactor: move postgrest config in another file

* feat: add a way to get postgrest error in php login

* fix: update api test file

* refactor: shorten gitignore file

* feat: automatically create the db

* feat: implement login (#5)

* feat: display averages for the last two months, refactor the way data is retrieved and placed in the pie chart

* feat: token added to link for API data, change to display of month element

* feat: link login element with login backend

* feat: link login element with login backend

* feat: the token in sampleContext takes the value from the user who logged in

* feat: store the token in localstorage

* fix: fix small errors to launch npm run build

* feat: added login functionality, created a function to get tokens from localstorage

* style: change input form design

* feat: redirect the user on login if the token is wrong

* feat: create a function that checks for 401 errors

* refactor: the method of collecting data and putting it into the monthly chart

* feat: add log out button

* fix: add link to esphome github page

---------

Co-authored-by: jordyBSK <125542402+jordyBSK@users.noreply.github.com>
  • Loading branch information
Rignchen and jordyBSK committed Apr 12, 2024
1 parent 70f6f43 commit 9042cb9
Show file tree
Hide file tree
Showing 21 changed files with 226 additions and 150 deletions.
File renamed without changes
File renamed without changes
File renamed without changes
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
.idea
# vim backup files
*.sw[pon]
156 changes: 72 additions & 84 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,102 +1,90 @@
# climat_guardian
Système de surveillance climatique
[Info]: <> (
All the information that are likely to need to be updated have a comment above them like this one
)
# Climat-Guardian
This project was made for the non-profit organization memoires-informatiques\
Memoires-informatiques has a lot of old computers and other electronic devices that need to be stored in a controlled environment\
The goal of this project is to monitor the temperature and humidity of the different rooms of the organization and to display the data on a web interface

## Postgresql
### Installation
This project uses a postgresql database wich is run in a docker container
Start by creating a database called `memoires-info`
Then to create the tables, you can run the file `init.sql` in the backend folder
## Installation
First thing you need to do is to clone the repository from the github page and install the dependencies
```bash
psql -h localhost -U postgres -d memoires-info -a -f backend/init.sql
git clone https://github.com/museebolo/climat-guardian.git
cd climat-guardian/login
composer install
cd ../Interface
npm install
npm run build
cd ..
```
### Launch
Once the database is created, you can start the docker container in the backend folder
This will run the database on port 5432
This also run adminer on port 8080 wich is a web interface to manage the database
This also run a postg rest server on port 3000

---
[Info]: <> (
This is the list of all the files that end with .example
)
Once the repository is cloned you can remove the `.example` at the end of the following files:
- login/.env.example
- esp32/config/secrets.example.yaml
```bash
cd backend
docker-compose up
```
### Adminer
You can access adminer by going to `localhost:8080` in your web browser
You can then connect to the database with the following credentials
```
System: PostgreSQL
Server: db
Username: postgres
Password: postgres
Database: memoires-info
mv login/.env.example login/.env
mv esp32/config/secrets.example.yaml esp32/config/secrets.yaml
```
### Postgrest
Postg rest is an api used to push and pull data from the database
get request can be made to pull data from the database and post request can be made to push data to the database
You can look at the database's content by going to `localhost:3000/data` in your web browser

## Esp32
### Installation
This project uses esp home to manage the esp32 wich is run in a docker container
Inside the config folder, start by copying the `secret.example.yaml` file to `secret.yaml` and fill in credentials
Then to start the esp32, you can run the following command
---
Now you want to generate a secret key for the jwt tokens used by the api
```bash
cd esp32
docker-compose up
tr -dc A-Za-z0-9 </dev/urandom | head -c 32; echo
```
### Home assistant
You can access home assistant by going to `localhost:6052` in your web browser
### Add esp32 to home assistant
Tou can then add the esp32 to home assistant by pluging the esp32 to your computer that runs the docker
Then press the `+ ADD DEVICE` button inside home assistant
Then press continue and name your device, give him a clever name so you know wich device it is
Then press `next` and select `ESP32` (on the top of the list)
Once that's done you want to skip the installation you'll have to reinstall it later anyway
Go to the card of the device and press `EDIT`
Here you want to copy everything from the line 31 of the `esp32/esp32.yaml` and paste it at the end of your esp32's configuration file
Then press `INSTALL` and select `Plug into the computer running ESPHome Dashboard` (the 3rd option)
You then want to look for the device for wich the path is `/dev/ttyUSB0` and select it
Now the installation should start and you should see the logs of the installation
It can take a few minutes to compile and install the firmware, be patient
Once the installation is done, you can press `STOP` to exit the logs
You can now unplug the esp32 the computer and plug it to any other power source
If you need to change the configuration of the esp32, you can now do it wirelessly from the home assistant interface

[Info]: <> (
This is the list of all the files that require to know the jwt secret key
)
You then want to copy the secret key and paste it the following files:
- login/.env
- postgrest.conf

---
Finally you can fill the `esp32/config/secrets.yaml` with the credentials of the wifi\

## Data transfer
Here are 2 diagrams that show how the data is transfered from the esp32 to the web interface
### Hardware
![hardware](/assets/hardware-diagram.png)
![hardware](/.assets/hardware-diagram.png)
### Software
![software](/assets/software-diagram.png)
![software](/.assets/software-diagram.png)

## User Login
When the database is created, a user is created with the following credentials
```
Username: admin
Password: admin
```
You can use these credentials to login to the web interface for the first time.\
This user can be used to create other users with different credentials\
All users have the same rights meaning they can all create users and read data from the database
### Start login backend
To start the login backend, you can run the following command
## Start the project
Once everything is configured you can start the project by running the docker compose
```bash
cd backend/login
php -S localhost:8000 -t public
docker compose up
```
### Test login backend
You can test the login backend by going to the file `backend/login/login.http` and running the requests,
be sure to give the right credentials to the requests and to give the token to the requests with the `Authorization` header
Once the docker is running you can access the web interface by going to `memoires-info.com` in your web browser (or the ip address of the computer that runs the docker)

## Web Interface
### Installation
This project uses a react web interface to display the data from the database\
First thing you need to do is to copy `Interface/src/contexts/SampleContext.example.tsx` to `Interface/src/contexts/SampleContext.tsx` and fill in the credentials\
Then you can start the web interface by running the following command
![web interface](/.assets/dashboard.png)

## ESP 32 Installation
This project uses esp home to manage the esp32, you can configure the esp32 by following the instructions below
- Connect yourself to the [esphome](https://github.com/esphome/esphome) interface by going to `esphome.memoires-info.com` in your web browser (or the ip address of the computer that runs the docker)
- Plug the esp32 to your computer
- Press the `+ ADD DEVICE` button inside esp home
- Name your device
- Select `ESP32` (on the top of the list)
- Skip the installation, you'll have to reinstall it later anyway
- Go to the card of the device and press `EDIT`
- Copy everything from the line 31 of the `esp32/esp32.yaml` and paste it at the end of your esp32's configuration file
- Press `INSTALL` and select `Plug into the computer running ESPHome Dashboard` (the 3rd option)
- Look for the device for wich the path is `/dev/ttyUSB0` and select it
- Wait for the installation to finish
- Press `STOP` to exit the logs
- Unplug the esp32 the computer and plug it to any other power source
- If you need to update the configuration of the esp32, you can now do it wirelessly from the esp home interface

## Adminer
If you want to access the database you can go to `adminer.memoires-info.com` in your web browser (or the ip address of the computer that runs the docker)\
You can login with the following credentials:
- System: PostgreSQL
- Server: db
- Username: postgres
- Password: example
- Database: memoires-info

```bash
cd Interface
npm install
npm run dev
```
### Access
You can then access the web interface by going to `localhost:5174` in your web browser
![web interface](/assets/dashboard.png)
1 change: 1 addition & 0 deletions database/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
data
File renamed without changes.
37 changes: 0 additions & 37 deletions database/docker-compose.yml

This file was deleted.

59 changes: 59 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# Use postgres/example user/password credentials
version: '3.9'

services:
esphome:
image: esphome/esphome
volumes:
- ./esp32/config:/config
- /etc/localtime:/etc/localtime:ro
- /dev/ttyUSB0:/dev/ttyUSB0
privileged: true

db:
image: postgres
shm_size: 128mb
volumes:
- "./database/data:/var/lib/postgresql/data"
- "./database/db.sql:/docker-entrypoint-initdb.d/db.sql"
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: example
POSTGRES_DB: memoires-info

adminer:
image: adminer
depends_on:
- db

postg-rest:
image: postgrest/postgrest
ports:
- '3000:3000'
volumes:
- ./postgrest.conf:/etc/postgrest.conf
depends_on:
- db
command: postgrest /etc/postgrest.conf

php-fpm:
image: php:8-fpm
volumes:
- ./login:/var/www/memoires-info/php
depends_on:
- db

web:
image: nginx:latest
ports:
- '80:80'
volumes:
- ./Interface/dist:/var/www/memoires-info/html
- ./nginx.conf:/etc/nginx/conf.d/default.conf
- ./login:/var/www/memoires-info/php
depends_on:
- php-fpm
- postg-rest
- adminer
- esphome

4 changes: 2 additions & 2 deletions esp32/.gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
config/*.yaml
!config/secrets.example.yaml
config/.esphome/
config/secrets.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
wifi_ssid:
wifi_password:
# The url of the server to send the data to
webhook_url:
webhook_url: "http://postgrest.memoires-info.com/insert_data"
16 changes: 0 additions & 16 deletions esp32/docker-compose.yml

This file was deleted.

3 changes: 3 additions & 0 deletions login/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
JWT_SECRET=
POSTGREST_API=http://postg-rest:3000
DETAILED_ERRORS=false
File renamed without changes.
File renamed without changes.
File renamed without changes.
11 changes: 6 additions & 5 deletions login_login/login.http → login/login.http
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
### Authentificate as admin
# @no-cookie-jar
# @no-log
GET http://localhost:5173/login.php?username=toto&password=IamToto
GET http://login.memoires-info.com/login.php?username=admin&password=admin


### Create a new user "toto" with password "IamToto"
# @no-cookie-jar
# @no-log
# the password said here is the hash of "IamToto"
POST http://192.168.1.66:3000/users
POST http://postgrest.memoires-info.com/users
Authorization: Bearer
Content-Type: application/json

Expand All @@ -21,11 +21,12 @@ Content-Type: application/json
### Authentificate as toto
# @no-cookie-jar
# @no-log
GET http://localhost:8080/login.php?username=toto&password=IamToto
GET http://login.memoires-info.com/login.php?username=toto&password=IamToto


### Get the last 20 data entries
# @no-cookie-jar
# @no-log
GET http://192.168.1.66:3000/data?order=timestamp.desc,ip&limit=20
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoid2ViX3VzZXIiLCJpZCI6MTQsImV4cCI6MTcxMjYyMDgwMH0.pktJqmndIWsyPFcMXpiDwsLp_inQdu--ohNuQKx3fWc
GET http://postgrest.memoires-info.com/data?order=timestamp.desc,ip&limit=20
Authorization: Bearer

17 changes: 14 additions & 3 deletions login_login/public/login.php → login/public/login.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,24 @@
$dotenv->load(__DIR__ . '/../.env');

// Generate a token and use it to get the user
$token = JWT::encode(['role' => 'web_login', 'exp' => time() + 3], $_ENV['JWT_SECRET'], 'HS256');
$token = JWT::encode(['role' => 'web_login', 'exp' => time()], $_ENV['JWT_SECRET'], 'HS256');
$user = callAPI('GET', $_ENV['POSTGREST_API'] . "/users?username=eq.{$data['username']}&limit=1&select=password,id", [], ["Authorization: Bearer $token"]);

// Check if the answer is valid
if ($user === false || isset($user["message"]))
output(['error' => 'Unknown error'], 500);
if ($user === false)
output(['error' =>
$_ENV['DETAILED_ERRORS'] === 'true' ?
'Unable to connect to the API' :
'Unknown error'
], 500);
$user = json_decode($user, true);
if (isset($user["message"]))
output(['error' =>
$_ENV['DETAILED_ERRORS'] === 'true' ?
$user :
'Unknown error'
], 500);

if (empty($user))
output(['error' => 'Unknown user'], 401);
if (!password_verify($data['password'], $user[0]['password']))
Expand Down
2 changes: 0 additions & 2 deletions login_login/.env.example

This file was deleted.

Loading

0 comments on commit 9042cb9

Please sign in to comment.